-
Notifications
You must be signed in to change notification settings - Fork 137
/
types.go
2169 lines (1758 loc) Β· 54 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
/*
* Cadence - The resource-oriented smart contract programming language
*
* Copyright Flow Foundation
*
* 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 cadence
import (
"fmt"
"reflect"
"strings"
"sync"
"github.com/onflow/cadence/common"
"github.com/onflow/cadence/errors"
"github.com/onflow/cadence/interpreter"
"github.com/onflow/cadence/sema"
)
type Type interface {
isType()
ID() string
Equal(other Type) bool
}
// TypeID is a type which is only known by its type ID.
// This type should not be used when encoding values,
// and should only be used for decoding values that were encoded
// using an older format of the JSON encoding (<v0.3.0)
type TypeID common.TypeID
func (TypeID) isType() {}
func (t TypeID) ID() string {
return string(t)
}
func (t TypeID) Equal(other Type) bool {
return t == other
}
// OptionalType
type OptionalType struct {
Type Type
}
var _ Type = &OptionalType{}
func NewOptionalType(typ Type) *OptionalType {
return &OptionalType{Type: typ}
}
func NewMeteredOptionalType(gauge common.MemoryGauge, typ Type) *OptionalType {
common.UseMemory(gauge, common.CadenceOptionalTypeMemoryUsage)
return NewOptionalType(typ)
}
func (*OptionalType) isType() {}
func (t *OptionalType) ID() string {
return sema.FormatOptionalTypeID(t.Type.ID())
}
func (t *OptionalType) Equal(other Type) bool {
otherOptional, ok := other.(*OptionalType)
if !ok {
return false
}
return t.Type.Equal(otherOptional.Type)
}
// BytesType
type BytesType struct{}
var TheBytesType = BytesType{}
func (BytesType) isType() {}
func (BytesType) ID() string {
return "Bytes"
}
func (t BytesType) Equal(other Type) bool {
return t == other
}
// PrimitiveType
type PrimitiveType interpreter.PrimitiveStaticType
var _ Type = PrimitiveType(interpreter.PrimitiveStaticTypeUnknown)
func (p PrimitiveType) isType() {}
func (p PrimitiveType) ID() string {
return string(interpreter.PrimitiveStaticType(p).ID())
}
func (p PrimitiveType) Equal(other Type) bool {
otherP, ok := other.(PrimitiveType)
return ok && p == otherP
}
var VoidType = PrimitiveType(interpreter.PrimitiveStaticTypeVoid)
var AnyType = PrimitiveType(interpreter.PrimitiveStaticTypeAny)
var NeverType = PrimitiveType(interpreter.PrimitiveStaticTypeNever)
var AnyStructType = PrimitiveType(interpreter.PrimitiveStaticTypeAnyStruct)
var AnyResourceType = PrimitiveType(interpreter.PrimitiveStaticTypeAnyResource)
var AnyStructAttachmentType = PrimitiveType(interpreter.PrimitiveStaticTypeAnyStructAttachment)
var AnyResourceAttachmentType = PrimitiveType(interpreter.PrimitiveStaticTypeAnyResourceAttachment)
var HashableStructType = PrimitiveType(interpreter.PrimitiveStaticTypeHashableStruct)
var BoolType = PrimitiveType(interpreter.PrimitiveStaticTypeBool)
var AddressType = PrimitiveType(interpreter.PrimitiveStaticTypeAddress)
var StringType = PrimitiveType(interpreter.PrimitiveStaticTypeString)
var CharacterType = PrimitiveType(interpreter.PrimitiveStaticTypeCharacter)
var MetaType = PrimitiveType(interpreter.PrimitiveStaticTypeMetaType)
var BlockType = PrimitiveType(interpreter.PrimitiveStaticTypeBlock)
var NumberType = PrimitiveType(interpreter.PrimitiveStaticTypeNumber)
var SignedNumberType = PrimitiveType(interpreter.PrimitiveStaticTypeSignedNumber)
var IntegerType = PrimitiveType(interpreter.PrimitiveStaticTypeInteger)
var SignedIntegerType = PrimitiveType(interpreter.PrimitiveStaticTypeSignedInteger)
var FixedSizeUnsignedIntegerType = PrimitiveType(interpreter.PrimitiveStaticTypeFixedSizeUnsignedInteger)
var FixedPointType = PrimitiveType(interpreter.PrimitiveStaticTypeFixedPoint)
var SignedFixedPointType = PrimitiveType(interpreter.PrimitiveStaticTypeSignedFixedPoint)
var IntType = PrimitiveType(interpreter.PrimitiveStaticTypeInt)
var Int8Type = PrimitiveType(interpreter.PrimitiveStaticTypeInt8)
var Int16Type = PrimitiveType(interpreter.PrimitiveStaticTypeInt16)
var Int32Type = PrimitiveType(interpreter.PrimitiveStaticTypeInt32)
var Int64Type = PrimitiveType(interpreter.PrimitiveStaticTypeInt64)
var Int128Type = PrimitiveType(interpreter.PrimitiveStaticTypeInt128)
var Int256Type = PrimitiveType(interpreter.PrimitiveStaticTypeInt256)
var UIntType = PrimitiveType(interpreter.PrimitiveStaticTypeUInt)
var UInt8Type = PrimitiveType(interpreter.PrimitiveStaticTypeUInt8)
var UInt16Type = PrimitiveType(interpreter.PrimitiveStaticTypeUInt16)
var UInt32Type = PrimitiveType(interpreter.PrimitiveStaticTypeUInt32)
var UInt64Type = PrimitiveType(interpreter.PrimitiveStaticTypeUInt64)
var UInt128Type = PrimitiveType(interpreter.PrimitiveStaticTypeUInt128)
var UInt256Type = PrimitiveType(interpreter.PrimitiveStaticTypeUInt256)
var Word8Type = PrimitiveType(interpreter.PrimitiveStaticTypeWord8)
var Word16Type = PrimitiveType(interpreter.PrimitiveStaticTypeWord16)
var Word32Type = PrimitiveType(interpreter.PrimitiveStaticTypeWord32)
var Word64Type = PrimitiveType(interpreter.PrimitiveStaticTypeWord64)
var Word128Type = PrimitiveType(interpreter.PrimitiveStaticTypeWord128)
var Word256Type = PrimitiveType(interpreter.PrimitiveStaticTypeWord256)
var Fix64Type = PrimitiveType(interpreter.PrimitiveStaticTypeFix64)
var UFix64Type = PrimitiveType(interpreter.PrimitiveStaticTypeUFix64)
var PathType = PrimitiveType(interpreter.PrimitiveStaticTypePath)
var CapabilityPathType = PrimitiveType(interpreter.PrimitiveStaticTypeCapabilityPath)
var StoragePathType = PrimitiveType(interpreter.PrimitiveStaticTypeStoragePath)
var PublicPathType = PrimitiveType(interpreter.PrimitiveStaticTypePublicPath)
var PrivatePathType = PrimitiveType(interpreter.PrimitiveStaticTypePrivatePath)
var DeployedContractType = PrimitiveType(interpreter.PrimitiveStaticTypeDeployedContract)
var StorageCapabilityControllerType = PrimitiveType(interpreter.PrimitiveStaticTypeStorageCapabilityController)
var AccountCapabilityControllerType = PrimitiveType(interpreter.PrimitiveStaticTypeAccountCapabilityController)
var AccountType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount)
var Account_ContractsType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_Contracts)
var Account_KeysType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_Keys)
var Account_StorageType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_Storage)
var Account_InboxType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_Inbox)
var Account_CapabilitiesType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_Capabilities)
var Account_StorageCapabilitiesType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_StorageCapabilities)
var Account_AccountCapabilitiesType = PrimitiveType(interpreter.PrimitiveStaticTypeAccount_AccountCapabilities)
var MutateType = PrimitiveType(interpreter.PrimitiveStaticTypeMutate)
var InsertType = PrimitiveType(interpreter.PrimitiveStaticTypeInsert)
var RemoveType = PrimitiveType(interpreter.PrimitiveStaticTypeRemove)
var IdentityType = PrimitiveType(interpreter.PrimitiveStaticTypeIdentity)
var StorageType = PrimitiveType(interpreter.PrimitiveStaticTypeStorage)
var SaveValueType = PrimitiveType(interpreter.PrimitiveStaticTypeSaveValue)
var LoadValueType = PrimitiveType(interpreter.PrimitiveStaticTypeLoadValue)
var CopyValueType = PrimitiveType(interpreter.PrimitiveStaticTypeCopyValue)
var BorrowValueType = PrimitiveType(interpreter.PrimitiveStaticTypeBorrowValue)
var ContractsType = PrimitiveType(interpreter.PrimitiveStaticTypeContracts)
var AddContractType = PrimitiveType(interpreter.PrimitiveStaticTypeAddContract)
var UpdateContractType = PrimitiveType(interpreter.PrimitiveStaticTypeUpdateContract)
var RemoveContractType = PrimitiveType(interpreter.PrimitiveStaticTypeRemoveContract)
var KeysType = PrimitiveType(interpreter.PrimitiveStaticTypeKeys)
var AddKeyType = PrimitiveType(interpreter.PrimitiveStaticTypeAddKey)
var RevokeKeyType = PrimitiveType(interpreter.PrimitiveStaticTypeRevokeKey)
var InboxType = PrimitiveType(interpreter.PrimitiveStaticTypeInbox)
var PublishInboxCapabilityType = PrimitiveType(interpreter.PrimitiveStaticTypePublishInboxCapability)
var UnpublishInboxCapabilityType = PrimitiveType(interpreter.PrimitiveStaticTypeUnpublishInboxCapability)
var ClaimInboxCapabilityType = PrimitiveType(interpreter.PrimitiveStaticTypeClaimInboxCapability)
var CapabilitiesType = PrimitiveType(interpreter.PrimitiveStaticTypeCapabilities)
var StorageCapabilitiesType = PrimitiveType(interpreter.PrimitiveStaticTypeStorageCapabilities)
var AccountCapabilitiesType = PrimitiveType(interpreter.PrimitiveStaticTypeAccountCapabilities)
var PublishCapabilityType = PrimitiveType(interpreter.PrimitiveStaticTypePublishCapability)
var UnpublishCapabilityType = PrimitiveType(interpreter.PrimitiveStaticTypeUnpublishCapability)
var GetStorageCapabilityControllerType = PrimitiveType(interpreter.PrimitiveStaticTypeGetStorageCapabilityController)
var IssueStorageCapabilityControllerType = PrimitiveType(interpreter.PrimitiveStaticTypeIssueStorageCapabilityController)
var GetAccountCapabilityControllerType = PrimitiveType(interpreter.PrimitiveStaticTypeGetAccountCapabilityController)
var IssueAccountCapabilityControllerType = PrimitiveType(interpreter.PrimitiveStaticTypeIssueAccountCapabilityController)
var CapabilitiesMappingType = PrimitiveType(interpreter.PrimitiveStaticTypeCapabilitiesMapping)
var AccountMappingType = PrimitiveType(interpreter.PrimitiveStaticTypeAccountMapping)
type ArrayType interface {
Type
Element() Type
}
// VariableSizedArrayType
type VariableSizedArrayType struct {
ElementType Type
}
var _ Type = &VariableSizedArrayType{}
func NewVariableSizedArrayType(
elementType Type,
) *VariableSizedArrayType {
return &VariableSizedArrayType{ElementType: elementType}
}
func NewMeteredVariableSizedArrayType(
gauge common.MemoryGauge,
elementType Type,
) *VariableSizedArrayType {
common.UseMemory(gauge, common.CadenceVariableSizedArrayTypeMemoryUsage)
return NewVariableSizedArrayType(elementType)
}
func (*VariableSizedArrayType) isType() {}
func (t *VariableSizedArrayType) ID() string {
return sema.FormatVariableSizedTypeID(t.ElementType.ID())
}
func (t *VariableSizedArrayType) Element() Type {
return t.ElementType
}
func (t *VariableSizedArrayType) Equal(other Type) bool {
otherType, ok := other.(*VariableSizedArrayType)
if !ok {
return false
}
return t.ElementType.Equal(otherType.ElementType)
}
// ConstantSizedArrayType
type ConstantSizedArrayType struct {
ElementType Type
Size uint
}
var _ Type = &ConstantSizedArrayType{}
func NewConstantSizedArrayType(
size uint,
elementType Type,
) *ConstantSizedArrayType {
return &ConstantSizedArrayType{
Size: size,
ElementType: elementType,
}
}
func NewMeteredConstantSizedArrayType(
gauge common.MemoryGauge,
size uint,
elementType Type,
) *ConstantSizedArrayType {
common.UseMemory(gauge, common.CadenceConstantSizedArrayTypeMemoryUsage)
return NewConstantSizedArrayType(size, elementType)
}
func (*ConstantSizedArrayType) isType() {}
func (t *ConstantSizedArrayType) ID() string {
return sema.FormatConstantSizedTypeID(t.ElementType.ID(), int64(t.Size))
}
func (t *ConstantSizedArrayType) Element() Type {
return t.ElementType
}
func (t *ConstantSizedArrayType) Equal(other Type) bool {
otherType, ok := other.(*ConstantSizedArrayType)
if !ok {
return false
}
return t.ElementType.Equal(otherType.ElementType) &&
t.Size == otherType.Size
}
// DictionaryType
type DictionaryType struct {
KeyType Type
ElementType Type
}
var _ Type = &DictionaryType{}
func NewDictionaryType(
keyType Type,
elementType Type,
) *DictionaryType {
return &DictionaryType{
KeyType: keyType,
ElementType: elementType,
}
}
func NewMeteredDictionaryType(
gauge common.MemoryGauge,
keyType Type,
elementType Type,
) *DictionaryType {
common.UseMemory(gauge, common.CadenceDictionaryTypeMemoryUsage)
return NewDictionaryType(keyType, elementType)
}
func (*DictionaryType) isType() {}
func (t *DictionaryType) ID() string {
return sema.FormatDictionaryTypeID(
t.KeyType.ID(),
t.ElementType.ID(),
)
}
func (t *DictionaryType) Equal(other Type) bool {
otherType, ok := other.(*DictionaryType)
if !ok {
return false
}
return t.KeyType.Equal(otherType.KeyType) &&
t.ElementType.Equal(otherType.ElementType)
}
// InclusiveRangeType
type InclusiveRangeType struct {
ElementType Type
typeID string
}
var _ Type = &InclusiveRangeType{}
func NewInclusiveRangeType(
elementType Type,
) *InclusiveRangeType {
return &InclusiveRangeType{
ElementType: elementType,
}
}
func NewMeteredInclusiveRangeType(
gauge common.MemoryGauge,
elementType Type,
) *InclusiveRangeType {
common.UseMemory(gauge, common.CadenceInclusiveRangeTypeMemoryUsage)
return NewInclusiveRangeType(elementType)
}
func (*InclusiveRangeType) isType() {}
func (t *InclusiveRangeType) ID() string {
if t.typeID == "" {
t.typeID = fmt.Sprintf(
"InclusiveRange<%s>",
t.ElementType.ID(),
)
}
return t.typeID
}
func (t *InclusiveRangeType) Equal(other Type) bool {
otherType, ok := other.(*InclusiveRangeType)
if !ok {
return false
}
return t.ElementType.Equal(otherType.ElementType)
}
// Field
type Field struct {
Type Type
Identifier string
}
// Fields are always created in an array, which must be metered ahead of time.
// So no metering here.
func NewField(identifier string, typ Type) Field {
return Field{
Identifier: identifier,
Type: typ,
}
}
// SearchCompositeFieldTypeByName searches for the field with the given name in the composite type,
// and returns the type of the field, or nil if the field is not found.
//
// WARNING: This function performs a linear search, so is not efficient for accessing multiple fields.
// Prefer using CompositeFieldTypesMappedByName if you need to access multiple fields.
func SearchCompositeFieldTypeByName(compositeType CompositeType, fieldName string) Type {
fields := compositeType.compositeFields()
if fields == nil {
return nil
}
for _, field := range fields {
if field.Identifier == fieldName {
return field.Type
}
}
return nil
}
func CompositeFieldTypesMappedByName(compositeType CompositeType) map[string]Type {
fields := compositeType.compositeFields()
if fields == nil {
return nil
}
fieldsMap := make(map[string]Type, len(fields))
for _, field := range fields {
fieldsMap[field.Identifier] = field.Type
}
return fieldsMap
}
// SearchInterfaceFieldTypeByName searches for the field with the given name in the interface type,
// and returns the type of the field, or nil if the field is not found.
//
// WARNING: This function performs a linear search, so is not efficient for accessing multiple fields.
// Prefer using InterfaceFieldTypesMappedByName if you need to access multiple fields.
func SearchInterfaceFieldTypeByName(interfaceType InterfaceType, fieldName string) Type {
fields := interfaceType.interfaceFields()
if fields == nil {
return nil
}
for _, field := range fields {
if field.Identifier == fieldName {
return field.Type
}
}
return nil
}
func InterfaceFieldTypesMappedByName(interfaceType InterfaceType) map[string]Type {
fields := interfaceType.interfaceFields()
if fields == nil {
return nil
}
fieldsMap := make(map[string]Type, len(fields))
for _, field := range fields {
fieldsMap[field.Identifier] = field.Type
}
return fieldsMap
}
// DecodeFields decodes a HasFields into a struct
func DecodeFields(composite Composite, s interface{}) error {
v := reflect.ValueOf(s)
if !v.IsValid() || v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
return fmt.Errorf("s must be a pointer to a struct")
}
v = v.Elem()
targetType := v.Type()
_, err := decodeStructInto(v, targetType, composite)
if err != nil {
return err
}
return nil
}
func decodeFieldValue(targetType reflect.Type, value Value) (reflect.Value, error) {
var decodeSpecialFieldFunc func(p reflect.Type, value Value) (reflect.Value, error)
switch targetType.Kind() {
case reflect.Ptr:
decodeSpecialFieldFunc = decodeOptional
case reflect.Map:
decodeSpecialFieldFunc = decodeDict
case reflect.Array, reflect.Slice:
decodeSpecialFieldFunc = decodeSlice
case reflect.Struct:
if !targetType.Implements(reflect.TypeOf((*Value)(nil)).Elem()) {
decodeSpecialFieldFunc = decodeStruct
}
}
var reflectedValue reflect.Value
if decodeSpecialFieldFunc != nil {
var err error
reflectedValue, err = decodeSpecialFieldFunc(targetType, value)
if err != nil {
ty := value.Type()
if ty == nil {
return reflect.Value{}, fmt.Errorf(
"cannot convert Cadence value to Go type %s: %w",
targetType,
err,
)
} else {
return reflect.Value{}, fmt.Errorf(
"cannot convert Cadence value of type %s to Go type %s: %w",
ty.ID(),
targetType,
err,
)
}
}
} else {
reflectedValue = reflect.ValueOf(value)
}
if !reflectedValue.CanConvert(targetType) {
ty := value.Type()
if ty == nil {
return reflect.Value{}, fmt.Errorf(
"cannot convert Cadence value to Go type %s",
targetType,
)
} else {
return reflect.Value{}, fmt.Errorf(
"cannot convert Cadence value of type %s to Go type %s",
ty.ID(),
targetType,
)
}
}
return reflectedValue.Convert(targetType), nil
}
func decodeOptional(pointerTargetType reflect.Type, cadenceValue Value) (reflect.Value, error) {
cadenceOptional, ok := cadenceValue.(Optional)
if !ok {
return reflect.Value{}, fmt.Errorf("field is not an optional")
}
// If Cadence optional is nil, skip and default the field to Go nil
cadenceInnerValue := cadenceOptional.Value
if cadenceInnerValue == nil {
return reflect.Zero(pointerTargetType), nil
}
// Create a new pointer
newPtr := reflect.New(pointerTargetType.Elem())
innerValue, err := decodeFieldValue(
pointerTargetType.Elem(),
cadenceInnerValue,
)
if err != nil {
return reflect.Value{}, fmt.Errorf(
"cannot decode optional value: %w",
err,
)
}
newPtr.Elem().Set(innerValue)
return newPtr, nil
}
func decodeDict(mapTargetType reflect.Type, cadenceValue Value) (reflect.Value, error) {
cadenceDictionary, ok := cadenceValue.(Dictionary)
if !ok {
return reflect.Value{}, fmt.Errorf(
"cannot decode non-Cadence dictionary %T to Go map",
cadenceValue,
)
}
keyTargetType := mapTargetType.Key()
valueTargetType := mapTargetType.Elem()
mapValue := reflect.MakeMap(mapTargetType)
for _, pair := range cadenceDictionary.Pairs {
key, err := decodeFieldValue(keyTargetType, pair.Key)
if err != nil {
return reflect.Value{}, fmt.Errorf(
"cannot decode dictionary key: %w",
err,
)
}
value, err := decodeFieldValue(valueTargetType, pair.Value)
if err != nil {
return reflect.Value{}, fmt.Errorf(
"cannot decode dictionary value: %w",
err,
)
}
mapValue.SetMapIndex(key, value)
}
return mapValue, nil
}
func decodeSlice(arrayTargetType reflect.Type, cadenceValue Value) (reflect.Value, error) {
cadenceArray, ok := cadenceValue.(Array)
if !ok {
return reflect.Value{}, fmt.Errorf(
"cannot decode non-Cadence array %T to Go slice",
cadenceValue,
)
}
elementTargetType := arrayTargetType.Elem()
var arrayValue reflect.Value
cadenceConstantSizeArrayType, ok := cadenceArray.ArrayType.(*ConstantSizedArrayType)
if ok {
// If the Cadence array is constant-sized, create a Go array
size := int(cadenceConstantSizeArrayType.Size)
arrayValue = reflect.New(reflect.ArrayOf(size, elementTargetType)).Elem()
} else {
// If the Cadence array is not constant-sized, create a Go slice
size := len(cadenceArray.Values)
arrayValue = reflect.MakeSlice(arrayTargetType, size, size)
}
for i, cadenceElement := range cadenceArray.Values {
elementValue, err := decodeFieldValue(elementTargetType, cadenceElement)
if err != nil {
return reflect.Value{}, fmt.Errorf(
"cannot decode array element %d: %w",
i,
err,
)
}
arrayValue.Index(i).Set(elementValue)
}
return arrayValue, nil
}
func decodeStruct(structTargetType reflect.Type, cadenceValue Value) (reflect.Value, error) {
structValue := reflect.New(structTargetType)
return decodeStructInto(structValue.Elem(), structTargetType, cadenceValue)
}
func decodeStructInto(
structValue reflect.Value,
structTargetType reflect.Type,
cadenceValue Value,
) (reflect.Value, error) {
composite, ok := cadenceValue.(Composite)
if !ok {
return reflect.Value{}, fmt.Errorf(
"cannot decode non-Cadence composite %T to Go struct",
cadenceValue,
)
}
fieldsMap := FieldsMappedByName(composite)
for i := 0; i < structValue.NumField(); i++ {
structField := structTargetType.Field(i)
tag := structField.Tag
fieldValue := structValue.Field(i)
cadenceFieldNameTag := tag.Get("cadence")
if cadenceFieldNameTag == "" {
continue
}
if !fieldValue.IsValid() || !fieldValue.CanSet() {
return reflect.Value{}, fmt.Errorf("cannot set field %s", structField.Name)
}
value := fieldsMap[cadenceFieldNameTag]
if value == nil {
return reflect.Value{}, fmt.Errorf("%s field not found", cadenceFieldNameTag)
}
converted, err := decodeFieldValue(fieldValue.Type(), value)
if err != nil {
return reflect.Value{}, fmt.Errorf(
"cannot convert Cadence field %s into Go field %s: %w",
cadenceFieldNameTag,
structField.Name,
err,
)
}
fieldValue.Set(converted)
}
return structValue, nil
}
// Parameter
type Parameter struct {
Type Type
Label string
Identifier string
}
func NewParameter(
label string,
identifier string,
typ Type,
) Parameter {
return Parameter{
Label: label,
Identifier: identifier,
Type: typ,
}
}
// TypeParameter
type TypeParameter struct {
Name string
TypeBound Type
}
func NewTypeParameter(
name string,
typeBound Type,
) TypeParameter {
return TypeParameter{
Name: name,
TypeBound: typeBound,
}
}
// CompositeType
type CompositeType interface {
Type
isCompositeType()
compositeFields() []Field
setCompositeFields([]Field)
CompositeTypeLocation() common.Location
CompositeTypeQualifiedIdentifier() string
CompositeInitializers() [][]Parameter
SearchFieldByName(fieldName string) Type
FieldsMappedByName() map[string]Type
}
// linked in by packages that need access to CompositeType.setCompositeFields,
// e.g. JSON and CCF codecs
func setCompositeTypeFields(compositeType CompositeType, fields []Field) { //nolint:unused
compositeType.setCompositeFields(fields)
}
// linked in by packages that need access to CompositeType.compositeFields,
// e.g. JSON and CCF codecs
func getCompositeTypeFields(compositeType CompositeType) []Field { //nolint:unused
return compositeType.compositeFields()
}
// StructType
type StructType struct {
Location common.Location
QualifiedIdentifier string
fields []Field
Initializers [][]Parameter
}
func NewStructType(
location common.Location,
qualifiedIdentifier string,
fields []Field,
initializers [][]Parameter,
) *StructType {
return &StructType{
Location: location,
QualifiedIdentifier: qualifiedIdentifier,
fields: fields,
Initializers: initializers,
}
}
func NewMeteredStructType(
gauge common.MemoryGauge,
location common.Location,
qualifiedIdentifier string,
fields []Field,
initializers [][]Parameter,
) *StructType {
common.UseMemory(gauge, common.CadenceStructTypeMemoryUsage)
return NewStructType(location, qualifiedIdentifier, fields, initializers)
}
func (*StructType) isType() {}
func (t *StructType) ID() string {
return string(common.NewTypeIDFromQualifiedName(nil, t.Location, t.QualifiedIdentifier))
}
func (*StructType) isCompositeType() {}
func (t *StructType) CompositeTypeLocation() common.Location {
return t.Location
}
func (t *StructType) CompositeTypeQualifiedIdentifier() string {
return t.QualifiedIdentifier
}
func (t *StructType) compositeFields() []Field {
return t.fields
}
func (t *StructType) setCompositeFields(fields []Field) {
t.fields = fields
}
func (t *StructType) CompositeInitializers() [][]Parameter {
return t.Initializers
}
func (t *StructType) Equal(other Type) bool {
otherType, ok := other.(*StructType)
if !ok {
return false
}
return t.Location == otherType.Location &&
t.QualifiedIdentifier == otherType.QualifiedIdentifier
}
func (t *StructType) SearchFieldByName(fieldName string) Type {
return SearchCompositeFieldTypeByName(t, fieldName)
}
func (t *StructType) FieldsMappedByName() map[string]Type {
return CompositeFieldTypesMappedByName(t)
}
// ResourceType
type ResourceType struct {
Location common.Location
QualifiedIdentifier string
fields []Field
Initializers [][]Parameter
}
func NewResourceType(
location common.Location,
qualifiedIdentifier string,
fields []Field,
initializers [][]Parameter,
) *ResourceType {
return &ResourceType{
Location: location,
QualifiedIdentifier: qualifiedIdentifier,
fields: fields,
Initializers: initializers,
}
}
func NewMeteredResourceType(
gauge common.MemoryGauge,
location common.Location,
qualifiedIdentifier string,
fields []Field,
initializers [][]Parameter,
) *ResourceType {
common.UseMemory(gauge, common.CadenceResourceTypeMemoryUsage)
return NewResourceType(location, qualifiedIdentifier, fields, initializers)
}
func (*ResourceType) isType() {}
func (t *ResourceType) ID() string {
return string(common.NewTypeIDFromQualifiedName(nil, t.Location, t.QualifiedIdentifier))
}
func (*ResourceType) isCompositeType() {}
func (t *ResourceType) CompositeTypeLocation() common.Location {
return t.Location
}
func (t *ResourceType) CompositeTypeQualifiedIdentifier() string {
return t.QualifiedIdentifier
}
func (t *ResourceType) compositeFields() []Field {
return t.fields
}
func (t *ResourceType) setCompositeFields(fields []Field) {
t.fields = fields
}
func (t *ResourceType) CompositeInitializers() [][]Parameter {
return t.Initializers
}
func (t *ResourceType) Equal(other Type) bool {
otherType, ok := other.(*ResourceType)
if !ok {
return false
}
return t.Location == otherType.Location &&
t.QualifiedIdentifier == otherType.QualifiedIdentifier
}
func (t *ResourceType) SearchFieldByName(fieldName string) Type {
return SearchCompositeFieldTypeByName(t, fieldName)
}
func (t *ResourceType) FieldsMappedByName() map[string]Type {
return CompositeFieldTypesMappedByName(t)
}
// AttachmentType
type AttachmentType struct {
Location common.Location
BaseType Type
QualifiedIdentifier string
fields []Field
Initializers [][]Parameter
}
func NewAttachmentType(
location common.Location,
qualifiedIdentifier string,
baseType Type,
fields []Field,
initializers [][]Parameter,
) *AttachmentType {
return &AttachmentType{
Location: location,
BaseType: baseType,
QualifiedIdentifier: qualifiedIdentifier,
fields: fields,
Initializers: initializers,
}
}
func NewMeteredAttachmentType(
gauge common.MemoryGauge,
location common.Location,
qualifiedIdentifier string,
baseType Type,
fields []Field,
initializers [][]Parameter,
) *AttachmentType {