/
type.go
7387 lines (6076 loc) Β· 182 KB
/
type.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 Dapper Labs, Inc.
*
* 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 sema
import (
"fmt"
"math"
"math/big"
"strings"
"sync"
"github.com/onflow/cadence/fixedpoint"
"github.com/onflow/cadence/runtime/ast"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/cadence/runtime/errors"
)
const TypeIDSeparator = '.'
func qualifiedIdentifier(identifier string, containerType Type) string {
if containerType == nil {
return identifier
}
// Gather all identifiers: this, parent, grand-parent, etc.
const level = 0
identifiers, bufSize := containerTypeNames(containerType, level+1)
identifiers[level] = identifier
bufSize += len(identifier)
// Append all identifiers, in reverse order
var sb strings.Builder
// Grow the buffer at once.
//
// bytes needed for separator '.'
// i.e: 1 x (length of identifiers - 1)
bufSize += len(identifiers) - 1
sb.Grow(bufSize)
for i := len(identifiers) - 1; i >= 0; i-- {
sb.WriteString(identifiers[i])
if i != 0 {
sb.WriteByte(TypeIDSeparator)
}
}
return sb.String()
}
func containerTypeNames(typ Type, level int) (typeNames []string, bufSize int) {
if typ == nil {
return make([]string, level), 0
}
var typeName string
var containerType Type
switch typedContainerType := typ.(type) {
case *InterfaceType:
typeName = typedContainerType.Identifier
containerType = typedContainerType.containerType
case *CompositeType:
typeName = typedContainerType.Identifier
containerType = typedContainerType.containerType
default:
panic(errors.NewUnreachableError())
}
typeNames, bufSize = containerTypeNames(containerType, level+1)
typeNames[level] = typeName
bufSize += len(typeName)
return typeNames, bufSize
}
type TypeID = common.TypeID
type Type interface {
IsType()
ID() TypeID
Tag() TypeTag
String() string
QualifiedString() string
Equal(other Type) bool
// IsResourceType returns true if the type is itself a resource (a `CompositeType` with resource kind),
// or it contains a resource type (e.g. for optionals, arrays, dictionaries, etc.)
IsResourceType() bool
// IsInvalidType returns true if the type is itself the invalid type (see `InvalidType`),
// or it contains an invalid type (e.g. for optionals, arrays, dictionaries, etc.)
IsInvalidType() bool
// IsStorable returns true if the type is allowed to be a stored,
// e.g. in a field of a composite type.
//
// The check if the type is storable is recursive,
// the results parameter prevents cycles:
// it is checked at the start of the recursively called function,
// and pre-set before a recursive call.
IsStorable(results map[*Member]bool) bool
// IsExportable returns true if a value of this type can be exported.
//
// The check if the type is exportable is recursive,
// the results parameter prevents cycles:
// it is checked at the start of the recursively called function,
// and pre-set before a recursive call.
IsExportable(results map[*Member]bool) bool
// IsImportable returns true if values of the type can be imported to a program as arguments
IsImportable(results map[*Member]bool) bool
// IsEquatable returns true if values of the type can be equated
IsEquatable() bool
// IsComparable returns true if values of the type can be compared
IsComparable() bool
TypeAnnotationState() TypeAnnotationState
RewriteWithRestrictedTypes() (result Type, rewritten bool)
// Unify attempts to unify the given type with this type, i.e., resolve type parameters
// in generic types (see `GenericType`) using the given type parameters.
//
// For a generic type, unification assigns a given type with a type parameter.
//
// If the type parameter has not been previously unified with a type,
// through an explicitly provided type argument in an invocation
// or through a previous unification, the type parameter is assigned the given type.
//
// If the type parameter has already been previously unified with a type,
// the type parameter's unified .
//
// The boolean return value indicates if a generic type was encountered during unification.
// For primitives (e.g. `Int`, `String`, etc.) it would be false, as .
// For types with nested types (e.g. optionals, arrays, and dictionaries)
// the result is the successful unification of the inner types.
//
// The boolean return value does *not* indicate if unification succeeded or not.
//
Unify(
other Type,
typeParameters *TypeParameterTypeOrderedMap,
report func(err error),
outerRange ast.Range,
) bool
// Resolve returns a type that is free of generic types (see `GenericType`),
// i.e. it resolves the type parameters in generic types given the type parameter
// unifications of `typeParameters`.
//
// If resolution fails, it returns `nil`.
//
Resolve(typeArguments *TypeParameterTypeOrderedMap) Type
GetMembers() map[string]MemberResolver
}
// ValueIndexableType is a type which can be indexed into using a value
type ValueIndexableType interface {
Type
isValueIndexableType() bool
AllowsValueIndexingAssignment() bool
ElementType(isAssignment bool) Type
IndexingType() Type
}
// TypeIndexableType is a type which can be indexed into using a type
type TypeIndexableType interface {
Type
isTypeIndexableType() bool
IsValidIndexingType(indexingType Type) bool
TypeIndexingElementType(indexingType Type) Type
}
type MemberResolver struct {
Resolve func(
memoryGauge common.MemoryGauge,
identifier string,
targetRange ast.Range,
report func(error),
) *Member
Kind common.DeclarationKind
Mutating bool
}
// ContainedType is a type which might have a container type
type ContainedType interface {
Type
GetContainerType() Type
SetContainerType(containerType Type)
}
// ContainerType is a type which might have nested types
type ContainerType interface {
Type
IsContainerType() bool
GetNestedTypes() *StringTypeOrderedMap
}
func VisitThisAndNested(t Type, visit func(ty Type)) {
visit(t)
containerType, ok := t.(ContainerType)
if !ok || !containerType.IsContainerType() {
return
}
containerType.GetNestedTypes().Foreach(func(_ string, nestedType Type) {
VisitThisAndNested(nestedType, visit)
})
}
func TypeActivationNestedType(typeActivation *VariableActivation, qualifiedIdentifier string) Type {
typeIDComponents := strings.Split(qualifiedIdentifier, string(TypeIDSeparator))
rootTypeName := typeIDComponents[0]
variable := typeActivation.Find(rootTypeName)
if variable == nil {
return nil
}
ty := variable.Type
// Traverse nested types until the leaf type
for i := 1; i < len(typeIDComponents); i++ {
containerType, ok := ty.(ContainerType)
if !ok || !containerType.IsContainerType() {
return nil
}
typeIDComponent := typeIDComponents[i]
ty, ok = containerType.GetNestedTypes().Get(typeIDComponent)
if !ok {
return nil
}
}
return ty
}
// CompositeKindedType is a type which has a composite kind
type CompositeKindedType interface {
Type
GetCompositeKind() common.CompositeKind
}
// LocatedType is a type which has a location
type LocatedType interface {
Type
GetLocation() common.Location
}
// ParameterizedType is a type which might have type parameters
type ParameterizedType interface {
Type
TypeParameters() []*TypeParameter
Instantiate(typeArguments []Type, report func(err error)) Type
BaseType() Type
TypeArguments() []Type
}
func MustInstantiate(t ParameterizedType, typeArguments ...Type) Type {
return t.Instantiate(
typeArguments,
func(err error) {
panic(errors.NewUnexpectedErrorFromCause(err))
},
)
}
// TypeAnnotation
type TypeAnnotation struct {
Type Type
IsResource bool
}
func (a TypeAnnotation) TypeAnnotationState() TypeAnnotationState {
if a.Type.IsInvalidType() {
return TypeAnnotationStateValid
}
innerState := a.Type.TypeAnnotationState()
if innerState != TypeAnnotationStateValid {
return innerState
}
isResourceType := a.Type.IsResourceType()
switch {
case isResourceType && !a.IsResource:
return TypeAnnotationStateMissingResourceAnnotation
case !isResourceType && a.IsResource:
return TypeAnnotationStateInvalidResourceAnnotation
default:
return TypeAnnotationStateValid
}
}
func (a TypeAnnotation) String() string {
if a.IsResource {
return fmt.Sprintf(
"%s%s",
common.CompositeKindResource.Annotation(),
a.Type,
)
} else {
return fmt.Sprint(a.Type)
}
}
func (a TypeAnnotation) QualifiedString() string {
qualifiedString := a.Type.QualifiedString()
if a.IsResource {
return fmt.Sprintf(
"%s%s",
common.CompositeKindResource.Annotation(),
qualifiedString,
)
} else {
return fmt.Sprint(qualifiedString)
}
}
func (a TypeAnnotation) Equal(other TypeAnnotation) bool {
return a.IsResource == other.IsResource &&
a.Type.Equal(other.Type)
}
func NewTypeAnnotation(ty Type) TypeAnnotation {
return TypeAnnotation{
IsResource: ty.IsResourceType(),
Type: ty,
}
}
// isInstance
const IsInstanceFunctionName = "isInstance"
var IsInstanceFunctionType = &FunctionType{
Parameters: []Parameter{
{
Label: ArgumentLabelNotRequired,
Identifier: "type",
TypeAnnotation: NewTypeAnnotation(
MetaType,
),
},
},
ReturnTypeAnnotation: NewTypeAnnotation(
BoolType,
),
}
const isInstanceFunctionDocString = `
Returns true if the object conforms to the given type at runtime
`
// getType
const GetTypeFunctionName = "getType"
var GetTypeFunctionType = &FunctionType{
ReturnTypeAnnotation: NewTypeAnnotation(
MetaType,
),
}
const getTypeFunctionDocString = `
Returns the type of the value
`
// toString
const ToStringFunctionName = "toString"
var ToStringFunctionType = &FunctionType{
ReturnTypeAnnotation: NewTypeAnnotation(
StringType,
),
}
const toStringFunctionDocString = `
A textual representation of this object
`
// fromString
const FromStringFunctionName = "fromString"
func FromStringFunctionDocstring(ty Type) string {
builder := new(strings.Builder)
builder.WriteString(
fmt.Sprintf(
"Attempts to parse %s from a string. Returns `nil` on overflow or invalid input. Whitespace or invalid digits will return a nil value.\n",
ty.String(),
))
if IsSameTypeKind(ty, FixedPointType) {
builder.WriteString(
`Both decimal and fractional components must be supplied. For instance, both "0." and ".1" are invalid string representations, but "0.1" is accepted.\n`,
)
}
if IsSameTypeKind(ty, SignedIntegerType) || IsSameTypeKind(ty, SignedFixedPointType) {
builder.WriteString(
"The string may optionally begin with a sign prefix of '-' or '+'.\n",
)
}
return builder.String()
}
func FromStringFunctionType(ty Type) *FunctionType {
return &FunctionType{
Parameters: []Parameter{
{
Label: ArgumentLabelNotRequired,
Identifier: "input",
TypeAnnotation: NewTypeAnnotation(StringType),
},
},
ReturnTypeAnnotation: NewTypeAnnotation(
&OptionalType{
Type: ty,
},
),
}
}
// fromBigEndianBytes
const FromBigEndianBytesFunctionName = "fromBigEndianBytes"
func FromBigEndianBytesFunctionDocstring(ty Type) string {
return fmt.Sprintf(
"Attempts to parse %s from a big-endian byte representation. Returns `nil` on invalid input.",
ty.String(),
)
}
func FromBigEndianBytesFunctionType(ty Type) *FunctionType {
return &FunctionType{
Parameters: []Parameter{
{
Label: ArgumentLabelNotRequired,
Identifier: "bytes",
TypeAnnotation: NewTypeAnnotation(ByteArrayType),
},
},
ReturnTypeAnnotation: NewTypeAnnotation(
&OptionalType{
Type: ty,
},
),
}
}
// toBigEndianBytes
const ToBigEndianBytesFunctionName = "toBigEndianBytes"
var toBigEndianBytesFunctionType = &FunctionType{
ReturnTypeAnnotation: NewTypeAnnotation(
ByteArrayType,
),
}
const toBigEndianBytesFunctionDocString = `
Returns an array containing the big-endian byte representation of the number
`
func withBuiltinMembers(ty Type, members map[string]MemberResolver) map[string]MemberResolver {
if members == nil {
members = map[string]MemberResolver{}
}
// All types have a predeclared member `fun isInstance(_ type: Type): Bool`
members[IsInstanceFunctionName] = MemberResolver{
Kind: common.DeclarationKindFunction,
Resolve: func(memoryGauge common.MemoryGauge, identifier string, _ ast.Range, _ func(error)) *Member {
return NewPublicFunctionMember(
memoryGauge,
ty,
identifier,
IsInstanceFunctionType,
isInstanceFunctionDocString,
)
},
}
// All types have a predeclared member `fun getType(): Type`
members[GetTypeFunctionName] = MemberResolver{
Kind: common.DeclarationKindFunction,
Resolve: func(memoryGauge common.MemoryGauge, identifier string, _ ast.Range, _ func(error)) *Member {
return NewPublicFunctionMember(
memoryGauge,
ty,
identifier,
GetTypeFunctionType,
getTypeFunctionDocString,
)
},
}
// All number types, addresses, and path types have a `toString` function
if IsSubType(ty, NumberType) || IsSubType(ty, TheAddressType) || IsSubType(ty, PathType) {
members[ToStringFunctionName] = MemberResolver{
Kind: common.DeclarationKindFunction,
Resolve: func(memoryGauge common.MemoryGauge, identifier string, _ ast.Range, _ func(error)) *Member {
return NewPublicFunctionMember(
memoryGauge,
ty,
identifier,
ToStringFunctionType,
toStringFunctionDocString,
)
},
}
}
// All number types have a `toBigEndianBytes` function
if IsSubType(ty, NumberType) {
members[ToBigEndianBytesFunctionName] = MemberResolver{
Kind: common.DeclarationKindFunction,
Resolve: func(memoryGauge common.MemoryGauge, identifier string, _ ast.Range, _ func(error)) *Member {
return NewPublicFunctionMember(
memoryGauge,
ty,
identifier,
toBigEndianBytesFunctionType,
toBigEndianBytesFunctionDocString,
)
},
}
}
return members
}
// OptionalType represents the optional variant of another type
type OptionalType struct {
Type Type
memberResolvers map[string]MemberResolver
memberResolversOnce sync.Once
}
var _ Type = &OptionalType{}
func NewOptionalType(memoryGauge common.MemoryGauge, typ Type) *OptionalType {
common.UseMemory(memoryGauge, common.OptionalSemaTypeMemoryUsage)
return &OptionalType{
Type: typ,
}
}
func (*OptionalType) IsType() {}
func (t *OptionalType) Tag() TypeTag {
if t.Type == NeverType {
return NilTypeTag
}
return t.Type.Tag().Or(NilTypeTag)
}
func (t *OptionalType) String() string {
if t.Type == nil {
return "optional"
}
return fmt.Sprintf("%s?", t.Type)
}
func (t *OptionalType) QualifiedString() string {
if t.Type == nil {
return "optional"
}
return fmt.Sprintf("%s?", t.Type.QualifiedString())
}
func OptionalTypeID(elementTypeID TypeID) TypeID {
return TypeID(fmt.Sprintf("%s?", elementTypeID))
}
func (t *OptionalType) ID() TypeID {
return OptionalTypeID(t.Type.ID())
}
func (t *OptionalType) Equal(other Type) bool {
otherOptional, ok := other.(*OptionalType)
if !ok {
return false
}
return t.Type.Equal(otherOptional.Type)
}
func (t *OptionalType) IsResourceType() bool {
return t.Type.IsResourceType()
}
func (t *OptionalType) IsInvalidType() bool {
return t.Type.IsInvalidType()
}
func (t *OptionalType) IsStorable(results map[*Member]bool) bool {
return t.Type.IsStorable(results)
}
func (t *OptionalType) IsExportable(results map[*Member]bool) bool {
return t.Type.IsExportable(results)
}
func (t *OptionalType) IsImportable(results map[*Member]bool) bool {
return t.Type.IsImportable(results)
}
func (t *OptionalType) IsEquatable() bool {
return t.Type.IsEquatable()
}
func (*OptionalType) IsComparable() bool {
return false
}
func (t *OptionalType) TypeAnnotationState() TypeAnnotationState {
return t.Type.TypeAnnotationState()
}
func (t *OptionalType) RewriteWithRestrictedTypes() (Type, bool) {
rewrittenType, rewritten := t.Type.RewriteWithRestrictedTypes()
if rewritten {
return &OptionalType{
Type: rewrittenType,
}, true
} else {
return t, false
}
}
func (t *OptionalType) Unify(
other Type,
typeParameters *TypeParameterTypeOrderedMap,
report func(err error),
outerRange ast.Range,
) bool {
otherOptional, ok := other.(*OptionalType)
if !ok {
return false
}
return t.Type.Unify(otherOptional.Type, typeParameters, report, outerRange)
}
func (t *OptionalType) Resolve(typeArguments *TypeParameterTypeOrderedMap) Type {
newInnerType := t.Type.Resolve(typeArguments)
if newInnerType == nil {
return nil
}
return &OptionalType{
Type: newInnerType,
}
}
const optionalTypeMapFunctionDocString = `
Returns an optional of the result of calling the given function
with the value of this optional when it is not nil.
Returns nil if this optional is nil
`
const OptionalTypeMapFunctionName = "map"
func (t *OptionalType) GetMembers() map[string]MemberResolver {
t.initializeMembers()
return t.memberResolvers
}
func (t *OptionalType) initializeMembers() {
t.memberResolversOnce.Do(func() {
t.memberResolvers = withBuiltinMembers(t, map[string]MemberResolver{
OptionalTypeMapFunctionName: {
Kind: common.DeclarationKindFunction,
Resolve: func(memoryGauge common.MemoryGauge, identifier string, targetRange ast.Range, report func(error)) *Member {
// It's invalid for an optional of a resource to have a `map` function
if t.Type.IsResourceType() {
report(
&InvalidResourceOptionalMemberError{
Name: identifier,
DeclarationKind: common.DeclarationKindFunction,
Range: targetRange,
},
)
}
return NewPublicFunctionMember(
memoryGauge,
t,
identifier,
OptionalTypeMapFunctionType(t.Type),
optionalTypeMapFunctionDocString,
)
},
},
})
})
}
func OptionalTypeMapFunctionType(typ Type) *FunctionType {
typeParameter := &TypeParameter{
Name: "T",
}
resultType := &GenericType{
TypeParameter: typeParameter,
}
return &FunctionType{
TypeParameters: []*TypeParameter{
typeParameter,
},
Parameters: []Parameter{
{
Label: ArgumentLabelNotRequired,
Identifier: "transform",
TypeAnnotation: NewTypeAnnotation(
&FunctionType{
Parameters: []Parameter{
{
Label: ArgumentLabelNotRequired,
Identifier: "value",
TypeAnnotation: NewTypeAnnotation(typ),
},
},
ReturnTypeAnnotation: NewTypeAnnotation(
resultType,
),
},
),
},
},
ReturnTypeAnnotation: NewTypeAnnotation(
&OptionalType{
Type: resultType,
},
),
}
}
// GenericType
type GenericType struct {
TypeParameter *TypeParameter
}
var _ Type = &GenericType{}
func (*GenericType) IsType() {}
func (t *GenericType) Tag() TypeTag {
return GenericTypeTag
}
func (t *GenericType) String() string {
return t.TypeParameter.Name
}
func (t *GenericType) QualifiedString() string {
return t.TypeParameter.Name
}
func (t *GenericType) ID() TypeID {
return TypeID(t.TypeParameter.Name)
}
func (t *GenericType) Equal(other Type) bool {
otherType, ok := other.(*GenericType)
if !ok {
return false
}
return t.TypeParameter == otherType.TypeParameter
}
func (*GenericType) IsResourceType() bool {
return false
}
func (*GenericType) IsInvalidType() bool {
return false
}
func (*GenericType) IsStorable(_ map[*Member]bool) bool {
return false
}
func (*GenericType) IsExportable(_ map[*Member]bool) bool {
return false
}
func (t *GenericType) IsImportable(_ map[*Member]bool) bool {
return false
}
func (*GenericType) IsEquatable() bool {
return false
}
func (*GenericType) IsComparable() bool {
return false
}
func (*GenericType) TypeAnnotationState() TypeAnnotationState {
return TypeAnnotationStateValid
}
func (t *GenericType) RewriteWithRestrictedTypes() (result Type, rewritten bool) {
return t, false
}
func (t *GenericType) Unify(
other Type,
typeParameters *TypeParameterTypeOrderedMap,
report func(err error),
outerRange ast.Range,
) bool {
if unifiedType, ok := typeParameters.Get(t.TypeParameter); ok {
// If the type parameter is already unified with a type argument
// (either explicit by a type argument, or implicit through an argument's type),
// check that this argument's type matches the unified type
if !other.Equal(unifiedType) {
report(
&TypeParameterTypeMismatchError{
TypeParameter: t.TypeParameter,
ExpectedType: unifiedType,
ActualType: other,
Range: outerRange,
},
)
}
} else {
// If the type parameter is not yet unified to a type argument, unify it.
typeParameters.Set(t.TypeParameter, other)
// If the type parameter corresponding to the type argument has a type bound,
// then check that the argument's type is a subtype of the type bound.
err := t.TypeParameter.checkTypeBound(other, outerRange)
if err != nil {
report(err)
}
}
return true
}
func (t *GenericType) Resolve(typeArguments *TypeParameterTypeOrderedMap) Type {
ty, ok := typeArguments.Get(t.TypeParameter)
if !ok {
return nil
}
return ty
}
func (t *GenericType) GetMembers() map[string]MemberResolver {
return withBuiltinMembers(t, nil)
}
// IntegerRangedType
type IntegerRangedType interface {
Type
MinInt() *big.Int
MaxInt() *big.Int
IsSuperType() bool
}
type FractionalRangedType interface {
IntegerRangedType
Scale() uint
MinFractional() *big.Int
MaxFractional() *big.Int
}
// SaturatingArithmeticType is a type that supports saturating arithmetic functions
type SaturatingArithmeticType interface {
Type
SupportsSaturatingAdd() bool
SupportsSaturatingSubtract() bool
SupportsSaturatingMultiply() bool
SupportsSaturatingDivide() bool
}
const NumericTypeSaturatingAddFunctionName = "saturatingAdd"
const numericTypeSaturatingAddFunctionDocString = `
self + other, saturating at the numeric bounds instead of overflowing.
`
const NumericTypeSaturatingSubtractFunctionName = "saturatingSubtract"
const numericTypeSaturatingSubtractFunctionDocString = `
self - other, saturating at the numeric bounds instead of overflowing.
`
const NumericTypeSaturatingMultiplyFunctionName = "saturatingMultiply"
const numericTypeSaturatingMultiplyFunctionDocString = `
self * other, saturating at the numeric bounds instead of overflowing.
`
const NumericTypeSaturatingDivideFunctionName = "saturatingDivide"
const numericTypeSaturatingDivideFunctionDocString = `
self / other, saturating at the numeric bounds instead of overflowing.
`
var SaturatingArithmeticTypeFunctionTypes = map[Type]*FunctionType{}
func registerSaturatingArithmeticType(t Type) {
SaturatingArithmeticTypeFunctionTypes[t] = &FunctionType{
Parameters: []Parameter{
{
Label: ArgumentLabelNotRequired,
Identifier: "other",
TypeAnnotation: NewTypeAnnotation(t),
},
},
ReturnTypeAnnotation: NewTypeAnnotation(t),
}
}
func addSaturatingArithmeticFunctions(t SaturatingArithmeticType, members map[string]MemberResolver) {
addArithmeticFunction := func(name string, docString string) {
members[name] = MemberResolver{
Kind: common.DeclarationKindFunction,
Resolve: func(memoryGauge common.MemoryGauge, _ string, _ ast.Range, _ func(error)) *Member {
return NewPublicFunctionMember(
memoryGauge,
t,
name,
SaturatingArithmeticTypeFunctionTypes[t],
docString,
)
},
}
}
if t.SupportsSaturatingAdd() {
addArithmeticFunction(
NumericTypeSaturatingAddFunctionName,
numericTypeSaturatingAddFunctionDocString,
)
}
if t.SupportsSaturatingSubtract() {
addArithmeticFunction(
NumericTypeSaturatingSubtractFunctionName,
numericTypeSaturatingSubtractFunctionDocString,
)
}
if t.SupportsSaturatingMultiply() {
addArithmeticFunction(
NumericTypeSaturatingMultiplyFunctionName,
numericTypeSaturatingMultiplyFunctionDocString,
)
}