-
Notifications
You must be signed in to change notification settings - Fork 38
/
types.scala
2612 lines (2301 loc) · 109 KB
/
types.scala
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 sigmastate
import java.math.BigInteger
import org.ergoplatform._
import org.ergoplatform.validation._
import scalan.{RType, Nullable}
import scalan.RType.GeneralType
import sigmastate.SType.{TypeCode, AnyOps}
import sigmastate.interpreter._
import sigmastate.utils.Overloading.Overload1
import sigmastate.utils.SparseArrayContainer
import scalan.util.Extensions._
import scorex.crypto.authds.{ADValue, ADKey}
import scorex.crypto.authds.avltree.batch.{Lookup, Remove, Insert, Update}
import scorex.crypto.hash.Blake2b256
import sigmastate.Values._
import sigmastate.lang.Terms._
import sigmastate.lang.{SigmaBuilder, Terms}
import sigmastate.SCollection._
import sigmastate.basics.CryptoConstants.{hashLength, EcPointType}
import sigmastate.serialization.OpCodes
import special.collection.Coll
import special.sigma._
import scala.language.implicitConversions
import scala.reflect.{classTag, ClassTag}
import scala.collection.compat.immutable.ArraySeq
import sigmastate.SMethod.{InvokeDescBuilder, MethodCostFunc, givenCost, javaMethodOf, MethodCallIrBuilder}
import sigmastate.utxo._
import sigmastate.lang.Terms.STypeSubst
import sigmastate.eval.Evaluation.stypeToRType
import sigmastate.eval._
import sigmastate.exceptions.MethodNotFound
import debox.cfor
import scalan.reflection.{CommonReflection, RClass, RMethod}
import scala.collection.mutable
import scala.util.{Success, Failure}
/** Base type for all AST nodes of sigma lang. */
trait SigmaNode extends Product
/** Base type for all companions of AST nodes of sigma lang. */
trait SigmaNodeCompanion
/** Every type descriptor is a tree represented by nodes in SType hierarchy.
* In order to extend type family:
* - Implement concrete class derived from SType
* - Implement serializer (see SCollectionSerializer) and register it in STypeSerializer.table
* Each SType is serialized to array of bytes by:
* - emitting typeCode of each node (see special case for collections below)
* - then recursively serializing subtrees from left to right on each level
* - for each collection of primitive type there is special type code to emit single byte instead of two bytes
* Types code intervals
* - (1 .. MaxPrimTypeCode) // primitive types
* - (CollectionTypeCode .. CollectionTypeCode + MaxPrimTypeCode) // collections of primitive types
* - (MaxCollectionTypeCode ..) // Other types
* Collection of non-primitive type is serialized as (CollectionTypeCode, serialize(elementType))
* */
sealed trait SType extends SigmaNode {
/** The underlying Scala type of data values described by this type descriptor.
* E.g. scala.Int for SInt descriptor.
*/
type WrappedType
/** Type code used in serialization of SType values.
* @see TypeSerializer
*/
val typeCode: SType.TypeCode
/** Returns true if this type embeddable, i.e. a type that can be combined with type
* constructor for optimized encoding. For each embeddable type `T`, and type
* constructor `C`, the type `C[T]` can be represented by a single byte.
* @see [[sigmastate.serialization.TypeSerializer]]
*/
def isEmbeddable: Boolean = false
/** Elvis operator for types. See https://en.wikipedia.org/wiki/Elvis_operator*/
def ?:(whenNoType: => SType): SType = if (this == NoType) whenNoType else this
/** Applies a type substitution to this type.
*
* @param subst the type substitution to apply
* @return the type after applying the substitution
*/
def withSubstTypes(subst: Map[STypeVar, SType]): SType =
if (subst.isEmpty) this
else
Terms.applySubst(this, subst)
/** Returns parsable type term string of the type described by this type descriptor.
* For every type it should be inverse to SigmaTyper.parseType.
* This is default fallback implementation, should be overriden if it
* is not correct for a particular type. */
def toTermString: String = {
val t = Evaluation.stypeToRType(this)
t.name
}
}
object SType {
/** Representation of type codes used in serialization. */
type TypeCode = Byte
val DummyValue = 0.asWrappedType
implicit val typeByte = SByte
implicit val typeShort = SShort
implicit val typeInt = SInt
implicit val typeLong = SLong
implicit val typeBigInt = SBigInt
implicit val typeBoolean = SBoolean
implicit val typeAvlTree = SAvlTree
implicit val typeGroupElement = SGroupElement
implicit val typeSigmaProp = SSigmaProp
implicit val typeBox = SBox
/** Costructs a collection type with the given type of elements. */
implicit def typeCollection[V <: SType](implicit tV: V): SCollection[V] = SCollection[V](tV)
/** RType descriptors for predefined types used in AOTC-based interpreter. */
implicit val SigmaBooleanRType: RType[SigmaBoolean] = RType.fromClassTag(classTag[SigmaBoolean])
implicit val ErgoBoxRType: RType[ErgoBox] = RType.fromClassTag(classTag[ErgoBox])
implicit val ErgoBoxCandidateRType: RType[ErgoBoxCandidate] = RType.fromClassTag(classTag[ErgoBoxCandidate])
implicit val AvlTreeDataRType: RType[AvlTreeData] = GeneralType(classTag[AvlTreeData])
implicit val ErgoLikeContextRType: RType[ErgoLikeContext] = RType.fromClassTag(classTag[ErgoLikeContext])
/** Named type variables and parameters used in generic types and method signatures.
* Generic type terms like `(Coll[IV],(IV) => Boolean) => Boolean` are used to represent
* method types of `Coll`` and `Option`` types. Each such type is an instance of [[SFunc]].
* To represent variables (such as `IV` in the example above) [[STypeVar]] instances
* are used.
*
* Generic types are not supported by ErgoTree serialization format and STypeVars are
* used internally and never serialized (there is no serializer for STypeVar).
* Thus the usage of type variables is limited.
*
* All necessary type variables can be declared in advance and reused across all code
* base. This allows to avoid allocation of many duplicates and also improve
* performance of SType values.
*/
val tT = STypeVar("T")
val tR = STypeVar("R")
val tK = STypeVar("K")
val tL = STypeVar("L")
val tO = STypeVar("O")
val tD = STypeVar("D")
val tV = STypeVar("V")
val tIV = STypeVar("IV")
val tOV = STypeVar("OV")
val paramT = STypeParam(tT)
val paramR = STypeParam(tR)
val paramIV = STypeParam(tIV)
val paramOV = STypeParam(tOV)
val paramIVSeq: Seq[STypeParam] = Array(paramIV)
val IndexedSeqOfT1: IndexedSeq[SType] = Array(SType.tT)
val IndexedSeqOfT2: IndexedSeq[SType] = Array(SType.tT, SType.tT)
/** Immutable empty array, can be used to avoid repeated allocations. */
val EmptyArray = Array.empty[SType]
/** Immutable empty IndexedSeq, can be used to avoid repeated allocations. */
val EmptySeq: IndexedSeq[SType] = EmptyArray
/** All pre-defined types should be listed here. Note, NoType is not listed.
* Should be in sync with sigmastate.lang.Types.predefTypes. */
val allPredefTypes: Seq[SType] = Array(SBoolean, SByte, SShort, SInt, SLong, SBigInt, SContext,
SGlobal, SHeader, SPreHeader, SAvlTree, SGroupElement, SSigmaProp, SString, SBox,
SUnit, SAny)
/** A mapping of object types supporting MethodCall operations. For each serialized
* typeId this map contains a companion object which can be used to access the list of
* corresponding methods.
*
* NOTE: in the current implementation only monomorphic methods are supported (without
* type parameters)
*
* NOTE2: in v3.x SNumericType.typeId is silently shadowed by SGlobal.typeId as part of
* `toMap` operation. As a result, the methods collected into SByte.methods cannot be
* resolved (using SMethod.fromIds()) for all numeric types (SByte, SShort, SInt,
* SLong, SBigInt). See the corresponding regression `property("MethodCall on numerics")`.
* However, this "shadowing" is not a problem since all casting methods are implemented
* via Downcast, Upcast opcodes and the remaining `toBytes`, `toBits` methods are not
* implemented at all.
* In order to allow MethodCalls on numeric types in future versions the SNumericType.typeId
* should be changed and SGlobal.typeId should be preserved. The regression tests in
* `property("MethodCall Codes")` should pass.
*/
// TODO v6.0 (h4): should contain all numeric types (including also SNumericType)
// to support method calls like 10.toByte which encoded as MethodCall with typeId = 4, methodId = 1
// see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/667
lazy val types: Map[Byte, STypeCompanion] = Seq(
SBoolean, SNumericType, SString, STuple, SGroupElement, SSigmaProp, SContext, SGlobal, SHeader, SPreHeader,
SAvlTree, SBox, SOption, SCollection, SBigInt
).map { t => (t.typeId, t) }.toMap
/** Checks that the type of the value corresponds to the descriptor `tpe`.
* If the value has complex structure only root type constructor is checked.
* NOTE, this method is used in ErgoTree evaluation to systematically check that each
* tree node evaluates to a value of the expected type.
* Shallow runtime checks are enough if:
* 1) ErgoTree is well-typed, i.e. each sub-expression has correct types (agree with
* the argument type).
* 2) `isValueOfType == true` for each tree leaf
* 3) `isValueOfType == true` for each sub-expression
*
* @param value value to check type
* @param tpe type descriptor to check value against
* @return true if the given `value` is of type tpe`
*/
def isValueOfType[T <: SType](x: Any, tpe: T): Boolean = tpe match {
case SBoolean => x.isInstanceOf[Boolean]
case SByte => x.isInstanceOf[Byte]
case SShort => x.isInstanceOf[Short]
case SInt => x.isInstanceOf[Int]
case SLong => x.isInstanceOf[Long]
case SBigInt => x.isInstanceOf[BigInt]
case SGroupElement => x.isInstanceOf[GroupElement]
case SSigmaProp => x.isInstanceOf[SigmaProp]
case SBox => x.isInstanceOf[Box]
case _: SCollectionType[_] => x.isInstanceOf[Coll[_]]
case _: SOption[_] => x.isInstanceOf[Option[_]]
case t: STuple =>
if (t.items.length == 2) x.isInstanceOf[Tuple2[_,_]]
else sys.error(s"Unsupported tuple type $t")
case tF: SFunc =>
if (tF.tDom.length == 1) x.isInstanceOf[Function1[_,_]]
else sys.error(s"Unsupported function type $tF")
case SContext => x.isInstanceOf[Context]
case SAvlTree => x.isInstanceOf[AvlTree]
case SGlobal => x.isInstanceOf[SigmaDslBuilder]
case SHeader => x.isInstanceOf[Header]
case SPreHeader => x.isInstanceOf[PreHeader]
case SUnit => x.isInstanceOf[Unit]
case _ => sys.error(s"Unknown type $tpe")
}
implicit class STypeOps(val tpe: SType) extends AnyVal {
def isCollectionLike: Boolean = tpe.isInstanceOf[SCollection[_]]
def isCollection: Boolean = tpe.isInstanceOf[SCollectionType[_]]
def isOption: Boolean = tpe.isInstanceOf[SOption[_]]
def isBox: Boolean = tpe.isInstanceOf[SBox.type]
def isGroupElement: Boolean = tpe.isInstanceOf[SGroupElement.type]
def isSigmaProp: Boolean = tpe.isInstanceOf[SSigmaProp.type]
def isAvlTree: Boolean = tpe.isInstanceOf[SAvlTree.type]
def isFunc : Boolean = tpe.isInstanceOf[SFunc]
def isTuple: Boolean = tpe.isInstanceOf[STuple]
/** Returns true if this type is numeric (Byte, Short, etc.)
* @see [[sigmastate.SNumericType]]
*/
def isNumType: Boolean = tpe.isInstanceOf[SNumericType]
/** Returns true if this type is either numeric (Byte, Short, etc.) or is NoType.
* @see [[sigmastate.SNumericType]]
*/
def isNumTypeOrNoType: Boolean = isNumType || tpe == NoType
def asNumType: SNumericType = tpe.asInstanceOf[SNumericType]
def asFunc: SFunc = tpe.asInstanceOf[SFunc]
def asProduct: SProduct = tpe.asInstanceOf[SProduct]
def asTuple: STuple = tpe.asInstanceOf[STuple]
def asOption[T <: SType]: SOption[T] = tpe.asInstanceOf[SOption[T]]
def whenFunc[T](action: SFunc => Unit) = if(tpe.isInstanceOf[SFunc]) action(tpe.asFunc)
def asCollection[T <: SType] = tpe.asInstanceOf[SCollection[T]]
/** Returns the [[ClassTag]] for the given [[SType]]. */
def classTag[T <: SType#WrappedType]: ClassTag[T] = (tpe match {
case SBoolean => reflect.classTag[Boolean]
case SByte => reflect.classTag[Byte]
case SShort => reflect.classTag[Short]
case SInt => reflect.classTag[Int]
case SLong => reflect.classTag[Long]
case SBigInt => reflect.classTag[BigInteger]
case SAvlTree => reflect.classTag[AvlTree]
case SGroupElement => reflect.classTag[EcPointType]
case SSigmaProp => reflect.classTag[SigmaBoolean]
case SUnit => reflect.classTag[Unit]
case SBox => reflect.classTag[ErgoBox]
case SAny => reflect.classTag[Any]
case opt: SOption[a] => reflect.classTag[Option[a]]
case _: STuple => reflect.classTag[Array[Any]]
case tColl: SCollection[a] =>
val elemType = tColl.elemType
implicit val ca = elemType.classTag[elemType.WrappedType]
reflect.classTag[Array[elemType.WrappedType]]
case _ => sys.error(s"Cannot get ClassTag for type $tpe")
}).asInstanceOf[ClassTag[T]]
}
implicit class AnyOps(val x: Any) extends AnyVal {
/** Helper method to simplify type casts. */
def asWrappedType: SType#WrappedType = x.asInstanceOf[SType#WrappedType]
}
}
/** Basic interface for all type companions.
* This is necessary to make distinction between concrete type descriptor of a type like Coll[Int]
* and generic descriptor of Coll[T] type constructor.
* Some simple types like Int, GroupElement inherit from both SType and STypeCompanion.
* @see SInt, SGroupElement, SType
*/
trait STypeCompanion {
/** Force initialization of reflection. */
val reflection = InterpreterReflection
/** Type identifier to use in method serialization */
def typeId: Byte
/** If this is SType instance then returns the name of the corresponding RType.
* Otherwise returns the name of type companion object (e.g. SCollection).
*/
def typeName: String = {
this match {
case t: SType =>
val rtype = stypeToRType(t)
rtype.name
case _ => this.getClass.getSimpleName.replace("$", "")
}
}
/** List of methods defined for instances of this type. */
def methods: Seq[SMethod]
private lazy val _methodsMap: Map[Byte, Map[Byte, SMethod]] = methods
.groupBy(_.objType.typeId)
.map { case (typeId, ms) => (typeId -> ms.map(m => m.methodId -> m).toMap) }
/** Lookup method by its id in this type. */
@inline def getMethodById(methodId: Byte): Option[SMethod] =
_methodsMap.get(typeId) match {
case Some(ms) => ms.get(methodId)
case None => None
}
/** Lookup method in this type by method's id or throw ValidationException.
* This method can be used in trySoftForkable section to either obtain valid method
* or catch ValidatioinException which can be checked for soft-fork condition.
* It delegate to getMethodById to lookup method.
* @see getMethodById
*/
def methodById(methodId: Byte): SMethod = {
ValidationRules.CheckAndGetMethod(this, methodId)
}
/** Looks up the method descriptor by the method name. */
def getMethodByName(name: String): SMethod = methods.find(_.name == name).get
/** Class which represents values of this type. When method call is executed, the corresponding method
* of this class is invoked via [[RMethod]].invoke(). */
def reprClass: RClass[_]
/** Represents class of `this`. */
lazy val thisRClass: RClass[_] = RClass(this.getClass)
}
/** Defines recognizer method which allows the derived object to be used in patterns
* to recognize method descriptors by method name.
* @see SCollecton
*/
trait MethodByNameUnapply extends STypeCompanion {
def unapply(methodName: String): Option[SMethod] = methods.find(_.name == methodName)
}
/** Base trait for all types which have methods (and properties) */
trait SProduct extends SType {
/** Returns -1 if `method` is not found. */
def methodIndex(name: String): Int = methods.indexWhere(_.name == name)
/** Returns true if this type has a method with the given name. */
def hasMethod(name: String): Boolean = methodIndex(name) != -1
/** This method should be overriden in derived classes to add new methods in addition to inherited.
* Typical override: `super.getMethods() ++ Seq(m1, m2, m3)` */
protected def getMethods(): Seq[SMethod] = Nil
/** Returns all the methods of this type. */
lazy val methods: Seq[SMethod] = {
val ms = getMethods()
assert(ms.map(_.name).distinct.length == ms.length, s"Duplicate method names in $this")
ms.groupBy(_.objType).foreach { case (comp, ms) =>
assert(ms.map(_.methodId).distinct.length == ms.length, s"Duplicate method ids in $comp: $ms")
}
ms
}
/** Finds a method descriptor [[SMethod]] for the given name. */
def method(methodName: String): Option[SMethod] = methods.find(_.name == methodName)
}
/** Base trait implemented by all generic types (those which has type parameters,
* e.g. Coll[T], Option[T], etc.)*/
trait SGenericType {
/** Type parameters of this generic type. */
def typeParams: Seq[STypeParam]
}
/** Meta information which can be attached to each argument of SMethod.
* @param name name of the argument
* @param description argument description. */
case class ArgInfo(name: String, description: String)
/** Meta information which can be attached to SMethod.
* @param opDesc optional operation descriptor
* @param description human readable description of the method
* @param args one item for each argument */
case class OperationInfo(opDesc: Option[ValueCompanion], description: String, args: Seq[ArgInfo]) {
def isFrontendOnly: Boolean = opDesc.isEmpty
def opTypeName: String = opDesc.map(_.typeName).getOrElse("(FRONTEND ONLY)")
}
object OperationInfo {
/** Convenience factory method. */
def apply(opDesc: ValueCompanion, description: String, args: Seq[ArgInfo]): OperationInfo =
OperationInfo(Some(opDesc), description, args)
}
/** Meta information connecting SMethod with ErgoTree.
* The optional builder is used by front-end ErgoScript compiler to replace method calls
* with ErgoTree nodes. In many cases [[SMethod.MethodCallIrBuilder]] builder is used.
* However there are specific cases where more complex builders are used, see for example
* usage of `withIRInfo` in the declaration of [[SCollection.GetOrElseMethod]].
* @param irBuilder optional method call recognizer and ErgoTree node builder.
* When the partial function is defined on a tuple
* (builder, obj, m, args, subst) it transforms it to a new ErgoTree
* node, which is then used in the resuting ErgoTree coming out of
* the ErgoScript compiler.
* @param javaMethod Java [[Method]] which should be used to evaluate
* [[sigmastate.lang.Terms.MethodCall]] node of ErgoTree.
* @param invokeDescsBuilder optional builder of additional type descriptors (see extraDescriptors)
*/
case class MethodIRInfo(
irBuilder: Option[PartialFunction[(SigmaBuilder, SValue, SMethod, Seq[SValue], STypeSubst), SValue]],
javaMethod: Option[RMethod],
invokeDescsBuilder: Option[InvokeDescBuilder]
)
/** Represents method descriptor.
*
* @param objType type or type constructor descriptor
* @param name method name
* @param stype method signature type,
* where `stype.tDom`` - argument type and
* `stype.tRange` - method result type.
* @param methodId method code, it should be unique among methods of the same objType.
* @param costKind cost descriptor for this method
* @param irInfo meta information connecting SMethod with ErgoTree (see [[MethodIRInfo]])
* @param docInfo optional human readable method description data
* @param costFunc optional specification of how the cost should be computed for the
* given method call (See ErgoTreeEvaluator.calcCost method).
*/
case class SMethod(
objType: STypeCompanion,
name: String,
stype: SFunc,
methodId: Byte,
costKind: CostKind,
irInfo: MethodIRInfo,
docInfo: Option[OperationInfo],
costFunc: Option[MethodCostFunc]) {
/** Operation descriptor of this method. */
lazy val opDesc = MethodDesc(this)
/** Finds and keeps the [[RMethod]] instance which corresponds to this method descriptor.
* The lazy value is forced only if irInfo.javaMethod == None
*/
lazy val javaMethod: RMethod = {
irInfo.javaMethod.getOrElse {
val paramTypes = stype.tDom.drop(1).map(t => t match {
case _: STypeVar => classOf[AnyRef]
case _: SFunc => classOf[_ => _]
case _ => Evaluation.stypeToRType(t).classTag.runtimeClass
}).toArray
val m = objType.reprClass.getMethod(name, paramTypes:_*)
m
}
}
/** Additional type descriptors, which are necessary to perform invocation of Method
* associated with this instance.
* @see MethodCall.eval
*/
lazy val extraDescriptors: Seq[RType[_]] = {
irInfo.invokeDescsBuilder match {
case Some(builder) =>
builder(stype).map(Evaluation.stypeToRType)
case None =>
ArraySeq.empty[RType[_]]
}
}
/** Invoke this method on the given object with the arguments.
* This is used for methods with FixedCost costKind. */
def invokeFixed(obj: Any, args: Array[Any])(implicit E: ErgoTreeEvaluator): Any = {
javaMethod.invoke(obj, args.asInstanceOf[Array[AnyRef]]:_*)
}
// TODO optimize: avoid lookup when this SMethod is created via `specializeFor`
/** Return generic template of this method. */
@inline final def genericMethod: SMethod = {
objType.getMethodById(methodId).get
}
/** Returns refection [[RMethod]] which must be invoked to evaluate this method.
* The method is resolved by its name using `name + "_eval"` naming convention.
* @see `map_eval`, `flatMap_eval` and other `*_eval` methods.
* @hotspot don't beautify the code */
lazy val evalMethod: RMethod = {
val argTypes = stype.tDom
val nArgs = argTypes.length
val paramTypes = new Array[Class[_]](nArgs + 2)
paramTypes(0) = classOf[MethodCall]
cfor(0)(_ < nArgs, _ + 1) { i =>
paramTypes(i + 1) = argTypes(i) match {
case _: STypeVar => classOf[AnyRef]
case _: SFunc => classOf[_ => _]
case _: SCollectionType[_] => classOf[Coll[_]]
case _: SOption[_] => classOf[Option[_]]
case t =>
Evaluation.stypeToRType(t).classTag.runtimeClass
}
}
paramTypes(paramTypes.length - 1) = classOf[ErgoTreeEvaluator]
val methodName = name + "_eval"
val m = try {
objType.thisRClass.getMethod(methodName, paramTypes:_*)
}
catch { case e: NoSuchMethodException =>
throw new RuntimeException(s"Cannot find eval method def $methodName(${Seq(paramTypes:_*)})", e)
}
m
}
/** Create a new instance with the given stype. */
def withSType(newSType: SFunc): SMethod = copy(stype = newSType)
/** Create a new instance with the given cost function. */
def withCost(costFunc: MethodCostFunc): SMethod = copy(costFunc = Some(costFunc))
/** Create a new instance in which the `stype` field transformed using
* the given substitution. */
def withConcreteTypes(subst: Map[STypeVar, SType]): SMethod =
withSType(stype.withSubstTypes(subst).asFunc)
/** Name of a language operation represented by this method. */
def opName = objType.getClass.getSimpleName + "." + name
/** Returns [[OperationId]] for AOT costing. */
def opId: OperationId = {
OperationId(opName, stype)
}
/** Specializes this instance by creating a new [[SMethod]] instance where signature
* is specialized with respect to the given object and args types. It is used in
* [[sigmastate.serialization.MethodCallSerializer]] `parse` method, so it is part of
* consensus protocol.
*
* @param objTpe specific type of method receiver (aka object)
* @param args specific types of method arguments
* @return new instance of method descriptor with specialized signature
* @consensus
*/
def specializeFor(objTpe: SType, args: Seq[SType]): SMethod = {
Terms.unifyTypeLists(stype.tDom, objTpe +: args) match {
case Some(subst) if subst.nonEmpty =>
withConcreteTypes(subst)
case _ => this
}
}
/** Create a new instance with the given [[OperationInfo]] parameters. */
def withInfo(opDesc: ValueCompanion, desc: String, args: ArgInfo*): SMethod = {
this.copy(docInfo = Some(OperationInfo(opDesc, desc, ArgInfo("this", "this instance") +: args.toSeq)))
}
/** Create a new instance with the given [[OperationInfo]] parameters.
* NOTE: opDesc parameter is not defined and falls back to None.
*/
def withInfo(desc: String, args: ArgInfo*): SMethod = {
this.copy(docInfo = Some(OperationInfo(None, desc, ArgInfo("this", "this instance") +: args.toSeq)))
}
/** Create a new instance with the given IR builder (aka MethodCall rewriter) parameter. */
def withIRInfo(
irBuilder: PartialFunction[(SigmaBuilder, SValue, SMethod, Seq[SValue], STypeSubst), SValue],
javaMethod: RMethod = null,
invokeHandler: InvokeDescBuilder = null): SMethod = {
this.copy(irInfo = MethodIRInfo(Some(irBuilder), Option(javaMethod), Option(invokeHandler)))
}
/** Lookup [[ArgInfo]] for the given argName or throw an exception. */
def argInfo(argName: String): ArgInfo =
docInfo.get.args.find(_.name == argName).get
}
object SMethod {
/** Type of functions used to assign cost to method call nodes.
* For a function `f: (mc, obj, args) => cost` it is called before the evaluation of
* the `mc` node with the given `obj` as method receiver and `args` as method
* arguments.
*/
abstract class MethodCostFunc extends Function4[ErgoTreeEvaluator, MethodCall, Any, Array[Any], CostDetails] {
/**
* The function returns an estimated cost of evaluation BEFORE actual evaluation of
* the method. For this reason [[MethodCostFunc]] is not used for higher-order
* operations like `Coll.map`, `Coll.filter` etc.
*/
def apply(E: ErgoTreeEvaluator, mc: MethodCall, obj: Any, args: Array[Any]): CostDetails
}
/** Returns a cost function which always returs the given cost. */
def givenCost(costKind: FixedCost): MethodCostFunc = new MethodCostFunc {
override def apply(E: ErgoTreeEvaluator,
mc: MethodCall,
obj: Any, args: Array[Any]): CostDetails = {
if (E.settings.costTracingEnabled)
TracedCost(Array(FixedCostItem(MethodDesc(mc.method), costKind)))
else
GivenCost(costKind.cost)
}
}
/** Returns a cost function which expects `obj` to be of `Coll[T]` type and
* uses its length to compute SeqCostItem */
def perItemCost(costKind: PerItemCost): MethodCostFunc = new MethodCostFunc {
override def apply(E: ErgoTreeEvaluator,
mc: MethodCall,
obj: Any, args: Array[Any]): CostDetails = obj match {
case coll: Coll[a] =>
if (E.settings.costTracingEnabled) {
val desc = MethodDesc(mc.method)
TracedCost(Array(SeqCostItem(desc, costKind, coll.length)))
}
else
GivenCost(costKind.cost(coll.length))
case _ =>
ErgoTreeEvaluator.error(
s"Invalid object $obj of method call $mc: Coll type is expected")
}
}
/** Some runtime methods (like Coll.map, Coll.flatMap) require additional RType descriptors.
* The builder can extract those descriptors from the given type of the method signature.
*/
type InvokeDescBuilder = SFunc => Seq[SType]
/** Return [[Method]] descriptor for the given `methodName` on the given `cT` type.
* @param methodName the name of the method to lookup
* @param cT the class where to search the methodName
* @param cA1 the class of the method argument
*/
def javaMethodOf[T, A1](methodName: String)
(implicit cT: ClassTag[T], cA1: ClassTag[A1]): RMethod =
RClass(cT.runtimeClass).getMethod(methodName, cA1.runtimeClass)
/** Return [[Method]] descriptor for the given `methodName` on the given `cT` type.
* @param methodName the name of the method to lookup
* @param cT the class where to search the methodName
* @param cA1 the class of the method's first argument
* @param cA2 the class of the method's second argument
*/
def javaMethodOf[T, A1, A2]
(methodName: String)
(implicit cT: ClassTag[T], cA1: ClassTag[A1], cA2: ClassTag[A2]): RMethod =
RClass(cT.runtimeClass).getMethod(methodName, cA1.runtimeClass, cA2.runtimeClass)
/** Default fallback method call recognizer which builds MethodCall ErgoTree nodes. */
val MethodCallIrBuilder: PartialFunction[(SigmaBuilder, SValue, SMethod, Seq[SValue], STypeSubst), SValue] = {
case (builder, obj, method, args, tparamSubst) =>
builder.mkMethodCall(obj, method, args.toIndexedSeq, tparamSubst)
}
/** Convenience factory method. */
def apply(objType: STypeCompanion, name: String, stype: SFunc,
methodId: Byte,
costKind: CostKind): SMethod = {
SMethod(
objType, name, stype, methodId, costKind,
MethodIRInfo(None, None, None), None, None)
}
/** Looks up [[SMethod]] instance for the given type and method ids.
*
* @param typeId id of a type which can contain methods
* @param methodId id of a method of the type given by `typeId`
* @return an instance of [[SMethod]] which may contain generic type variables in the
* signature (see SMethod.stype). As a result `specializeFor` is called by
* deserializer to obtain monomorphic method descriptor.
* @consensus this is method is used in [[sigmastate.serialization.MethodCallSerializer]]
* `parse` method and hence it is part of consensus protocol
*/
def fromIds(typeId: Byte, methodId: Byte): SMethod = {
ValidationRules.CheckTypeWithMethods(typeId, SType.types.contains(typeId))
val typeCompanion = SType.types(typeId)
val method = typeCompanion.methodById(methodId)
method
}
}
/** Special type to represent untyped values.
* Interpreter raises an error when encounter a Value with this type.
* All Value nodes with this type should be elimitanted during typing.
* If no specific type can be assigned statically during typing,
* then either error should be raised or type SAny should be assigned
* which is interpreted as dynamic typing. */
case object NoType extends SType {
type WrappedType = Nothing
override val typeCode = 0: Byte
}
/** Base trait for all pre-defined types which are not necessary primitive (e.g. Box, AvlTree).
*/
trait SPredefType extends SType {
}
/** Base trait for all embeddable types.
*/
trait SEmbeddable extends SType {
override def isEmbeddable: Boolean = true
/** Type code of embeddable type can be combined with code of type constructor.
* Resulting code can be serialized. This simple convention allows to save space for most frequently used types.
* See TypeSerializer */
@inline final def embedIn(typeConstrId: Byte): Byte = (typeConstrId + this.typeCode).toByte
}
/** Base trait for all primitive types (aka atoms) which don't have internal type items.
* All primitive types can occupy a reserved interval of codes from 1 to MaxPrimTypeCode. */
trait SPrimType extends SType with SPredefType {
}
/** Primitive type recognizer to pattern match on TypeCode */
object SPrimType {
def unapply(t: SType): Option[SType] = SType.allPredefTypes.find(_ == t)
/** Type code of the last valid prim type so that (1 to LastPrimTypeCode) is a range of valid codes. */
final val LastPrimTypeCode: Byte = 8: Byte
/** Upper limit of the interval of valid type codes for primitive types */
final val MaxPrimTypeCode: Byte = 11: Byte
/** Max possible number of primitive types. */
final val PrimRange: Byte = (MaxPrimTypeCode + 1).toByte
}
/** Marker trait for all numeric types. */
trait SNumericType extends SProduct {
import SNumericType._
protected override def getMethods(): Seq[SMethod] = {
super.getMethods() ++ SNumericType.methods.map {
m => m.copy(stype = Terms.applySubst(m.stype, Map(tNum -> this)).asFunc)
}
}
/** Checks if the given name is a cast method name.
* @return true if it is. */
def isCastMethod (name: String): Boolean = castMethods.contains(name)
/** Upcasts the given value of a smaller type to this larger type.
* Corresponds to section 5.1.2 Widening Primitive Conversion of Java Language Spec.
* @param n numeric value to be converted
* @return a value of WrappedType of this type descriptor's instance.
* @throw exception if `n` has actual type which is larger than this type.
*/
def upcast(n: AnyVal): WrappedType
/** Downcasts the given value of a larger type to this smaller type.
* Corresponds to section 5.1.3 Narrowing Primitive Conversion of Java Language Spec.
* @param n numeric value to be converted
* @return a value of WrappedType of this type descriptor's instance.
* @throw exception if the actual value of `i` cannot fit into this type.
*/
def downcast(n: AnyVal): WrappedType
/** Returns a type which is larger. */
@inline def max(that: SNumericType): SNumericType =
if (this.numericTypeIndex > that.numericTypeIndex) this else that
/** Returns true if this numeric type is larger than that. */
@inline final def >(that: SNumericType): Boolean = this.numericTypeIndex > that.numericTypeIndex
/** Numeric types are ordered by the number of bytes to store the numeric values.
* @return index in the array of all numeric types. */
def numericTypeIndex: Int
override def toString: String = this.getClass.getSimpleName
}
object SNumericType extends STypeCompanion {
/** Array of all numeric types ordered by number of bytes in the representation. */
final val allNumericTypes = Array(SByte, SShort, SInt, SLong, SBigInt)
// TODO v6.0 (4h): this typeId is now shadowed by SGlobal.typeId
// see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/667
override def typeId: TypeCode = 106: Byte
/** Since this object is not used in SMethod instances. */
override def reprClass: RClass[_] = sys.error(s"Shouldn't be called.")
/** Type variable used in generic signatures of method descriptors. */
val tNum = STypeVar("TNum")
/** Cost function which is assigned for numeric cast MethodCall nodes in ErgoTree.
* It is called as part of MethodCall.eval method. */
val costOfNumericCast: MethodCostFunc = new MethodCostFunc {
override def apply(E: ErgoTreeEvaluator,
mc: MethodCall,
obj: Any,
args: Array[Any]): CostDetails = {
val targetTpe = mc.method.stype.tRange
val cast = getNumericCast(mc.obj.tpe, mc.method.name, targetTpe).get
val costKind = if (cast == Downcast) Downcast.costKind else Upcast.costKind
TracedCost(Array(TypeBasedCostItem(MethodDesc(mc.method), costKind, targetTpe)))
}
}
/** The following SMethod instances are descriptors of methods available on all numeric
* types.
* @see `val methods` below
* */
val ToByteMethod: SMethod = SMethod(this, "toByte", SFunc(tNum, SByte), 1, null)
.withCost(costOfNumericCast)
.withInfo(PropertyCall, "Converts this numeric value to \\lst{Byte}, throwing exception if overflow.")
val ToShortMethod: SMethod = SMethod(this, "toShort", SFunc(tNum, SShort), 2, null)
.withCost(costOfNumericCast)
.withInfo(PropertyCall, "Converts this numeric value to \\lst{Short}, throwing exception if overflow.")
val ToIntMethod: SMethod = SMethod(this, "toInt", SFunc(tNum, SInt), 3, null)
.withCost(costOfNumericCast)
.withInfo(PropertyCall, "Converts this numeric value to \\lst{Int}, throwing exception if overflow.")
val ToLongMethod: SMethod = SMethod(this, "toLong", SFunc(tNum, SLong), 4, null)
.withCost(costOfNumericCast)
.withInfo(PropertyCall, "Converts this numeric value to \\lst{Long}, throwing exception if overflow.")
val ToBigIntMethod: SMethod = SMethod(this, "toBigInt", SFunc(tNum, SBigInt), 5, null)
.withCost(costOfNumericCast)
.withInfo(PropertyCall, "Converts this numeric value to \\lst{BigInt}")
/** Cost of: 1) creating Byte collection from a numeric value */
val ToBytes_CostKind = FixedCost(JitCost(5))
val ToBytesMethod: SMethod = SMethod(
this, "toBytes", SFunc(tNum, SByteArray), 6, ToBytes_CostKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(PropertyCall,
""" Returns a big-endian representation of this numeric value in a collection of bytes.
| For example, the \lst{Int} value \lst{0x12131415} would yield the
| collection of bytes \lst{[0x12, 0x13, 0x14, 0x15]}.
""".stripMargin)
/** Cost of: 1) creating Boolean collection (one bool for each bit) from a numeric
* value. */
val ToBits_CostKind = FixedCost(JitCost(5))
val ToBitsMethod: SMethod = SMethod(
this, "toBits", SFunc(tNum, SBooleanArray), 7, ToBits_CostKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(PropertyCall,
""" Returns a big-endian representation of this numeric in a collection of Booleans.
| Each boolean corresponds to one bit.
""".stripMargin)
override val methods: Seq[SMethod] = Array(
ToByteMethod, // see Downcast
ToShortMethod, // see Downcast
ToIntMethod, // see Downcast
ToLongMethod, // see Downcast
ToBigIntMethod, // see Downcast
ToBytesMethod,
ToBitsMethod
)
/** Collection of names of numeric casting methods (like `toByte`, `toInt`, etc). */
val castMethods: Array[String] =
Array(ToByteMethod, ToShortMethod, ToIntMethod, ToLongMethod, ToBigIntMethod)
.map(_.name)
/** Checks the given name is numeric type cast method (like toByte, toInt, etc.).*/
def isCastMethod(name: String): Boolean = castMethods.contains(name)
/** Convert the given method to a cast operation from fromTpe to resTpe. */
def getNumericCast(fromTpe: SType, methodName: String, resTpe: SType): Option[NumericCastCompanion] = (fromTpe, resTpe) match {
case (from: SNumericType, to: SNumericType) if isCastMethod(methodName) =>
val op = if (to > from) Upcast else Downcast
Some(op)
case _ => None // the method in not numeric type cast
}
}
/** Base type for SBoolean and SSigmaProp. */
trait SLogical extends SType {
}
/** Monomorphic type descriptor i.e. a type without generic parameters.
* @see `SGenericType`
*/
trait SMonoType extends SType with STypeCompanion {
/** Helper method to create method descriptors for properties (i.e. methods without args). */
protected def propertyCall(name: String, tpeRes: SType, id: Byte, costKind: CostKind): SMethod =
SMethod(this, name, SFunc(this, tpeRes), id, costKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(PropertyCall, "")
/** Helper method to create method descriptors for properties (i.e. methods without args). */
protected def property(name: String, tpeRes: SType, id: Byte, valueCompanion: ValueCompanion): SMethod =
SMethod(this, name, SFunc(this, tpeRes), id, valueCompanion.costKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(valueCompanion, "")
}
/** Descriptor of ErgoTree type `Boolean` holding `true` or `false` values. */
case object SBoolean extends SPrimType with SEmbeddable with SLogical with SProduct with SMonoType {
override type WrappedType = Boolean
override val typeCode: TypeCode = 1: Byte
override def typeId = typeCode
override val reprClass: RClass[_] = RClass(classOf[Boolean])
val ToByte = "toByte"
protected override def getMethods() = super.getMethods()
/* TODO soft-fork: https://github.com/ScorexFoundation/sigmastate-interpreter/issues/479
++ Seq(
SMethod(this, ToByte, SFunc(this, SByte), 1)
.withInfo(PropertyCall, "Convert true to 1 and false to 0"),
)
*/
}
/** Descriptor of ErgoTree type `Byte` - 8-bit signed integer. */
case object SByte extends SPrimType with SEmbeddable with SNumericType with SMonoType {
override type WrappedType = Byte
override val typeCode: TypeCode = 2: Byte
override val reprClass: RClass[_] = RClass(classOf[Byte])
override def typeId = typeCode
override def numericTypeIndex: Int = 0
override def upcast(v: AnyVal): Byte = v match {
case b: Byte => b
case _ => sys.error(s"Cannot upcast value $v to the type $this")
}
override def downcast(v: AnyVal): Byte = v match {
case b: Byte => b
case s: Short => s.toByteExact
case i: Int => i.toByteExact
case l: Long => l.toByteExact
case _ => sys.error(s"Cannot downcast value $v to the type $this")
}
}
/** Descriptor of ErgoTree type `Short` - 16-bit signed integer. */
case object SShort extends SPrimType with SEmbeddable with SNumericType with SMonoType {
override type WrappedType = Short
override val typeCode: TypeCode = 3: Byte
override val reprClass: RClass[_] = RClass(classOf[Short])
override def typeId = typeCode
override def numericTypeIndex: Int = 1
override def upcast(v: AnyVal): Short = v match {
case x: Byte => x.toShort
case x: Short => x
case _ => sys.error(s"Cannot upcast value $v to the type $this")
}
override def downcast(v: AnyVal): Short = v match {
case s: Short => s
case i: Int => i.toShortExact
case l: Long => l.toShortExact
case _ => sys.error(s"Cannot downcast value $v to the type $this")
}
}
/** Descriptor of ErgoTree type `Int` - 32-bit signed integer. */
case object SInt extends SPrimType with SEmbeddable with SNumericType with SMonoType {
override type WrappedType = Int
override val typeCode: TypeCode = 4: Byte
override val reprClass: RClass[_] = RClass(classOf[Int])
override def typeId = typeCode
override def numericTypeIndex: Int = 2
override def upcast(v: AnyVal): Int = v match {
case x: Byte => x.toInt
case x: Short => x.toInt
case x: Int => x
case _ => sys.error(s"Cannot upcast value $v to the type $this")
}
override def downcast(v: AnyVal): Int = v match {
case b: Byte => b.toInt
case s: Short => s.toInt
case i: Int => i
case l: Long => l.toIntExact
case _ => sys.error(s"Cannot downcast value $v to the type $this")
}
}
/** Descriptor of ErgoTree type `Long` - 64-bit signed integer. */
case object SLong extends SPrimType with SEmbeddable with SNumericType with SMonoType {
override type WrappedType = Long
override val typeCode: TypeCode = 5: Byte
override val reprClass: RClass[_] = RClass(classOf[Long])
override def typeId = typeCode
override def numericTypeIndex: Int = 3
override def upcast(v: AnyVal): Long = v match {
case x: Byte => x.toLong