-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathmethods.scala
2088 lines (1809 loc) · 88.2 KB
/
methods.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 sigma.ast
import org.ergoplatform._
import org.ergoplatform.validation._
import sigma.{Coll, VersionContext, _}
import sigma.Evaluation.stypeToRType
import sigma._
import sigma.{VersionContext, _}
import sigma.{UnsignedBigInt, _}
import sigma.ast.SCollection.{SBooleanArray, SBoxArray, SByteArray, SByteArray2, SHeaderArray}
import sigma.ast.SGlobalMethods.{decodeNBitsMethod, encodeNBitsMethod}
import sigma.ast.SMethod.{MethodCallIrBuilder, MethodCostFunc, javaMethodOf}
import sigma.ast.SType.{TypeCode, paramT, tT}
import sigma.ast.syntax.{SValue, ValueOps}
import sigma.data.ExactIntegral.{ByteIsExactIntegral, IntIsExactIntegral, LongIsExactIntegral, ShortIsExactIntegral}
import sigma.data.NumericOps.BigIntIsExactIntegral
import sigma.data.OverloadHack.Overloaded1
import sigma.data.UnsignedBigIntNumericOps.UnsignedBigIntIsExactIntegral
import sigma.data.{DataValueComparer, KeyValueColl, Nullable, RType, SigmaConstants}
import sigma.data.{CBigInt, DataValueComparer, KeyValueColl, Nullable, RType, SigmaConstants}
import sigma.eval.{CostDetails, ErgoTreeEvaluator, TracedCost}
import sigma.pow.Autolykos2PowValidation
import sigma.reflection.RClass
import sigma.serialization.CoreByteWriter.ArgInfo
import sigma.serialization.{DataSerializer, SigmaByteWriter, SigmaSerializer}
import sigma.util.NBitsUtils
import sigma.utils.SparseArrayContainer
import scala.annotation.unused
/** Base type for all companions of AST nodes of sigma lang. */
trait SigmaNodeCompanion
/** 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 MethodsContainer {
def unapply(methodName: String): Option[SMethod] = methods.find(_.name == methodName)
}
/** Base trait for all method containers (which store methods and properties) */
sealed trait MethodsContainer {
/** Type for which this container defines methods. */
def ownerType: STypeCompanion
override def toString: String =
getClass.getSimpleName.stripSuffix("$") // e.g. SInt, SCollection, etc
/** Represents class of `this`. */
lazy val thisRClass: RClass[_] = RClass(this.getClass)
def typeId: Byte = ownerType.typeId
def typeName: String = ownerType.typeName
/** 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. */
def methods: Seq[SMethod] = { //todo: consider versioned caching
val ms = getMethods().toArray
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
}
private def _methodsMap: Map[Byte, Map[Byte, SMethod]] = methods //todo: consider versioned caching
.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 ValidationException which can be checked for soft-fork condition.
* It delegate to getMethodById to lookup method.
*
* @see getMethodById
*/
def methodById(methodId: Byte): SMethod = {
if (VersionContext.current.isV6SoftForkActivated) {
ValidationRules.CheckAndGetMethodV6(this, methodId)
} else {
ValidationRules.CheckAndGetMethod(this, methodId)
}
}
/** Finds a method descriptor [[SMethod]] for the given name. */
def method(methodName: String): Option[SMethod] = methods.find(_.name == methodName)
/** Looks up the method descriptor by the method name. */
def getMethodByName(name: String): SMethod = methods.find(_.name == name).get
}
object MethodsContainer {
private val methodsV5 = Array(
SByteMethods,
SShortMethods,
SIntMethods,
SLongMethods,
SBigIntMethods,
SBooleanMethods,
SStringMethods,
SGroupElementMethods,
SSigmaPropMethods,
SBoxMethods,
SAvlTreeMethods,
SHeaderMethods,
SPreHeaderMethods,
SGlobalMethods,
SContextMethods,
SCollectionMethods,
SOptionMethods,
STupleMethods,
SUnitMethods,
SAnyMethods
)
private val methodsV6 = methodsV5 ++ Seq(SUnsignedBigIntMethods)
private val containersV5 = new SparseArrayContainer[MethodsContainer](methodsV5.map(m => (m.typeId, m)))
private val containersV6 = new SparseArrayContainer[MethodsContainer](methodsV6.map(m => (m.typeId, m)))
def contains(typeId: TypeCode): Boolean = {
if (VersionContext.current.isV6SoftForkActivated) {
containersV6.contains(typeId)
} else {
containersV5.contains(typeId)
}
}
def apply(typeId: TypeCode): MethodsContainer = {
if (VersionContext.current.isV6SoftForkActivated) {
containersV6(typeId)
} else {
containersV5(typeId)
}
}
/** Finds the method of the give type.
*
* @param tpe type of the object for which the method is looked up
* @param methodName name of the method
* @return method descriptor or None if not found
*/
def getMethod(tpe: SType, methodName: String): Option[SMethod] = tpe match {
case tup: STuple =>
STupleMethods.getTupleMethod(tup, methodName)
case _ =>
if (VersionContext.current.isV6SoftForkActivated) {
containersV6.get(tpe.typeCode).flatMap(_.method(methodName))
} else {
containersV5.get(tpe.typeCode).flatMap(_.method(methodName))
}
}
}
trait MonoTypeMethods extends MethodsContainer {
def ownerType: SMonoType
/** 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.ownerType, 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.ownerType, tpeRes), id, valueCompanion.costKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(valueCompanion, "")
}
trait SNumericTypeMethods extends MonoTypeMethods {
import SNumericTypeMethods.tNum
private val subst = Map(tNum -> this.ownerType)
val v5Methods = {
SNumericTypeMethods.v5Methods.map { m =>
m.copy(stype = applySubst(m.stype, subst).asFunc)
}
}
val v6Methods = {
SNumericTypeMethods.v6Methods.map { m =>
m.copy(
objType = this, // associate the method with the concrete numeric type
stype = applySubst(m.stype, subst).asFunc
)}
}
protected override def getMethods(): Seq[SMethod] = {
if (VersionContext.current.isV6SoftForkActivated) {
super.getMethods() ++ v6Methods
} else {
super.getMethods() ++ v5Methods
}
}
}
object SNumericTypeMethods extends MethodsContainer {
/** Type for which this container defines methods. */
override def ownerType: STypeCompanion = SNumericType
/** 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)
.withUserDefinedInvoke({ (m: SMethod, obj: Any, _: Array[Any]) =>
m.objType match {
case SByteMethods => ByteIsExactIntegral.toBigEndianBytes(obj.asInstanceOf[Byte])
case SShortMethods => ShortIsExactIntegral.toBigEndianBytes(obj.asInstanceOf[Short])
case SIntMethods => IntIsExactIntegral.toBigEndianBytes(obj.asInstanceOf[Int])
case SLongMethods => LongIsExactIntegral.toBigEndianBytes(obj.asInstanceOf[Long])
case SBigIntMethods => obj.asInstanceOf[BigInt].toBytes
case SUnsignedBigIntMethods => obj.asInstanceOf[UnsignedBigInt].toBytes
}
})
.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)
.withUserDefinedInvoke({ (m: SMethod, obj: Any, _: Array[Any]) =>
m.objType match {
case SByteMethods => ByteIsExactIntegral.toBits(obj.asInstanceOf[Byte])
case SShortMethods => ShortIsExactIntegral.toBits(obj.asInstanceOf[Short])
case SIntMethods => IntIsExactIntegral.toBits(obj.asInstanceOf[Int])
case SLongMethods => LongIsExactIntegral.toBits(obj.asInstanceOf[Long])
case SBigIntMethods => BigIntIsExactIntegral.toBits(obj.asInstanceOf[BigInt])
case SUnsignedBigIntMethods => UnsignedBigIntIsExactIntegral.toBits(obj.asInstanceOf[UnsignedBigInt])
}
})
.withInfo(PropertyCall,
""" Returns a big-endian representation of this numeric in a collection of Booleans.
| Each boolean corresponds to one bit.
""".stripMargin)
/** Cost of inverting bits of a number. */
val BitwiseOp_CostKind = FixedCost(JitCost(5))
val BitwiseInverseMethod: SMethod = SMethod(
this, "bitwiseInverse", SFunc(tNum, tNum), 8, BitwiseOp_CostKind)
.withIRInfo(MethodCallIrBuilder)
.withUserDefinedInvoke({ (m: SMethod, obj: Any, _: Array[Any]) =>
m.objType match {
case SByteMethods => ByteIsExactIntegral.bitwiseInverse(obj.asInstanceOf[Byte])
case SShortMethods => ShortIsExactIntegral.bitwiseInverse(obj.asInstanceOf[Short])
case SIntMethods => IntIsExactIntegral.bitwiseInverse(obj.asInstanceOf[Int])
case SLongMethods => LongIsExactIntegral.bitwiseInverse(obj.asInstanceOf[Long])
case SBigIntMethods => BigIntIsExactIntegral.bitwiseInverse(obj.asInstanceOf[BigInt])
case SUnsignedBigIntMethods => UnsignedBigIntIsExactIntegral.bitwiseInverse(obj.asInstanceOf[UnsignedBigInt])
}
})
.withInfo(PropertyCall, desc = "Returns bitwise inverse of this numeric. ")
val BitwiseOrMethod: SMethod = SMethod(
this, "bitwiseOr", SFunc(Array(tNum, tNum), tNum), 9, BitwiseOp_CostKind)
.withIRInfo(MethodCallIrBuilder)
.withUserDefinedInvoke({ (m: SMethod, obj: Any, other: Array[Any]) =>
m.objType match {
case SByteMethods => ByteIsExactIntegral.bitwiseOr(obj.asInstanceOf[Byte], other.head.asInstanceOf[Byte])
case SShortMethods => ShortIsExactIntegral.bitwiseOr(obj.asInstanceOf[Short], other.head.asInstanceOf[Short])
case SIntMethods => IntIsExactIntegral.bitwiseOr(obj.asInstanceOf[Int], other.head.asInstanceOf[Int])
case SLongMethods => LongIsExactIntegral.bitwiseOr(obj.asInstanceOf[Long], other.head.asInstanceOf[Long])
case SBigIntMethods => BigIntIsExactIntegral.bitwiseOr(obj.asInstanceOf[BigInt], other.head.asInstanceOf[BigInt])
case SUnsignedBigIntMethods => UnsignedBigIntIsExactIntegral.bitwiseOr(obj.asInstanceOf[UnsignedBigInt], other.head.asInstanceOf[UnsignedBigInt])
}
})
.withInfo(MethodCall,
""" Returns bitwise or of this numeric and provided one. """.stripMargin,
ArgInfo("that", "A numeric value to calculate or with."))
val BitwiseAndMethod: SMethod = SMethod(
this, "bitwiseAnd", SFunc(Array(tNum, tNum), tNum), 10, BitwiseOp_CostKind)
.withIRInfo(MethodCallIrBuilder)
.withUserDefinedInvoke({ (m: SMethod, obj: Any, other: Array[Any]) =>
m.objType match {
case SByteMethods => ByteIsExactIntegral.bitwiseAnd(obj.asInstanceOf[Byte], other.head.asInstanceOf[Byte])
case SShortMethods => ShortIsExactIntegral.bitwiseAnd(obj.asInstanceOf[Short], other.head.asInstanceOf[Short])
case SIntMethods => IntIsExactIntegral.bitwiseAnd(obj.asInstanceOf[Int], other.head.asInstanceOf[Int])
case SLongMethods => LongIsExactIntegral.bitwiseAnd(obj.asInstanceOf[Long], other.head.asInstanceOf[Long])
case SBigIntMethods => BigIntIsExactIntegral.bitwiseAnd(obj.asInstanceOf[BigInt], other.head.asInstanceOf[BigInt])
case SUnsignedBigIntMethods => UnsignedBigIntIsExactIntegral.bitwiseAnd(obj.asInstanceOf[UnsignedBigInt], other.head.asInstanceOf[UnsignedBigInt])
}
})
.withInfo(MethodCall,
""" Returns bitwise and of this numeric and provided one. """.stripMargin,
ArgInfo("that", "A numeric value to calculate and with."))
val BitwiseXorMethod: SMethod = SMethod(
this, "bitwiseXor", SFunc(Array(tNum, tNum), tNum), 11, BitwiseOp_CostKind)
.withIRInfo(MethodCallIrBuilder)
.withUserDefinedInvoke({ (m: SMethod, obj: Any, other: Array[Any]) =>
m.objType match {
case SByteMethods => ByteIsExactIntegral.bitwiseXor(obj.asInstanceOf[Byte], other.head.asInstanceOf[Byte])
case SShortMethods => ShortIsExactIntegral.bitwiseXor(obj.asInstanceOf[Short], other.head.asInstanceOf[Short])
case SIntMethods => IntIsExactIntegral.bitwiseXor(obj.asInstanceOf[Int], other.head.asInstanceOf[Int])
case SLongMethods => LongIsExactIntegral.bitwiseXor(obj.asInstanceOf[Long], other.head.asInstanceOf[Long])
case SBigIntMethods => BigIntIsExactIntegral.bitwiseXor(obj.asInstanceOf[BigInt], other.head.asInstanceOf[BigInt])
case SUnsignedBigIntMethods => UnsignedBigIntIsExactIntegral.bitwiseXor(obj.asInstanceOf[UnsignedBigInt], other.head.asInstanceOf[UnsignedBigInt])
}
})
.withInfo(MethodCall,
""" Returns bitwise xor of this numeric and provided one. """.stripMargin,
ArgInfo("that", "A numeric value to calculate xor with."))
val ShiftLeftMethod: SMethod = SMethod(
this, "shiftLeft", SFunc(Array(tNum, SInt), tNum), 12, BitwiseOp_CostKind)
.withIRInfo(MethodCallIrBuilder)
.withUserDefinedInvoke({ (m: SMethod, obj: Any, other: Array[Any]) =>
m.objType match {
case SByteMethods => ByteIsExactIntegral.shiftLeft(obj.asInstanceOf[Byte], other.head.asInstanceOf[Int])
case SShortMethods => ShortIsExactIntegral.shiftLeft(obj.asInstanceOf[Short], other.head.asInstanceOf[Int])
case SIntMethods => IntIsExactIntegral.shiftLeft(obj.asInstanceOf[Int], other.head.asInstanceOf[Int])
case SLongMethods => LongIsExactIntegral.shiftLeft(obj.asInstanceOf[Long], other.head.asInstanceOf[Int])
case SBigIntMethods => BigIntIsExactIntegral.shiftLeft(obj.asInstanceOf[BigInt], other.head.asInstanceOf[Int])
case SUnsignedBigIntMethods => UnsignedBigIntIsExactIntegral.shiftLeft(obj.asInstanceOf[UnsignedBigInt], other.head.asInstanceOf[Int])
}
})
.withInfo(MethodCall,
""" Returns a big-endian representation of this numeric in a collection of Booleans.
| Each boolean corresponds to one bit.
""".stripMargin,
ArgInfo("bits", "Number of bit to shift to the left. Note, that bits value must be non-negative and less than " +
"the size of the number in bits (e.g. 64 for Long, 256 for BigInt)"))
val ShiftRightMethod: SMethod = SMethod(
this, "shiftRight", SFunc(Array(tNum, SInt), tNum), 13, BitwiseOp_CostKind)
.withIRInfo(MethodCallIrBuilder)
.withUserDefinedInvoke({ (m: SMethod, obj: Any, other: Array[Any]) =>
m.objType match {
case SByteMethods => ByteIsExactIntegral.shiftRight(obj.asInstanceOf[Byte], other.head.asInstanceOf[Int])
case SShortMethods => ShortIsExactIntegral.shiftRight(obj.asInstanceOf[Short], other.head.asInstanceOf[Int])
case SIntMethods => IntIsExactIntegral.shiftRight(obj.asInstanceOf[Int], other.head.asInstanceOf[Int])
case SLongMethods => LongIsExactIntegral.shiftRight(obj.asInstanceOf[Long], other.head.asInstanceOf[Int])
case SBigIntMethods => BigIntIsExactIntegral.shiftRight(obj.asInstanceOf[BigInt], other.head.asInstanceOf[Int])
case SUnsignedBigIntMethods => UnsignedBigIntIsExactIntegral.shiftRight(obj.asInstanceOf[UnsignedBigInt], other.head.asInstanceOf[Int])
}
})
.withInfo(MethodCall,
""" Returns a big-endian representation of this numeric in a collection of Booleans.
| Each boolean corresponds to one bit.
""".stripMargin,
ArgInfo("bits", "Number of bit to shift to the right. Note, that bits value must be non-negative and less than " +
"the size of the number in bits (e.g. 64 for Long, 256 for BigInt)"))
lazy val v5Methods = Array(
ToByteMethod, // see Downcast
ToShortMethod, // see Downcast
ToIntMethod, // see Downcast
ToLongMethod, // see Downcast
ToBigIntMethod, // see Downcast
ToBytesMethod,
ToBitsMethod
)
lazy val v6Methods = v5Methods ++ Array(
BitwiseInverseMethod,
BitwiseOrMethod,
BitwiseAndMethod,
BitwiseXorMethod,
ShiftLeftMethod,
ShiftRightMethod
)
protected override def getMethods(): Seq[SMethod] = {
throw new Exception("SNumericTypeMethods.getMethods shouldn't ever be called")
}
/** Collection of names of numeric casting methods (like `toByte`, `toInt`, etc). */
// todo: add unsigned big int
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
}
}
/** Methods of ErgoTree type `Boolean`. */
case object SBooleanMethods extends MonoTypeMethods {
/** Type for which this container defines methods. */
override def ownerType: SMonoType = SBoolean
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"),
)
*/
}
/** Methods of ErgoTree type `Byte`. */
case object SByteMethods extends SNumericTypeMethods {
/** Type for which this container defines methods. */
override def ownerType: SMonoType = SByte
}
/** Methods of ErgoTree type `Short`. */
case object SShortMethods extends SNumericTypeMethods {
/** Type for which this container defines methods. */
override def ownerType: SMonoType = ast.SShort
}
/** Descriptor of ErgoTree type `Int`. */
case object SIntMethods extends SNumericTypeMethods {
/** Type for which this container defines methods. */
override def ownerType: SMonoType = SInt
}
/** Descriptor of ErgoTree type `Long`. */
case object SLongMethods extends SNumericTypeMethods {
/** Type for which this container defines methods. */
override def ownerType: SMonoType = SLong
}
/** Methods of BigInt type. Implemented using [[java.math.BigInteger]]. */
case object SBigIntMethods extends SNumericTypeMethods {
/** Type for which this container defines methods. */
override def ownerType: SMonoType = SBigInt
private val ToUnsignedCostKind = FixedCost(JitCost(5))
//id = 8 to make it after toBits
val ToUnsigned = SMethod(this, "toUnsigned", SFunc(this.ownerType, SUnsignedBigInt), 14, ToUnsignedCostKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(MethodCall,
"Converts non-negative big integer to unsigned type, throws exception on negative big integer.")
private val ToUnsignedModCostKind = FixedCost(JitCost(15))
val ToUnsignedMod = SMethod(this, "toUnsignedMod", SFunc(Array(this.ownerType, SUnsignedBigInt), SUnsignedBigInt), 15, ToUnsignedModCostKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(MethodCall,
"Converts non-negative big integer to unsigned type using cryptographic mod operation.",
ArgInfo("m", "modulo value"))
protected override def getMethods(): Seq[SMethod] = {
if (VersionContext.current.isV6SoftForkActivated) {
super.getMethods() ++ Seq(ToUnsigned, ToUnsignedMod)
} else {
super.getMethods()
}
}
}
/** Methods of UnsignedBigInt type. Implemented using [[java.math.BigInteger]]. */
case object SUnsignedBigIntMethods extends SNumericTypeMethods {
/** Type for which this container defines methods. */
override def ownerType: SMonoType = SUnsignedBigInt
final val ModInverseCostInfo = OperationCostInfo(FixedCost(JitCost(30)), NamedDesc("ModInverseMethodCall"))
val ModInverseMethod = SMethod(this, "modInverse", SFunc(Array(this.ownerType, this.ownerType), this.ownerType), 14, ModInverseCostInfo.costKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(MethodCall,
"Computes modular inverse of a value. Modular inverse of A mod C is the B value that makes A * B mod C = 1.",
ArgInfo("m", "modulo value")
)
final val PlusModCostInfo = OperationCostInfo(FixedCost(JitCost(30)), NamedDesc("ModInverseMethodCall"))
val PlusModMethod = SMethod(this, "plusMod", SFunc(Array(this.ownerType, this.ownerType, this.ownerType), this.ownerType), 15, PlusModCostInfo.costKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(MethodCall, "Modular addition", ArgInfo("that", "Addend") , ArgInfo("m", "modulo value"))
final val SubtractModCostInfo = OperationCostInfo(FixedCost(JitCost(30)), NamedDesc("SubtractModMethodCall"))
val SubtractModMethod = SMethod(this, "subtractMod", SFunc(Array(this.ownerType, this.ownerType, this.ownerType), this.ownerType), 16, SubtractModCostInfo.costKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(MethodCall, "Modular subtraction", ArgInfo("that", "Subtrahend") , ArgInfo("m", "modulo value"))
final val MultiplyModCostInfo = OperationCostInfo(FixedCost(JitCost(40)), NamedDesc("MultiplyModMethodCall"))
val MultiplyModMethod = SMethod(this, "multiplyMod", SFunc(Array(this.ownerType, this.ownerType, this.ownerType), this.ownerType), 17, MultiplyModCostInfo.costKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(MethodCall, "Modular multiplication", ArgInfo("that", "Multiplier") , ArgInfo("m", "modulo value"))
final val ModCostInfo = OperationCostInfo(FixedCost(JitCost(20)), NamedDesc("ModMethodCall"))
val ModMethod = SMethod(this, "mod", SFunc(Array(this.ownerType, this.ownerType), this.ownerType), 18, ModCostInfo.costKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(MethodCall, "Cryptographic modulo operation", ArgInfo("m", "Modulo value"))
final val ToSignedCostInfo = OperationCostInfo(FixedCost(JitCost(10)), NamedDesc("ToSignedMethodCall"))
val ToSignedMethod = SMethod(this, "toSigned", SFunc(Array(this.ownerType), SBigInt), 19, ToSignedCostInfo.costKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(MethodCall, "Convert this unsigned big int to signed (with possible exception if leftmost bit is set to 1).")
// no 6.0 versioning here as it is done in method containers
protected override def getMethods(): Seq[SMethod] = {
super.getMethods() ++ Seq(
ModInverseMethod,
PlusModMethod,
SubtractModMethod,
MultiplyModMethod,
ModMethod,
ToSignedMethod
)
}
}
/** Methods of type `String`. */
case object SStringMethods extends MonoTypeMethods {
/** Type for which this container defines methods. */
override def ownerType: SMonoType = SString
}
/** Methods of type `GroupElement`. */
case object SGroupElementMethods extends MonoTypeMethods {
/** Type for which this container defines methods. */
override def ownerType: SMonoType = SGroupElement
/** Cost of: 1) serializing EcPointType to bytes 2) packing them in Coll. */
val GetEncodedCostKind = FixedCost(JitCost(250))
/** The following SMethod instances are descriptors of methods defined in `GroupElement` type. */
lazy val GetEncodedMethod: SMethod = SMethod(
this, "getEncoded", SFunc(Array(this.ownerType), SByteArray), 2, GetEncodedCostKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(PropertyCall, "Get an encoding of the point value.")
lazy val ExponentiateMethod: SMethod = SMethod(
this, "exp", SFunc(Array(this.ownerType, SBigInt), this.ownerType), 3, Exponentiate.costKind)
.withIRInfo({ case (builder, obj, _, Seq(arg), _) =>
builder.mkExponentiate(obj.asGroupElement, arg.asBigInt)
})
.withInfo(Exponentiate,
"Exponentiate this \\lst{GroupElement} to the given number. Returns this to the power of k",
ArgInfo("k", "The power"))
lazy val ExponentiateUnsignedMethod: SMethod = SMethod(
this, "expUnsigned", SFunc(Array(this.ownerType, SUnsignedBigInt), this.ownerType), 6, Exponentiate.costKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo("Exponentiate this \\lst{GroupElement} to the given number. Returns this to the power of k",
ArgInfo("k", "The power"))
lazy val MultiplyMethod: SMethod = SMethod(
this, "multiply", SFunc(Array(this.ownerType, SGroupElement), this.ownerType), 4, MultiplyGroup.costKind)
.withIRInfo({ case (builder, obj, _, Seq(arg), _) =>
builder.mkMultiplyGroup(obj.asGroupElement, arg.asGroupElement)
})
.withInfo(MultiplyGroup, "Group operation.", ArgInfo("other", "other element of the group"))
/** Cost of: 1) calling EcPoint.negate 2) wrapping in GroupElement. */
val Negate_CostKind = FixedCost(JitCost(45))
lazy val NegateMethod: SMethod = SMethod(
this, "negate", SFunc(this.ownerType, this.ownerType), 5, Negate_CostKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(PropertyCall, "Inverse element of the group.")
protected override def getMethods(): Seq[SMethod] = {
/* TODO soft-fork: https://github.com/ScorexFoundation/sigmastate-interpreter/issues/479
SMethod(this, "isIdentity", SFunc(this, SBoolean), 1)
.withInfo(PropertyCall, "Checks if this value is identity element of the eliptic curve group."),
*/
val v5Methods = Seq(
GetEncodedMethod,
ExponentiateMethod,
MultiplyMethod,
NegateMethod)
super.getMethods() ++ (if (VersionContext.current.isV6SoftForkActivated) {
v5Methods ++ Seq(ExponentiateUnsignedMethod)
} else {
v5Methods
})
}
}
/** Methods of type `SigmaProp` which represent sigma-protocol propositions. */
case object SSigmaPropMethods extends MonoTypeMethods {
/** Type for which this container defines methods. */
override def ownerType: SMonoType = SSigmaProp
/** The maximum size of SigmaProp value in serialized byte array representation. */
val MaxSizeInBytes: Long = SigmaConstants.MaxSigmaPropSizeInBytes.value
val PropBytes = "propBytes"
val IsProven = "isProven"
lazy val PropBytesMethod = SMethod(
this, PropBytes, SFunc(this.ownerType, SByteArray), 1, SigmaPropBytes.costKind)
.withInfo(SigmaPropBytes, "Serialized bytes of this sigma proposition taken as ErgoTree.")
lazy val IsProvenMethod = SMethod(this, IsProven, SFunc(this.ownerType, SBoolean), 2, null)
.withInfo(// available only at frontend of ErgoScript
"Verify that sigma proposition is proven.")
protected override def getMethods() = super.getMethods() ++ Seq(
PropBytesMethod, IsProvenMethod
)
}
/** Any other type is implicitly subtype of this type. */
case object SAnyMethods extends MonoTypeMethods {
override def ownerType: SMonoType = SAny
}
/** The type with single inhabitant value `()` */
case object SUnitMethods extends MonoTypeMethods {
/** Type for which this container defines methods. */
override def ownerType = SUnit
}
object SOptionMethods extends MethodsContainer {
/** Type for which this container defines methods. */
override def ownerType: STypeCompanion = SOption
/** Code of `Option[_]` type constructor. */
val OptionTypeConstrId = 3
/** Type code for `Option[T] for some T` type used in TypeSerializer. */
val OptionTypeCode: TypeCode = ((SPrimType.MaxPrimTypeCode + 1) * OptionTypeConstrId).toByte
/** Code of `Option[Coll[_]]` type constructor. */
val OptionCollectionTypeConstrId = 4
/** Type code for `Option[Coll[T]] for some T` type used in TypeSerializer. */
val OptionCollectionTypeCode: TypeCode = ((SPrimType.MaxPrimTypeCode + 1) * OptionCollectionTypeConstrId).toByte
val IsDefined = "isDefined"
val Get = "get"
val GetOrElse = "getOrElse"
import SType.{paramR, paramT, tR, tT}
/** Type descriptor of `this` argument used in the methods below. */
val ThisType = SOption(tT)
/** The following SMethod instances are descriptors of methods defined in `Option` type. */
val IsDefinedMethod = SMethod(
this, IsDefined, SFunc(ThisType, SBoolean), 2, OptionIsDefined.costKind)
.withIRInfo({
case (builder, obj, _, args, _) if args.isEmpty => builder.mkOptionIsDefined(obj.asValue[SOption[SType]])
})
.withInfo(OptionIsDefined,
"Returns \\lst{true} if the option is an instance of \\lst{Some}, \\lst{false} otherwise.")
val GetMethod = SMethod(this, Get, SFunc(ThisType, tT), 3, OptionGet.costKind)
.withIRInfo({
case (builder, obj, _, args, _) if args.isEmpty => builder.mkOptionGet(obj.asValue[SOption[SType]])
})
.withInfo(OptionGet,
"""Returns the option's value. The option must be nonempty. Throws exception if the option is empty.""")
lazy val GetOrElseMethod = SMethod(
this, GetOrElse, SFunc(Array(ThisType, tT), tT, Array[STypeParam](tT)), 4, OptionGetOrElse.costKind)
.withIRInfo(irBuilder = {
case (builder, obj, _, Seq(d), _) => builder.mkOptionGetOrElse(obj.asValue[SOption[SType]], d)
})
.withInfo(OptionGetOrElse,
"""Returns the option's value if the option is nonempty, otherwise
|return the result of evaluating \lst{default}.
""".stripMargin, ArgInfo("default", "the default value"))
// TODO soft-fork: https://github.com/ScorexFoundation/sigmastate-interpreter/issues/479
// val FoldMethod = SMethod(
// this, Fold, SFunc(Array(ThisType, tR, SFunc(tT, tR)), tR, Array[STypeParam](tT, tR)), 5, FixedCost(JitCost(1)))
// .withInfo(MethodCall,
// """Returns the result of applying \lst{f} to this option's
// | value if the option is nonempty. Otherwise, evaluates
// | expression \lst{ifEmpty}.
// | This is equivalent to \lst{option map f getOrElse ifEmpty}.
// """.stripMargin,
// ArgInfo("ifEmpty", "the expression to evaluate if empty"),
// ArgInfo("f", "the function to apply if nonempty"))
val MapMethod = SMethod(this, "map",
SFunc(Array(ThisType, SFunc(tT, tR)), SOption(tR), Array(paramT, paramR)), 7, FixedCost(JitCost(20)))
.withIRInfo(MethodCallIrBuilder)
.withInfo(MethodCall,
"""Returns a \lst{Some} containing the result of applying \lst{f} to this option's
| value if this option is nonempty.
| Otherwise return \lst{None}.
""".stripMargin, ArgInfo("f", "the function to apply"))
val FilterMethod = SMethod(this, "filter",
SFunc(Array(ThisType, SFunc(tT, SBoolean)), ThisType, Array(paramT)), 8, FixedCost(JitCost(20)))
.withIRInfo(MethodCallIrBuilder)
.withInfo(MethodCall,
"""Returns this option if it is nonempty and applying the predicate \lst{p} to
| this option's value returns true. Otherwise, return \lst{None}.
""".stripMargin, ArgInfo("p", "the predicate used for testing"))
override protected def getMethods(): Seq[SMethod] = super.getMethods() ++
Seq(
IsDefinedMethod,
GetMethod,
GetOrElseMethod,
/* TODO soft-fork: https://github.com/ScorexFoundation/sigmastate-interpreter/issues/479
FoldMethod,
*/
MapMethod,
FilterMethod
)
/** Creates a descriptor of `Option[T]` type for the given element type `T`. */
def apply[T <: SType](implicit elemType: T, @unused ov: Overloaded1): SOption[T] = SOption(elemType)
}
object SCollectionMethods extends MethodsContainer with MethodByNameUnapply {
import SType.{paramIV, paramIVSeq, paramOV}
/** Type for which this container defines methods. */
override def ownerType: STypeCompanion = SCollection
/** Helper descriptors reused across different method descriptors. */
def tIV = SType.tIV
def tOV = SType.tOV
/** This descriptors are instantiated once here and then reused. */
val ThisType = SCollection(tIV)
val tOVColl = SCollection(tOV)
val tPredicate = SFunc(tIV, SBoolean)
/** The following SMethod instances are descriptors of methods defined in `Coll` type. */
val SizeMethod = SMethod(this, "size", SFunc(ThisType, SInt), 1, SizeOf.costKind)
.withInfo(SizeOf, "The size of the collection in elements.")
val GetOrElseMethod = SMethod(
this, "getOrElse", SFunc(Array(ThisType, SInt, tIV), tIV, paramIVSeq), 2, DynamicCost)
.withIRInfo({ case (builder, obj, _, Seq(index, defaultValue), _) =>
val index1 = index.asValue[SInt.type]
val defaultValue1 = defaultValue.asValue[SType]
builder.mkByIndex(obj.asValue[SCollection[SType]], index1, Some(defaultValue1))
})
.withInfo(ByIndex, "Return the element of collection if \\lst{index} is in range \\lst{0 .. size-1}",
ArgInfo("index", "index of the element of this collection"),
ArgInfo("default", "value to return when \\lst{index} is out of range"))
/** Implements evaluation of Coll.getOrElse method call ErgoTree node.
* Called via reflection based on naming convention.
* @see SMethod.evalMethod
*/
def getOrElse_eval[A](mc: MethodCall, xs: Coll[A], i: Int, default: A)(implicit E: ErgoTreeEvaluator): A = {
E.addCost(ByIndex.costKind, mc.method.opDesc)
// the following lines should be semantically the same as in ByIndex.eval
Value.checkType(mc.args.last.tpe, default)
xs.getOrElse(i, default)
}
val MapMethod = SMethod(this, "map",
SFunc(Array(ThisType, SFunc(tIV, tOV)), tOVColl, Array(paramIV, paramOV)), 3, MapCollection.costKind)
.withIRInfo({
case (builder, obj, _, Seq(mapper), _) => builder.mkMapCollection(obj.asValue[SCollection[SType]], mapper.asFunc)
})
.withInfo(MapCollection,
""" Builds a new collection by applying a function to all elements of this collection.
| Returns a new collection of type \lst{Coll[B]} resulting from applying the given function
| \lst{f} to each element of this collection and collecting the results.
""".stripMargin,
ArgInfo("f", "the function to apply to each element"))
/** Implements evaluation of Coll.map method call ErgoTree node.
* Called via reflection based on naming convention.
* @see SMethod.evalMethod
*/
def map_eval[A,B](mc: MethodCall, xs: Coll[A], f: A => B)(implicit E: ErgoTreeEvaluator): Coll[B] = {
val tpeB = mc.tpe.asInstanceOf[SCollection[SType]].elemType
val tB = Evaluation.stypeToRType(tpeB).asInstanceOf[RType[B]]
E.addSeqCostNoOp(MapCollection.costKind, xs.length, mc.method.opDesc)
xs.map(f)(tB)
}
val ExistsMethod = SMethod(this, "exists",
SFunc(Array(ThisType, tPredicate), SBoolean, paramIVSeq), 4, Exists.costKind)
.withIRInfo({
case (builder, obj, _, Seq(c), _) => builder.mkExists(obj.asValue[SCollection[SType]], c.asFunc)
})
.withInfo(Exists,
"""Tests whether a predicate holds for at least one element of this collection.
|Returns \lst{true} if the given predicate \lst{p} is satisfied by at least one element of this collection, otherwise \lst{false}
""".stripMargin,
ArgInfo("p", "the predicate used to test elements"))
val FoldMethod = SMethod(
this, "fold",
SFunc(Array(ThisType, tOV, SFunc(Array(tOV, tIV), tOV)), tOV, Array(paramIV, paramOV)),
5, Fold.costKind)
.withIRInfo({
case (builder, obj, _, Seq(z, op), _) => builder.mkFold(obj.asValue[SCollection[SType]], z, op.asFunc)
})
.withInfo(Fold, "Applies a binary operator to a start value and all elements of this collection, going left to right.",
ArgInfo("zero", "a starting value"),
ArgInfo("op", "the binary operator"))
val ForallMethod = SMethod(this, "forall",
SFunc(Array(ThisType, tPredicate), SBoolean, paramIVSeq), 6, ForAll.costKind)
.withIRInfo({
case (builder, obj, _, Seq(c), _) => builder.mkForAll(obj.asValue[SCollection[SType]], c.asFunc)
})
.withInfo(ForAll,
"""Tests whether a predicate holds for all elements of this collection.
|Returns \lst{true} if this collection is empty or the given predicate \lst{p}
|holds for all elements of this collection, otherwise \lst{false}.
""".stripMargin,
ArgInfo("p", "the predicate used to test elements"))
val SliceMethod = SMethod(this, "slice",
SFunc(Array(ThisType, SInt, SInt), ThisType, paramIVSeq), 7, Slice.costKind)
.withIRInfo({
case (builder, obj, _, Seq(from, until), _) =>
builder.mkSlice(obj.asCollection[SType], from.asIntValue, until.asIntValue)
})
.withInfo(Slice,
"""Selects an interval of elements. The returned collection is made up
| of all elements \lst{x} which satisfy the invariant:
| \lst{
| from <= indexOf(x) < until
| }
""".stripMargin,
ArgInfo("from", "the lowest index to include from this collection"),
ArgInfo("until", "the lowest index to EXCLUDE from this collection"))
val FilterMethod = SMethod(this, "filter",
SFunc(Array(ThisType, tPredicate), ThisType, paramIVSeq), 8, Filter.costKind)
.withIRInfo({
case (builder, obj, _, Seq(l), _) => builder.mkFilter(obj.asValue[SCollection[SType]], l.asFunc)
})
.withInfo(Filter,
"""Selects all elements of this collection which satisfy a predicate.
| Returns a new collection consisting of all elements of this collection that satisfy the given
| predicate \lst{p}. The order of the elements is preserved.
""".stripMargin,
ArgInfo("p", "the predicate used to test elements."))
val AppendMethod = SMethod(this, "append",
SFunc(Array(ThisType, ThisType), ThisType, paramIVSeq), 9, Append.costKind)
.withIRInfo({
case (builder, obj, _, Seq(xs), _) =>
builder.mkAppend(obj.asCollection[SType], xs.asCollection[SType])
})
.withInfo(Append, "Puts the elements of other collection after the elements of this collection (concatenation of 2 collections)",
ArgInfo("other", "the collection to append at the end of this"))
val ApplyMethod = SMethod(this, "apply",
SFunc(Array(ThisType, SInt), tIV, Array[STypeParam](tIV)), 10, ByIndex.costKind)
.withInfo(ByIndex,
"""The element at given index.
| Indices start at \lst{0}; \lst{xs.apply(0)} is the first element of collection \lst{xs}.
| Note the indexing syntax \lst{xs(i)} is a shorthand for \lst{xs.apply(i)}.
| Returns the element at the given index.
| Throws an exception if \lst{i < 0} or \lst{length <= i}
""".stripMargin, ArgInfo("i", "the index"))
/** Cost of creating a collection of indices */
val IndicesMethod_CostKind = PerItemCost(
baseCost = JitCost(20), perChunkCost = JitCost(2), chunkSize = 16)
val IndicesMethod = SMethod(
this, "indices", SFunc(ThisType, SCollection(SInt)), 14, IndicesMethod_CostKind)
.withIRInfo(MethodCallIrBuilder)
.withInfo(PropertyCall,
"""Produces the range of all indices of this collection as a new collection
| containing [0 .. length-1] values.
""".stripMargin)
/** Implements evaluation of Coll.indices method call ErgoTree node.
* Called via reflection based on naming convention.
* @see SMethod.evalMethod
*/
def indices_eval[A, B](mc: MethodCall, xs: Coll[A])
(implicit E: ErgoTreeEvaluator): Coll[Int] = {
val m = mc.method
E.addSeqCost(m.costKind.asInstanceOf[PerItemCost], xs.length, m.opDesc) { () =>
xs.indices
}
}
/** BaseCost:
* 1) base cost of Coll.flatMap
* PerChunkCost:
* 1) cost of Coll.flatMap (per item)
* 2) new collection is allocated for each item
* 3) each collection is then appended to the resulting collection */
val FlatMapMethod_CostKind = PerItemCost(
baseCost = JitCost(60), perChunkCost = JitCost(10), chunkSize = 8)
val FlatMapMethod = SMethod(this, "flatMap",
SFunc(Array(ThisType, SFunc(tIV, tOVColl)), tOVColl, Array(paramIV, paramOV)),
15, FlatMapMethod_CostKind)
.withIRInfo(
MethodCallIrBuilder,
javaMethodOf[Coll[_], Function1[_,_], RType[_]]("flatMap"),
{ mtype => Array(mtype.tRange.asCollection[SType].elemType) })
.withInfo(MethodCall,
""" Builds a new collection by applying a function to all elements of this collection
| and using the elements of the resulting collections.
| Function \lst{f} is constrained to be of the form \lst{x => x.someProperty}, otherwise
| it is illegal.
| Returns a new collection of type \lst{Coll[B]} resulting from applying the given collection-valued function
| \lst{f} to each element of this collection and concatenating the results.
""".stripMargin, ArgInfo("f", "the function to apply to each element."))
/** We assume all flatMap body patterns have similar execution cost. */
final val CheckFlatmapBody_Info = OperationCostInfo(
PerItemCost(baseCost = JitCost(20), perChunkCost = JitCost(20), chunkSize = 1),
NamedDesc("CheckFlatmapBody"))
/** This patterns recognize all expressions, which are allowed as lambda body
* of flatMap. Other bodies are rejected with throwing exception.
*/
val flatMap_BodyPatterns = Array[PartialFunction[SValue, Int]](
{ case MethodCall(ValUse(id, _), _, args, _) if args.isEmpty => id },
{ case ExtractScriptBytes(ValUse(id, _)) => id },
{ case ExtractId(ValUse(id, _)) => id },
{ case SigmaPropBytes(ValUse(id, _)) => id },