diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/Evaluation.scala b/core/shared/src/main/scala/sigma/Evaluation.scala similarity index 56% rename from interpreter/shared/src/main/scala/sigmastate/eval/Evaluation.scala rename to core/shared/src/main/scala/sigma/Evaluation.scala index 8771fe2b32..893bdfb9f8 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/Evaluation.scala +++ b/core/shared/src/main/scala/sigma/Evaluation.scala @@ -1,48 +1,16 @@ -package sigmastate.eval +package sigma -import org.ergoplatform._ -import sigma.data._ -import sigma.data.RType._ -import sigmastate.SType._ -import sigmastate.Values.SigmaBoolean -import sigmastate._ import debox.cfor -import sigmastate.exceptions.CostLimitException +import sigma.ast.SType +import sigma.data.RType._ +import sigma.data._ +import sigma.ast._ -import scala.reflect.ClassTag -import scala.util.Try // TODO refactor: find better place for this methods after code cleanup and repo reorganization /** Helper methods used as part of ErgoTree evaluation. */ object Evaluation { - import sigma._ - import sigma._ - - def msgCostLimitError(cost: Long, limit: Long) = s"Estimated execution cost $cost exceeds the limit $limit" - - /** Helper method to accumulate cost while checking limit. - * - * @param current current cost value - * @param delta additional cost to add to the current value - * @param limit total cost limit - * @param msgSuffix use case-specific error message suffix - * @return new increased cost when it doesn't exceed the limit - * @throws CostLimitException - */ - def addCostChecked(current: Long, delta: Long, limit: Long, msgSuffix: => String = ""): Long = { - val newCost = java7.compat.Math.addExact(current, delta) - if (newCost > limit) { - throw new CostLimitException( - estimatedCost = newCost, - message = { - val suffix = if (msgSuffix.isEmpty) "" else s": $msgSuffix" - msgCostLimitError(newCost, limit) + suffix - }, - cause = None) - } - newCost - } /** Transforms a serializable ErgoTree type descriptor to the corresponding RType descriptor of SigmaDsl, * which is used during evaluation. @@ -101,14 +69,15 @@ object Evaluation { case BigIntRType => SBigInt case GroupElementRType => SGroupElement case AvlTreeRType => SAvlTree - case ot: OptionType[_] => sigmastate.SOption(rtypeToSType(ot.tA)) + case ot: OptionType[_] => SOption(rtypeToSType(ot.tA)) case BoxRType => SBox case ContextRType => SContext case SigmaDslBuilderRType => SGlobal case HeaderRType => SHeader case PreHeaderRType => SPreHeader case SigmaPropRType => SSigmaProp - case SigmaBooleanRType => SSigmaProp + // TODO remove commented code below after full sync test + // case SigmaBooleanRType => SSigmaProp // this is not used in consensus code case tup: TupleType => STuple(tup.items.map(t => rtypeToSType(t))) case at: ArrayType[_] => SCollection(rtypeToSType(at.tA)) case ct: CollType[_] => SCollection(rtypeToSType(ct.tItem)) @@ -117,47 +86,6 @@ object Evaluation { case _ => sys.error(s"Don't know how to convert RType $t to SType") } - /** Tries to reconstruct RType of the given value. - * If not successfull returns failure. - * NOTE, this method is NOT used in consensus. */ - def rtypeOf(value: Any): Try[RType[_]] = Try { value match { - case arr if arr.getClass.isArray => - val itemClass = arr.getClass.getComponentType - if (itemClass.isPrimitive) { - val itemTag = ClassTag[Any](itemClass) - RType.fromClassTag(itemTag) - } else - sys.error(s"Cannot compute rtypeOf($value): non-primitive type of array items") - - case coll: Coll[_] => collRType(coll.tItem) - - // all primitive types - case _: Boolean => BooleanType - case _: Byte => ByteType - case _: Short => ShortType - case _: Int => IntType - case _: Long => LongType - case _: String => StringType - case _: Unit => UnitType - case _: sigma.BigInt => BigIntRType - case _: GroupElement => GroupElementRType - // TODO remove this case to allow removing of RType instances - // for ErgoBox, AvlTreeData, SigmaBoolean. - // RType describes only the types that can be put into registers, context variables and - // used as ErgoTree evaluation intermediate values. - case _: ErgoBox => ErgoBoxRType - case _: Box => BoxRType - - case _: AvlTreeData => AvlTreeDataRType // TODO remove this RType - case _: AvlTree => AvlTreeRType - - case _: SigmaBoolean => SigmaBooleanRType // TODO remove this RType - case _: SigmaProp => SigmaPropRType - case _: Context => ContextRType - case _ => - sys.error(s"Don't know how to compute typeOf($value)") - }} - /** Convert SigmaDsl representation of tuple to ErgoTree serializable representation. */ def fromDslTuple(value: Any, tupleTpe: STuple): Coll[Any] = value match { case t: Tuple2[_,_] => TupleColl(t._1, t._2) diff --git a/core/shared/src/main/scala/sigma/ast/SType.scala b/core/shared/src/main/scala/sigma/ast/SType.scala new file mode 100644 index 0000000000..7e3207ec44 --- /dev/null +++ b/core/shared/src/main/scala/sigma/ast/SType.scala @@ -0,0 +1,844 @@ +package sigma.ast + +import sigma.Evaluation.stypeToRType +import sigma.ast.SCollection.SByteArray +import sigma.ast.SType.TypeCode +import sigma.data.OverloadHack.Overloaded1 +import sigma.data.{CBigInt, Nullable, SigmaConstants} +import sigma.reflection.{RClass, RMethod, ReflectionData} +import sigma.util.Extensions.{IntOps, LongOps, ShortOps} +import sigma.{AvlTree, BigInt, Box, Coll, Context, Evaluation, GroupElement, Header, PreHeader, SigmaDslBuilder, SigmaProp} + +import java.math.BigInteger + +/** Base type for all AST nodes of ErgoTree. */ +trait SigmaNode extends Product + +/** 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 + + + /** 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 + + /** 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[SType]( + 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: 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 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 = ReflectionData + + /** 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("$", "") + } + } + + /** 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) +} + + +/** 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 +} + +/** Type variable which is used in generic method/func signatures. + * Used by ErgoScript compiler IR and eliminated during compilation. + * It is not used in ErgoTree. + */ +case class STypeVar(name: String) extends SType { + require(name.length <= 255, "name is too long") + override type WrappedType = Any + override val typeCode = STypeVar.TypeCode + override def toString = name + override def toTermString: String = name +} +object STypeVar { + val TypeCode: TypeCode = 103: Byte + implicit def liftString(n: String): STypeVar = STypeVar(n) + + /** Immutable empty array, can be used to avoid repeated allocations. */ + val EmptyArray = Array.empty[STypeVar] + + /** Immutable empty IndexedSeq, can be used to avoid repeated allocations. */ + val EmptySeq: IndexedSeq[STypeVar] = EmptyArray +} + +/** Base trait for all pre-defined types which are not necessary primitive (e.g. Box, AvlTree). + */ +trait SPredefType extends SType { +} + +/** Base type for SBoolean and SSigmaProp. */ +trait SLogical extends SType { +} + +/** 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] +} + +/** 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 +} + +/** Base trait for all types which have methods (and properties) */ +trait SProduct extends SType { +} + +/** Monomorphic type descriptor i.e. a type without generic parameters. + * @see `SGenericType` + */ +trait SMonoType extends SType with STypeCompanion { +} + +/** Marker trait for all numeric types. */ +trait SNumericType extends SProduct with STypeCompanion { + /** 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: 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.") +} + +/** 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 val reprClass: RClass[_] = RClass(classOf[Boolean]) + override def typeId = typeCode + implicit def typeBoolean: SBoolean.type = this +} + +/** 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]) + implicit def typeByte: SByte.type = this + 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]) + implicit val typeShort: SShort.type = this + 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 + implicit def typeInt: SInt.type = this + 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 + implicit def typeLong: SLong.type = this + + override def upcast(v: AnyVal): Long = v match { + case x: Byte => x.toLong + case x: Short => x.toLong + case x: Int => x.toLong + case x: Long => x + case _ => sys.error(s"Cannot upcast value $v to the type $this") + } + override def downcast(v: AnyVal): Long = v match { + case b: Byte => b.toLong + case s: Short => s.toLong + case i: Int => i.toLong + case l: Long => l + case _ => sys.error(s"Cannot downcast value $v to the type $this") + } +} + +/** Type of 256 bit integet values. Implemented using [[java.math.BigInteger]]. */ +case object SBigInt extends SPrimType with SEmbeddable with SNumericType with SMonoType { + override type WrappedType = BigInt + override val typeCode: TypeCode = 6: Byte + override val reprClass: RClass[_] = RClass(classOf[BigInt]) + override def typeId = typeCode + implicit def typeBigInt: SBigInt.type = this + + /** Type of Relation binary op like GE, LE, etc. */ + val RelationOpType = SFunc(Array(SBigInt, SBigInt), SBoolean) + + /** The maximum size of BigInteger value in byte array representation. */ + val MaxSizeInBytes: Long = SigmaConstants.MaxBigIntSizeInBytes.value + + override def numericTypeIndex: Int = 4 + + override def upcast(v: AnyVal): BigInt = { + val bi = v match { + case x: Byte => BigInteger.valueOf(x.toLong) + case x: Short => BigInteger.valueOf(x.toLong) + case x: Int => BigInteger.valueOf(x.toLong) + case x: Long => BigInteger.valueOf(x) + case _ => sys.error(s"Cannot upcast value $v to the type $this") + } + CBigInt(bi) + } + override def downcast(v: AnyVal): BigInt = { + val bi = v match { + case x: Byte => BigInteger.valueOf(x.toLong) + case x: Short => BigInteger.valueOf(x.toLong) + case x: Int => BigInteger.valueOf(x.toLong) + case x: Long => BigInteger.valueOf(x) + case _ => sys.error(s"Cannot downcast value $v to the type $this") + } + CBigInt(bi) + } +} + +/** Descriptor of type `String` which is not used in ErgoTree, but used in ErgoScript. + * NOTE: this descriptor both type and type companion */ +case object SString extends SProduct with SMonoType { + override type WrappedType = String + override val typeCode: TypeCode = 102: Byte + override def typeId = typeCode + override def reprClass: RClass[_] = RClass(classOf[String]) +} + +/** Descriptor of ErgoTree type `GroupElement`. + * NOTE: this descriptor both type and type companion */ +case object SGroupElement extends SProduct with SPrimType with SEmbeddable with SMonoType { + override type WrappedType = GroupElement + override val typeCode: TypeCode = 7: Byte + override val reprClass: RClass[_] = RClass(classOf[GroupElement]) + override def typeId = typeCode + implicit def typeGroupElement: SGroupElement.type = this +} + +/** Descriptor of ErgoTree type `SigmaProp` which represent sigma-protocol propositions. */ +case object SSigmaProp extends SProduct with SPrimType with SEmbeddable with SLogical with SMonoType { + import SType._ + override type WrappedType = SigmaProp + override val typeCode: TypeCode = 8: Byte + override val reprClass: RClass[_] = RClass(classOf[SigmaProp]) + override def typeId = typeCode + implicit def typeSigmaProp: SSigmaProp.type = this + + /** The maximum size of SigmaProp value in serialized byte array representation. */ + val MaxSizeInBytes: Long = SigmaConstants.MaxSigmaPropSizeInBytes.value +} + +/** Any other type is implicitly subtype of this type. */ +case object SAny extends SPrimType with SMonoType { + override type WrappedType = Any + override val typeCode: TypeCode = 97: Byte + + /** Type identifier to use in method serialization */ + override def typeId: TypeCode = typeCode + + /** Class which represents values of this type. When method call is executed, the corresponding method + * of this class is invoked via [[RMethod]].invoke(). */ + override def reprClass: RClass[_] = RClass(classOf[Any]) +} + +/** The type with single inhabitant value `()` */ +case object SUnit extends SPrimType with SMonoType { + override type WrappedType = Unit + override val typeCode: TypeCode = 98: Byte + /** Type identifier to use in method serialization */ + override def typeId: TypeCode = typeCode + + /** Class which represents values of this type. When method call is executed, the corresponding method + * of this class is invoked via [[RMethod]].invoke(). */ + override def reprClass: RClass[_] = RClass(classOf[Unit]) +} + +/** Helper constuctor/extractor for tuples of two types. */ +object SPair { + def apply(l: SType, r: SType) = STuple(Array(l, r)) + def unapply(t: STuple): Nullable[(SType, SType)] = t match { + case STuple(IndexedSeq(l, r)) => Nullable((l, r)) + case _ => Nullable.None + } +} + +/** Type descriptor of lambda types. */ +case class SFunc(tDom: IndexedSeq[SType], tRange: SType, tpeParams: Seq[STypeParam] = Nil) + extends SType with SGenericType +{ + override type WrappedType = Any => tRange.WrappedType + override val typeCode = SFunc.FuncTypeCode + override def toString = { + val args = if (tpeParams.isEmpty) "" else tpeParams.mkString("[", ",", "]") + s"$args(${tDom.mkString(",")}) => $tRange" + } + override def toTermString = { + val args = if (tpeParams.isEmpty) "" else tpeParams.mkString("[", ",", "]") + s"$args(${tDom.map(_.toTermString).mkString(",")}) => ${tRange.toTermString}" + } + override val typeParams: Seq[STypeParam] = tpeParams + + /** Generalize this type and return a new descriptor. */ + def getGenericType: SFunc = { + val typeParams: Seq[STypeParam] = tDom.zipWithIndex + .map { case (_, i) => STypeParam(SType.tD.name + (i + 1)) } :+ STypeParam(SType.tR.name) + val ts = typeParams.map(_.ident) + SFunc(ts.init.toIndexedSeq, ts.last, Nil) + } + + /** Transform function into method type by adding the given `objType` as the first + * argument type (aka method receiver type). + */ + def withReceiverType(objType: SType) = this.copy(tDom = objType +: tDom) +} + +object SFunc { + final val FuncTypeCode: TypeCode = TypeCodes.FirstFuncType + def apply(tDom: SType, tRange: SType): SFunc = SFunc(Array(tDom), tRange) // HOTSPOT: + val identity = { x: Any => x } +} + +/** Used by ErgoScript compiler IR and eliminated during compilation. + * It is not used in ErgoTree. + */ +case class STypeApply(name: String, args: IndexedSeq[SType] = IndexedSeq()) extends SType { + override type WrappedType = Any + override val typeCode = STypeApply.TypeCode +} +object STypeApply { + val TypeCode = 94: Byte +} + +/** Type description of optional values. Instances of `Option` + * are either constructed by `Some` or by `None` constructors. */ +case class SOption[ElemType <: SType](elemType: ElemType) extends SProduct with SGenericType { + override type WrappedType = Option[ElemType#WrappedType] + override val typeCode: TypeCode = SOption.OptionTypeCode + override def toString = s"Option[$elemType]" + override def toTermString: String = s"Option[${elemType.toTermString}]" + override lazy val typeParams: Seq[STypeParam] = Array(SType.paramT) +} + +object SOption extends STypeCompanion { + /** 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 + + override def typeId = OptionTypeCode + + override val reprClass: RClass[_] = RClass(classOf[Option[_]]) + + type SBooleanOption = SOption[SBoolean.type] + type SByteOption = SOption[SByte.type] + type SShortOption = SOption[SShort.type] + type SIntOption = SOption[SInt.type] + type SLongOption = SOption[SLong.type] + type SBigIntOption = SOption[SBigInt.type] + type SGroupElementOption = SOption[SGroupElement.type] + type SBoxOption = SOption[SBox.type] + type SAvlTreeOption = SOption[SAvlTree.type] + + /** This descriptors are instantiated once here and then reused. */ + implicit val SByteOption = SOption(SByte) + implicit val SByteArrayOption = SOption(SByteArray) + implicit val SShortOption = SOption(SShort) + implicit val SIntOption = SOption(SInt) + implicit val SLongOption = SOption(SLong) + implicit val SBigIntOption = SOption(SBigInt) + implicit val SBooleanOption = SOption(SBoolean) + implicit val SAvlTreeOption = SOption(SAvlTree) + implicit val SGroupElementOption = SOption(SGroupElement) + implicit val SSigmaPropOption = SOption(SSigmaProp) + implicit val SBoxOption = SOption(SBox) + + def apply[T <: SType](implicit elemType: T, ov: Overloaded1): SOption[T] = SOption(elemType) +} + + +/** Base class for descriptors of `Coll[T]` ErgoTree type for some elemType T. */ +trait SCollection[T <: SType] extends SProduct with SGenericType { + def elemType: T + override type WrappedType = Coll[T#WrappedType] +} + +/** Descriptor of `Coll[T]` ErgoTree type for some elemType T. */ +case class SCollectionType[T <: SType](elemType: T) extends SCollection[T] { + override val typeCode: TypeCode = SCollectionType.CollectionTypeCode + override def typeParams: Seq[STypeParam] = SCollectionType.typeParams + override def toString = s"Coll[$elemType]" + override def toTermString = s"Coll[${elemType.toTermString}]" +} + +object SCollectionType { + /** Code of `Coll[_]` type constructor. */ + val CollectionTypeConstrId = 1 + + /** Type code for `Coll[T] for some T` type used in TypeSerializer. */ + val CollectionTypeCode: TypeCode = ((SPrimType.MaxPrimTypeCode + 1) * CollectionTypeConstrId).toByte + + /** Code of `Coll[Coll[_]]` type constructor. */ + val NestedCollectionTypeConstrId = 2 + + /** Type code for `Coll[Coll[T]] for some T` type used in TypeSerializer. */ + val NestedCollectionTypeCode: TypeCode = ((SPrimType.MaxPrimTypeCode + 1) * NestedCollectionTypeConstrId).toByte + + /** Array of generic type parameters reused in all SCollectionType instances. */ + val typeParams: Seq[STypeParam] = Array(SType.paramIV) +} + +object SCollection extends STypeCompanion { + override val reprClass: RClass[_] = RClass(classOf[Coll[_]]) + override def typeId = SCollectionType.CollectionTypeCode + + /** Costructs a collection type with the given type of elements. */ + implicit def typeCollection[V <: SType](implicit tV: V): SCollection[V] = SCollection[V](tV) + + /** 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) + + /** Helper constructors. */ + def apply[T <: SType](elemType: T): SCollection[T] = SCollectionType(elemType) + def apply[T <: SType](implicit elemType: T, ov: Overloaded1): SCollection[T] = SCollectionType(elemType) + + type SBooleanArray = SCollection[SBoolean.type] + type SByteArray = SCollection[SByte.type] + type SShortArray = SCollection[SShort.type] + type SIntArray = SCollection[SInt.type] + type SLongArray = SCollection[SLong.type] + type SBigIntArray = SCollection[SBigInt.type] + type SGroupElementArray = SCollection[SGroupElement.type] + type SBoxArray = SCollection[SBox.type] + type SAvlTreeArray = SCollection[SAvlTree.type] + + /** This descriptors are instantiated once here and then reused. */ + val SBooleanArray = SCollection(SBoolean) + val SByteArray = SCollection(SByte) + val SByteArray2 = SCollection(SCollection(SByte)) + val SShortArray = SCollection(SShort) + val SIntArray = SCollection(SInt) + val SLongArray = SCollection(SLong) + val SBigIntArray = SCollection(SBigInt) + val SGroupElementArray = SCollection(SGroupElement) + val SSigmaPropArray = SCollection(SSigmaProp) + val SBoxArray = SCollection(SBox) + val SAvlTreeArray = SCollection(SAvlTree) + val SHeaderArray = SCollection(SHeader) +} + +/** Type descriptor of tuple type. */ +case class STuple(items: IndexedSeq[SType]) extends SCollection[SAny.type] { + override val typeCode = STuple.TupleTypeCode + + /** Lazily computed value representing true | false | none. + * 0 - none, 1 - false, 2 - true + */ + @volatile + private var _isConstantSizeCode: Byte = 0.toByte + + override def elemType: SAny.type = SAny + + override val typeParams = Nil + + override def toTermString = s"(${items.map(_.toTermString).mkString(",")})" + override def toString = s"(${items.mkString(",")})" +} + +object STuple extends STypeCompanion { + /** Code of `(_, T) for some embeddable T` type constructor. */ + val Pair1TypeConstrId = 5 + /** Type code for `(E, T) for some embeddable T` type used in TypeSerializer. */ + val Pair1TypeCode: TypeCode = ((SPrimType.MaxPrimTypeCode + 1) * Pair1TypeConstrId).toByte + + /** Code of `(T, _) for some embeddable T` type constructor. */ + val Pair2TypeConstrId = 6 + /** Type code for `(T, E) for some embeddable T` type used in TypeSerializer. */ + val Pair2TypeCode: TypeCode = ((SPrimType.MaxPrimTypeCode + 1) * Pair2TypeConstrId).toByte + val TripleTypeCode: TypeCode = Pair2TypeCode + + /** Type constructor code of symmetric pair `(T, T)` for some embeddable T. */ + val PairSymmetricTypeConstrId = 7 + /** Type code of symmetric pair `(T, T)` for some embeddable T. */ + val PairSymmetricTypeCode: TypeCode = ((SPrimType.MaxPrimTypeCode + 1) * PairSymmetricTypeConstrId).toByte + val QuadrupleTypeCode: TypeCode = PairSymmetricTypeCode + + /** Type code of generic tuple type. */ + val TupleTypeCode = ((SPrimType.MaxPrimTypeCode + 1) * 8).toByte + + override def typeId = TupleTypeCode + + override val reprClass: RClass[_] = RClass(classOf[Product2[_,_]]) + + /** Helper factory method. */ + def apply(items: SType*): STuple = STuple(items.toArray) + +} + +/** Type descriptor of `Box` type of ErgoTree. */ +case object SBox extends SProduct with SPredefType with SMonoType { + override type WrappedType = Box + override val typeCode: TypeCode = 99: Byte + override val reprClass: RClass[_] = RClass(classOf[Box]) + override def typeId = typeCode + implicit def typeBox: SBox.type = this +} + +/** Type descriptor of `AvlTree` type of ErgoTree. */ +case object SAvlTree extends SProduct with SPredefType with SMonoType { + override type WrappedType = AvlTree + override val typeCode: TypeCode = 100: Byte + override val reprClass: RClass[_] = RClass(classOf[AvlTree]) + override def typeId = typeCode + implicit def typeAvlTree: SAvlTree.type = this + + import SOption._ + lazy val TCollOptionCollByte = SCollection(SByteArrayOption) + lazy val CollKeyValue = SCollection(STuple(SByteArray, SByteArray)) +} + +/** Type descriptor of `Context` type of ErgoTree. */ +case object SContext extends SProduct with SPredefType with SMonoType { + override type WrappedType = Context + override val typeCode: TypeCode = 101: Byte + override def reprClass: RClass[_] = RClass(classOf[Context]) + override def typeId = typeCode +} + +/** Type descriptor of `Header` type of ErgoTree. */ +case object SHeader extends SProduct with SPredefType with SMonoType { + override type WrappedType = Header + override val typeCode: TypeCode = 104: Byte + override val reprClass: RClass[_] = RClass(classOf[Header]) + override def typeId = typeCode +} + +/** Type descriptor of `PreHeader` type of ErgoTree. */ +case object SPreHeader extends SProduct with SPredefType with SMonoType { + override type WrappedType = PreHeader + override val typeCode: TypeCode = 105: Byte + override val reprClass: RClass[_] = RClass(classOf[PreHeader]) + override def typeId = typeCode +} + +/** This type is introduced to unify handling of global and non-global (i.e. methods) operations. + * It unifies implementation of global operation with implementation of methods and avoids code + * duplication (following DRY principle https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). + * The WrappedType is `sigma.SigmaDslBuilder`, which is an interface implemented by + * the singleton sigmastate.eval.CostingSigmaDslBuilder + * + * The Constant(...) tree node of this type are not allowed, as well as using it in register and + * context variables (aka ContextExtension) + * + * When new methods are added to this type via a soft-fork, they will be serialized as part + * of ErgoTree using MethodCallSerializer, where SGlobal.typeCode will be used. + * + * @see sigmastate.lang.SigmaPredef + * */ +case object SGlobal extends SProduct with SPredefType with SMonoType { + override type WrappedType = SigmaDslBuilder + override val typeCode: TypeCode = 106: Byte + override val reprClass: RClass[_] = RClass(classOf[SigmaDslBuilder]) + override def typeId = typeCode +} + diff --git a/core/shared/src/main/scala/sigma/ast/STypeParam.scala b/core/shared/src/main/scala/sigma/ast/STypeParam.scala new file mode 100644 index 0000000000..56d89d01f8 --- /dev/null +++ b/core/shared/src/main/scala/sigma/ast/STypeParam.scala @@ -0,0 +1,26 @@ +package sigma.ast + +/** Represents a type parameter in a type system. + * + * @param ident The identifier for this type parameter. + * @param upperBound The upper bound of this type parameter, if exists. + * @param lowerBound The lower bound of this type parameter, if exists. + * @note Type parameters with bounds are currently not supported. + */ +case class STypeParam( + ident: STypeVar, + upperBound: Option[SType] = None, + lowerBound: Option[SType] = None) { + assert(upperBound.isEmpty && lowerBound.isEmpty, s"Type parameters with bounds are not supported, but found $this") + + override def toString = ident.toString + upperBound.fold("")(u => s" <: $u") + lowerBound.fold("")(l => s" >: $l") +} + +object STypeParam { + /** Enables implicit conversion from [[STypeVar]] to [[STypeParam]]. + * + * @param id The type variable to convert. + * @return A type parameter constructed from the provided type variable. + */ + implicit def typeIdentToTypeParam(id: STypeVar): STypeParam = STypeParam(id) +} \ No newline at end of file diff --git a/core/shared/src/main/scala/sigma/ast/TypeCodes.scala b/core/shared/src/main/scala/sigma/ast/TypeCodes.scala new file mode 100644 index 0000000000..605378f5f5 --- /dev/null +++ b/core/shared/src/main/scala/sigma/ast/TypeCodes.scala @@ -0,0 +1,21 @@ +package sigma.ast + +import supertagged.TaggedType + +/** Encoding of types for serialization. */ +object TypeCodes { + object TypeCode extends TaggedType[Byte] + type TypeCode = TypeCode.Type + + /** Decoding of types depends on the first byte and in general is a recursive procedure + * consuming some number of bytes from Reader. + * All data types are recognized by the first byte falling in the region [FirstDataType .. LastDataType] */ + val FirstDataType: TypeCode = TypeCode @@ 1.toByte + + val LastDataType : TypeCode = TypeCode @@ 111.toByte + + /** SFunc types occupy remaining space of byte values [FirstFuncType .. 255] */ + val FirstFuncType: TypeCode = TypeCode @@ (LastDataType + 1).toByte + + val LastFuncType : TypeCode = TypeCode @@ 255.toByte +} diff --git a/core/shared/src/main/scala/sigma/data/CBigInt.scala b/core/shared/src/main/scala/sigma/data/CBigInt.scala new file mode 100644 index 0000000000..bcc9e8c09e --- /dev/null +++ b/core/shared/src/main/scala/sigma/data/CBigInt.scala @@ -0,0 +1,64 @@ +package sigma.data + +import sigma.util.Extensions.BigIntegerOps +import sigma.{BigInt, Coll, Colls} + +import java.math.BigInteger + +/** A default implementation of [[BigInt]] interface. + * + * @see [[BigInt]] for detailed descriptions + */ +case class CBigInt(override val wrappedValue: BigInteger) extends BigInt with WrapperOf[BigInteger] { + + override def toByte: Byte = wrappedValue.toByteExact + + override def toShort: Short = wrappedValue.toShortExact + + override def toInt: Int = wrappedValue.toIntExact + + override def toLong: Long = wrappedValue.toLongExact + + override def toBytes: Coll[Byte] = Colls.fromArray(wrappedValue.toByteArray) + + override def toAbs: BigInt = CBigInt(wrappedValue.abs()) + + override def compareTo(that: BigInt): Int = + wrappedValue.compareTo(that.asInstanceOf[CBigInt].wrappedValue) + + override def toBits: Coll[Boolean] = ??? + + override def modQ: BigInt = ??? + + override def plusModQ(other: BigInt): BigInt = ??? + + override def minusModQ(other: BigInt): BigInt = ??? + + override def multModQ(other: BigInt): BigInt = ??? + + override def inverseModQ: BigInt = ??? + + override def signum: Int = wrappedValue.signum() + + override def add(that: BigInt): BigInt = CBigInt(wrappedValue.add(that.asInstanceOf[CBigInt].wrappedValue).to256BitValueExact) + + override def subtract(that: BigInt): BigInt = CBigInt(wrappedValue.subtract(that.asInstanceOf[CBigInt].wrappedValue).to256BitValueExact) + + override def multiply(that: BigInt): BigInt = CBigInt(wrappedValue.multiply(that.asInstanceOf[CBigInt].wrappedValue).to256BitValueExact) + + override def divide(that: BigInt): BigInt = CBigInt(wrappedValue.divide(that.asInstanceOf[CBigInt].wrappedValue)) + + override def mod(m: BigInt): BigInt = CBigInt(wrappedValue.mod(m.asInstanceOf[CBigInt].wrappedValue)) + + override def remainder(that: BigInt): BigInt = CBigInt(wrappedValue.remainder(that.asInstanceOf[CBigInt].wrappedValue)) + + override def min(that: BigInt): BigInt = CBigInt(wrappedValue.min(that.asInstanceOf[CBigInt].wrappedValue)) + + override def max(that: BigInt): BigInt = CBigInt(wrappedValue.max(that.asInstanceOf[CBigInt].wrappedValue)) + + override def negate(): BigInt = CBigInt(wrappedValue.negate().to256BitValueExact) + + override def and(that: BigInt): BigInt = CBigInt(wrappedValue.and(that.asInstanceOf[CBigInt].wrappedValue)) + + override def or(that: BigInt): BigInt = CBigInt(wrappedValue.or(that.asInstanceOf[CBigInt].wrappedValue)) +} diff --git a/core/shared/src/main/scala/sigma/data/Iso.scala b/core/shared/src/main/scala/sigma/data/Iso.scala new file mode 100644 index 0000000000..224b784772 --- /dev/null +++ b/core/shared/src/main/scala/sigma/data/Iso.scala @@ -0,0 +1,29 @@ +package sigma.data + +/** Type-class of isomorphisms between types. + * Isomorphism between two types `A` and `B` essentially say that both types + * represents the same information (entity) but in a different way. + *

+ * The information is not lost so that both are true: + * 1) a == from(to(a)) + * 2) b == to(from(b)) + *

+ * It is used to define type-full conversions: + * - different conversions between Java and Scala data types. + * - conversion between Ergo representations and generated API representations + */ +abstract class Iso[A, B] { + def to(a: A): B + def from(b: B): A + def andThen[C](iso: Iso[B,C]): Iso[A,C] = ComposeIso(iso, this) + def inverse: Iso[B, A] = InverseIso(this) +} +final case class InverseIso[A,B](iso: Iso[A,B]) extends Iso[B,A] { + override def to(a: B): A = iso.from(a) + override def from(b: A): B = iso.to(b) +} +final case class ComposeIso[A, B, C](iso2: Iso[B, C], iso1: Iso[A, B]) extends Iso[A, C] { + def from(c: C): A = iso1.from(iso2.from(c)) + def to(a: A): C = iso2.to(iso1.to(a)) +} + diff --git a/core/shared/src/main/scala/sigma/data/RType.scala b/core/shared/src/main/scala/sigma/data/RType.scala index 281e032aa4..54402f1254 100644 --- a/core/shared/src/main/scala/sigma/data/RType.scala +++ b/core/shared/src/main/scala/sigma/data/RType.scala @@ -48,12 +48,6 @@ case class PrimitiveType[A]( override def name: String = classTag.toString() } -case class StringType() extends RType[String] { - override def classTag: ClassTag[String] = ClassTag[String](classOf[String]) - - override def name: String = "String" -} - /** Descriptor of descriptor to represent type of RType[_] instances. * This describes any possible descriptor, disregarding its underlying type. * Thus the underlying type is assumed to be Any. */ diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/SigmaConstants.scala b/core/shared/src/main/scala/sigma/data/SigmaConstants.scala similarity index 94% rename from interpreter/shared/src/main/scala/org/ergoplatform/SigmaConstants.scala rename to core/shared/src/main/scala/sigma/data/SigmaConstants.scala index 74dc98ade9..7198d5dc09 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/SigmaConstants.scala +++ b/core/shared/src/main/scala/sigma/data/SigmaConstants.scala @@ -1,7 +1,6 @@ -package org.ergoplatform +package sigma.data import sigma.util.CollectionUtil.TraversableOps // used in Scala 2.11 -import sigmastate.crypto.CryptoConstants /** Descriptor of a constant which represents some size value. * @tparam T type of the constant value @@ -42,7 +41,8 @@ object SigmaConstants { "Max length of Box.propositionBytes collection") { } - object MaxBoxSizeWithoutRefs extends SizeConstant[Int](MaxBoxSize.value - (CryptoConstants.hashLength + 2/*size of Short*/), 6, + object MaxBoxSizeWithoutRefs extends SizeConstant[Int]( + MaxBoxSize.value - (32/*CryptoConstants.hashLength*/ + 2/*size of Short*/), 6, "Box size should not be greater than provided value") { } diff --git a/core/shared/src/main/scala/sigma/data/WrapperOf.scala b/core/shared/src/main/scala/sigma/data/WrapperOf.scala new file mode 100644 index 0000000000..7a6a98c217 --- /dev/null +++ b/core/shared/src/main/scala/sigma/data/WrapperOf.scala @@ -0,0 +1,7 @@ +package sigma.data + +/** Interface implmented by wrappers to provide access to the underlying wrapped value. */ +trait WrapperOf[T] { + /** The data value wrapped by this wrapper. */ + def wrappedValue: T +} diff --git a/core/shared/src/main/scala/sigma/data/package.scala b/core/shared/src/main/scala/sigma/data/package.scala index 8c34f7e9b9..b6088de1ad 100644 --- a/core/shared/src/main/scala/sigma/data/package.scala +++ b/core/shared/src/main/scala/sigma/data/package.scala @@ -10,6 +10,7 @@ package object data { */ @nowarn private def rtypeToClassTag = ??? + val StringClassTag = classTag[String] val BigIntClassTag = classTag[BigInt] val GroupElementClassTag = classTag[GroupElement] val SigmaPropClassTag = classTag[SigmaProp] @@ -38,4 +39,12 @@ package object data { */ def emptyDBufferOfInt: debox.Buffer[Int] = debox.Buffer.unsafe(EmptyArrayOfInt) + /** Constructor of tuple value with more than 2 items. + * Such long tuples are represented as Coll[Any]. + * This representaion of tuples is different from representation of pairs (x, y), + * where Tuple2 type is used instead of Coll. */ + def TupleColl(items: Any*): Coll[Any] = Colls.fromItems(items: _*)(sigma.AnyType) + + type KeyValueColl = Coll[(Coll[Byte], Coll[Byte])] + } diff --git a/core/shared/src/main/scala/sigma/package.scala b/core/shared/src/main/scala/sigma/package.scala index f7f2321096..67560b462c 100644 --- a/core/shared/src/main/scala/sigma/package.scala +++ b/core/shared/src/main/scala/sigma/package.scala @@ -23,7 +23,7 @@ package object sigma { implicit val UnitType : RType[Unit] = PrimitiveType[Unit](ClassTag.Unit, Array[Unit]()(ClassTag.Unit)) - implicit val StringType : RType[String] = sigma.data.StringType() + implicit val StringType : RType[String] = GeneralType(StringClassTag) implicit val BigIntRType: RType[BigInt] = GeneralType(BigIntClassTag) implicit val GroupElementRType: RType[GroupElement] = GeneralType(GroupElementClassTag) diff --git a/core/shared/src/main/scala/sigma/reflection/ReflectionData.scala b/core/shared/src/main/scala/sigma/reflection/ReflectionData.scala index cdab5d5be7..01949b89ff 100644 --- a/core/shared/src/main/scala/sigma/reflection/ReflectionData.scala +++ b/core/shared/src/main/scala/sigma/reflection/ReflectionData.scala @@ -1,6 +1,7 @@ package sigma.reflection import sigma._ +import sigma.ast.{SCollectionType, SOption, STuple, SType} import sigma.data.RType import scala.collection.compat.immutable.ArraySeq @@ -463,4 +464,28 @@ object ReflectionData { ) ) } + + registerClassEntry(classOf[SCollectionType[_]], + constructors = Array( + mkConstructor(Array(classOf[SType])) { args => + new SCollectionType(args(0).asInstanceOf[SType]) + } + ) + ) + + registerClassEntry(classOf[SOption[_]], + constructors = Array( + mkConstructor(Array(classOf[SType])) { args => + new SOption(args(0).asInstanceOf[SType]) + } + ) + ) + + registerClassEntry(classOf[STuple], + constructors = Array( + mkConstructor(Array(classOf[IndexedSeq[_]])) { args => + new STuple(args(0).asInstanceOf[IndexedSeq[SType]]) + } + ) + ) } diff --git a/interpreter/js/src/main/scala/sigmastate/Platform.scala b/interpreter/js/src/main/scala/sigmastate/Platform.scala index bff11b53a8..07d11d81c0 100644 --- a/interpreter/js/src/main/scala/sigmastate/Platform.scala +++ b/interpreter/js/src/main/scala/sigmastate/Platform.scala @@ -2,11 +2,12 @@ package sigmastate import org.ergoplatform.ErgoBox import sigma.data.Nullable -import sigma.VersionContext +import sigma.{Evaluation, VersionContext} import sigmastate.Values.{Constant, FalseLeaf, SigmaBoolean, TrueLeaf} -import sigmastate.eval.{Evaluation, SigmaDsl} +import sigmastate.eval.SigmaDsl import sigmastate.lang.SigmaBuilder import sigma.Coll +import sigma.ast._ import sigma.{AnyValue, AvlTree, GroupElement, SigmaProp} import java.math.BigInteger diff --git a/interpreter/js/src/main/scala/sigmastate/crypto/Platform.scala b/interpreter/js/src/main/scala/sigmastate/crypto/Platform.scala index fdb3b128fd..5116af38a9 100644 --- a/interpreter/js/src/main/scala/sigmastate/crypto/Platform.scala +++ b/interpreter/js/src/main/scala/sigmastate/crypto/Platform.scala @@ -5,6 +5,7 @@ import scorex.util.encode.Base16 import sigmastate._ import sigma.Coll import sigma._ +import sigma.ast._ import java.math.BigInteger import scala.scalajs.js diff --git a/interpreter/jvm/src/main/scala/sigmastate/Platform.scala b/interpreter/jvm/src/main/scala/sigmastate/Platform.scala index fa44f9a16f..a6e9f6a580 100644 --- a/interpreter/jvm/src/main/scala/sigmastate/Platform.scala +++ b/interpreter/jvm/src/main/scala/sigmastate/Platform.scala @@ -2,11 +2,12 @@ package sigmastate import org.ergoplatform.ErgoBox import sigma.data.Nullable -import sigma.VersionContext +import sigma.{Evaluation, VersionContext} import sigmastate.Values.{Constant, FalseLeaf, SigmaBoolean, TrueLeaf} -import sigmastate.eval.{Evaluation, SigmaDsl} +import sigmastate.eval.SigmaDsl import sigmastate.lang.SigmaBuilder import sigma.Coll +import sigma.ast._ import sigma.{AvlTree, GroupElement, SigmaProp} import java.math.BigInteger diff --git a/interpreter/jvm/src/main/scala/sigmastate/crypto/Platform.scala b/interpreter/jvm/src/main/scala/sigmastate/crypto/Platform.scala index 1c5c63b197..c213d7a718 100644 --- a/interpreter/jvm/src/main/scala/sigmastate/crypto/Platform.scala +++ b/interpreter/jvm/src/main/scala/sigmastate/crypto/Platform.scala @@ -10,6 +10,7 @@ import java.math.BigInteger import sigmastate._ import sigma.Coll import sigma._ +import sigma.ast._ import java.text.Normalizer.Form.NFKD import java.text.Normalizer diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoAddress.scala b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoAddress.scala index 5813ff99e7..100fc383a6 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoAddress.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoAddress.scala @@ -11,6 +11,7 @@ import sigmastate.exceptions.SigmaException import sigmastate.serialization._ import sigmastate.utxo.{DeserializeContext, Slice} import sigma.Coll +import sigma.ast.{SInt, SSigmaProp} import scala.util.Try diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoBox.scala b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoBox.scala index 670d51d123..e4ee583ffa 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoBox.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoBox.scala @@ -6,8 +6,10 @@ import scorex.crypto.authds.ADKey import scorex.crypto.hash.Blake2b256 import scorex.util._ import scorex.utils.{Ints, Shorts} -import sigmastate.SCollection.SByteArray -import sigmastate.SType.AnyOps +import sigma.ast.SCollection.SByteArray +import sigma.ast.{SCollection, SLong, STuple, SType} +import sigma.ast.SType.AnyOps +import sigma.data.SigmaConstants import sigmastate.Values._ import sigmastate._ import sigmastate.eval.Extensions._ diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala index a167b95143..c174e04d00 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala @@ -5,9 +5,10 @@ import org.ergoplatform.ErgoBox._ import org.ergoplatform.settings.ErgoAlgos import scorex.util.{ModifierId, bytesToId} import sigma.Extensions.CollOps +import sigma.ast.SType +import sigma.ast.SType.AnyOps import sigma.util.safeNewArray import sigma.{Coll, Colls} -import sigmastate.SType.AnyOps import sigmastate.Values._ import sigmastate._ import sigmastate.eval.Extensions._ diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeContext.scala b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeContext.scala index 05b5bde4e2..137c91fded 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeContext.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeContext.scala @@ -1,7 +1,6 @@ package org.ergoplatform import org.ergoplatform.validation.SigmaValidationSettings -import sigmastate.SType._ import sigmastate.Values._ import sigmastate._ import sigmastate.eval.Extensions._ @@ -10,10 +9,13 @@ import sigmastate.interpreter.ErgoTreeEvaluator.DataEnv import sigmastate.interpreter.{ContextExtension, ErgoTreeEvaluator, Interpreter, InterpreterContext} import sigmastate.exceptions.InterpreterException import sigmastate.serialization.OpCodes -import sigmastate.serialization.OpCodes.OpCode import sigma.Coll import sigma.{AnyValue, Header, PreHeader} import debox.cfor +import sigma.ast.{SBox, SCollection, SContext, SFunc, SGlobal, SInt, SType, SUnit} +import sigma.ast.SType.{TypeCode, AnyOps} +import sigma.data.SigmaConstants +import sigmastate.serialization.ValueCodes.OpCode /** Represents a script evaluation context to be passed to a prover and a verifier to execute and * validate guarding proposition of input boxes of a transaction. @@ -137,7 +139,7 @@ class ErgoLikeContext(val lastBlockUtxoRoot: AvlTreeData, ErgoLikeContext.copy(this)(spendingTransaction = newSpendingTransaction) override def toSigmaContext(extensions: Map[Byte, AnyValue] = Map()): sigma.Context = { - import Evaluation._ + import sigma.Evaluation._ def contextVars(m: Map[Byte, AnyValue]): Coll[AnyValue] = { val maxKey = if (m.keys.isEmpty) 0 else m.keys.max // TODO optimize: max takes 90% of this method diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala index 1730bed277..2a5898d888 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala @@ -1,6 +1,6 @@ package org.ergoplatform -import sigmastate.SCollection.SByteArray +import sigma.ast.SCollection.SByteArray import sigmastate.Values._ import sigmastate.interpreter.Interpreter import sigmastate.utxo._ diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoTreePredef.scala b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoTreePredef.scala index 8f01a46864..fb4dd6b5d1 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoTreePredef.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoTreePredef.scala @@ -1,11 +1,12 @@ package org.ergoplatform import org.ergoplatform.settings.MonetarySettings +import sigma.ast.SCollection.SByteArray +import sigma.ast.{SBox, SInt, SLong, SSigmaProp} import sigmastate.crypto.DLogProtocol.ProveDlog import sigmastate.crypto.CryptoConstants import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.SCollection.SByteArray -import sigmastate.Values.{LongConstant, SigmaPropConstant, IntArrayConstant, TrueSigmaProp, Value, FalseSigmaProp, SigmaPropValue, IntConstant, ErgoTree} +import sigmastate.Values.{ErgoTree, FalseSigmaProp, IntArrayConstant, IntConstant, LongConstant, SigmaPropConstant, SigmaPropValue, TrueSigmaProp, Value} import sigmastate.utxo._ import sigmastate._ import sigmastate.lang.Terms.ValueOps diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/validation/ValidationRules.scala b/interpreter/shared/src/main/scala/org/ergoplatform/validation/ValidationRules.scala index 442faed890..4191421b10 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/validation/ValidationRules.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/validation/ValidationRules.scala @@ -1,12 +1,13 @@ package org.ergoplatform.validation +import sigma.ast.{SGlobal, SOption, TypeCodes} import sigma.util.Extensions.toUByte import sigmastate.Values.{ErgoTree, SValue} import sigmastate._ -import sigmastate.exceptions.{InterpreterException, InvalidOpCode, ReaderPositionLimitExceeded, SerializerException, SigmaException} -import sigmastate.serialization.OpCodes.OpCode +import sigmastate.exceptions._ import sigmastate.serialization.TypeSerializer.embeddableIdToType -import sigmastate.serialization.{OpCodes, ValueSerializer} +import sigmastate.serialization.ValueCodes.OpCode +import sigmastate.serialization.{OpCodes, ValueCodes, ValueSerializer} import sigmastate.utxo.DeserializeContext /** Base class for different validation rules registered in ValidationRules.currentSettings. @@ -110,7 +111,7 @@ object ValidationRules { checkRule() if (ser == null || ser.opCode != opCode) { throwValidationException( - new InvalidOpCode(s"Cannot find serializer for Value with opCode = LastConstantCode + ${toUByte(opCode) - OpCodes.LastConstantCode}"), + new InvalidOpCode(s"Cannot find serializer for Value with opCode = LastConstantCode + ${toUByte(opCode) - ValueCodes.LastConstantCode}"), Array(opCode)) } } @@ -186,7 +187,7 @@ object ValidationRules { final def apply[T](typeCode: Byte): Unit = { checkRule() val ucode = toUByte(typeCode) - if (typeCode == SOption.OptionTypeCode || ucode > toUByte(OpCodes.LastDataType)) { + if (typeCode == SOption.OptionTypeCode || ucode > toUByte(TypeCodes.LastDataType)) { // the `typeCode == SOption.OptionTypeCode` condition is added in v5.0 and we // throw ValidationException for Option type as well in order to be able to // interpret it as soft-fork condition. @@ -216,7 +217,7 @@ object ValidationRules { object CheckAndGetMethod extends ValidationRule(1011, "Check the type has the declared method.") { - final def apply[T](objType: STypeCompanion, methodId: Byte): SMethod = { + final def apply[T](objType: MethodsContainer, methodId: Byte): SMethod = { checkRule() val methodOpt = objType.getMethodById(methodId) if (methodOpt.isDefined) methodOpt.get @@ -231,8 +232,8 @@ object ValidationRules { ruleId: Short, status: RuleStatus, args: Seq[Any]): Boolean = (status, args) match { - case (ChangedRule(newValue), Seq(objType: STypeCompanion, methodId: Byte)) => - val key = Array(objType.typeId, methodId) + case (ChangedRule(newValue), Seq(objType: MethodsContainer, methodId: Byte)) => + val key = Array(objType.ownerType.typeId, methodId) newValue.grouped(2).exists(java.util.Arrays.equals(_, key)) case _ => false } diff --git a/interpreter/shared/src/main/scala/sigmastate/CostKind.scala b/interpreter/shared/src/main/scala/sigmastate/CostKind.scala index 0730bb4ec0..18bb70901c 100644 --- a/interpreter/shared/src/main/scala/sigmastate/CostKind.scala +++ b/interpreter/shared/src/main/scala/sigmastate/CostKind.scala @@ -1,5 +1,7 @@ package sigmastate +import sigma.ast.SType + import scala.runtime.Statics /** Cost descriptor of a single operation, usually associated with diff --git a/interpreter/shared/src/main/scala/sigmastate/InterpreterReflection.scala b/interpreter/shared/src/main/scala/sigmastate/InterpreterReflection.scala index c6cec6c3da..217903a619 100644 --- a/interpreter/shared/src/main/scala/sigmastate/InterpreterReflection.scala +++ b/interpreter/shared/src/main/scala/sigmastate/InterpreterReflection.scala @@ -4,15 +4,16 @@ import org.ergoplatform.ErgoBox.RegisterId import sigma.reflection.ReflectionData.registerClassEntry import sigma.reflection.{ReflectionData, mkConstructor, mkMethod} import sigma.Coll +import sigma.ast.SCollection.{SBooleanArray, SByteArray, SIntArray} +import sigma.ast.{SAny, SAvlTree, SCollectionType, SFunc, SNumericType, SOption, SSigmaProp, STuple, SType, STypeParam, STypeVar} import sigma.{AvlTree, SigmaDslBuilder} -import sigmastate.SAvlTree.KeyValueColl -import sigmastate.SCollection.{SBooleanArray, SByteArray, SIntArray} +import sigmastate.SAvlTreeMethods.KeyValueColl import sigmastate.Values._ import sigmastate.crypto.VerifierMessage.Challenge import sigmastate.crypto.GF2_192_Poly import sigmastate.interpreter.ErgoTreeEvaluator import sigmastate.lang.Terms._ -import sigmastate.serialization.OpCodes.OpCode +import sigmastate.serialization.ValueCodes.OpCode import sigmastate.utxo._ /** Reflection metadata for `interpreter` module. @@ -283,41 +284,41 @@ object InterpreterReflection { ) ) - { val clazz = SAvlTree.getClass + { val clazz = SAvlTreeMethods.getClass registerClassEntry(clazz, methods = Map( mkMethod(clazz, "update_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SAvlTree.type].update_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SAvlTreeMethods.type].update_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[AvlTree], args(2).asInstanceOf[KeyValueColl], args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) }, mkMethod(clazz, "contains_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SAvlTree.type].contains_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SAvlTreeMethods.type].contains_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[AvlTree], args(2).asInstanceOf[Coll[Byte]], args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) }, mkMethod(clazz, "get_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SAvlTree.type].get_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SAvlTreeMethods.type].get_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[AvlTree], args(2).asInstanceOf[Coll[Byte]], args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) }, mkMethod(clazz, "getMany_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SAvlTree.type].getMany_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SAvlTreeMethods.type].getMany_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[AvlTree], args(2).asInstanceOf[Coll[Coll[Byte]]], args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) }, mkMethod(clazz, "remove_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SAvlTree.type].remove_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SAvlTreeMethods.type].remove_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[AvlTree], args(2).asInstanceOf[Coll[Coll[Byte]]], args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) }, mkMethod(clazz, "insert_eval", Array[Class[_]](classOf[MethodCall], classOf[AvlTree], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SAvlTree.type].insert_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SAvlTreeMethods.type].insert_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[AvlTree], args(2).asInstanceOf[KeyValueColl], args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) @@ -326,73 +327,65 @@ object InterpreterReflection { ) } - { val clazz = SCollection.getClass + { val clazz = SCollectionMethods.getClass registerClassEntry(clazz, methods = Map( mkMethod(clazz, "zip_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollection.type].zip_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SCollectionMethods.type].zip_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[Coll[Any]], args(2).asInstanceOf[Coll[Any]])(args(3).asInstanceOf[ErgoTreeEvaluator]) }, mkMethod(clazz, "getOrElse_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Int], classOf[java.lang.Object], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollection.type].getOrElse_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SCollectionMethods.type].getOrElse_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[Coll[Any]], args(2).asInstanceOf[Int], args(3).asInstanceOf[Any])(args(4).asInstanceOf[ErgoTreeEvaluator]) }, mkMethod(clazz, "patch_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Int], classOf[Coll[_]], classOf[Int], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollection.type].patch_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SCollectionMethods.type].patch_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[Coll[Any]], args(2).asInstanceOf[Int], args(3).asInstanceOf[Coll[Any]], args(4).asInstanceOf[Int])(args(5).asInstanceOf[ErgoTreeEvaluator]) }, mkMethod(clazz, "map_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Function1[_,_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollection.type].map_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SCollectionMethods.type].map_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[Coll[Any]], args(2).asInstanceOf[Any => Any])(args(3).asInstanceOf[ErgoTreeEvaluator]) }, mkMethod(clazz, "updated_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Int], classOf[java.lang.Object], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollection.type].updated_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SCollectionMethods.type].updated_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[Coll[Any]], args(2).asInstanceOf[Int], args(3))(args(4).asInstanceOf[ErgoTreeEvaluator]) }, mkMethod(clazz, "indexOf_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[java.lang.Object], classOf[Int], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollection.type].indexOf_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SCollectionMethods.type].indexOf_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[Coll[Any]], args(2), args(3).asInstanceOf[Int])(args(4).asInstanceOf[ErgoTreeEvaluator]) }, mkMethod(clazz, "updateMany_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollection.type].updateMany_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SCollectionMethods.type].updateMany_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[Coll[Any]], args(2).asInstanceOf[Coll[Int]], args(3).asInstanceOf[Coll[Any]])(args(4).asInstanceOf[ErgoTreeEvaluator]) }, mkMethod(clazz, "indices_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollection.type].indices_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SCollectionMethods.type].indices_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[Coll[Any]])(args(2).asInstanceOf[ErgoTreeEvaluator]) }, mkMethod(clazz, "flatMap_eval", Array[Class[_]](classOf[MethodCall], classOf[Coll[_]], classOf[Function1[_,_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SCollection.type].flatMap_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SCollectionMethods.type].flatMap_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[Coll[Any]], args(2).asInstanceOf[Any => Coll[Any]])(args(3).asInstanceOf[ErgoTreeEvaluator]) } ) ) } - registerClassEntry(classOf[SCollectionType[_]], - constructors = Array( - mkConstructor(Array(classOf[SType])) { args => - new SCollectionType(args(0).asInstanceOf[SType]) - } - ) - ) - - { val clazz = SGlobal.getClass + { val clazz = SGlobalMethods.getClass registerClassEntry(clazz, methods = Map( mkMethod(clazz, "xor_eval", Array[Class[_]](classOf[MethodCall], classOf[SigmaDslBuilder], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SGlobal.type].xor_eval(args(0).asInstanceOf[MethodCall], + obj.asInstanceOf[SGlobalMethods.type].xor_eval(args(0).asInstanceOf[MethodCall], args(1).asInstanceOf[SigmaDslBuilder], args(2).asInstanceOf[Coll[Byte]], args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) @@ -401,22 +394,6 @@ object InterpreterReflection { ) } - registerClassEntry(classOf[SOption[_]], - constructors = Array( - mkConstructor(Array(classOf[SType])) { args => - new SOption(args(0).asInstanceOf[SType]) - } - ) - ) - - registerClassEntry(classOf[STuple], - constructors = Array( - mkConstructor(Array(classOf[IndexedSeq[_]])) { args => - new STuple(args(0).asInstanceOf[IndexedSeq[SType]]) - } - ) - ) - registerClassEntry(classOf[SigmaAnd], constructors = Array( mkConstructor(Array(classOf[Seq[_]])) { args => diff --git a/interpreter/shared/src/main/scala/sigmastate/SMethod.scala b/interpreter/shared/src/main/scala/sigmastate/SMethod.scala new file mode 100644 index 0000000000..0ee6df43aa --- /dev/null +++ b/interpreter/shared/src/main/scala/sigmastate/SMethod.scala @@ -0,0 +1,324 @@ +package sigmastate + +import debox.cfor +import org.ergoplatform.validation.ValidationRules +import sigma.{Coll, Evaluation} +import sigma.ast._ +import sigma.data.RType +import sigma.reflection.{RClass, RMethod} +import sigmastate.SMethod.{InvokeDescBuilder, MethodCostFunc} +import sigmastate.Values.{SValue, ValueCompanion} +import sigmastate.interpreter.{CostDetails, ErgoTreeEvaluator, FixedCostItem, GivenCost, MethodDesc, SeqCostItem, TracedCost} +import sigmastate.lang.{SigmaBuilder, Terms} +import sigmastate.lang.Terms.{MethodCall, OperationId, STypeSubst} + +import scala.collection.compat.immutable.ArraySeq +import scala.reflect.ClassTag + +/** 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: MethodsContainer, + 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.ownerType.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: MethodsContainer, 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, MethodsContainer.contains(typeId)) + val container = MethodsContainer(typeId) + val method = container.methodById(methodId) + method + } +} + diff --git a/interpreter/shared/src/main/scala/sigmastate/Values.scala b/interpreter/shared/src/main/scala/sigmastate/Values.scala index df79471ee8..e292eff463 100644 --- a/interpreter/shared/src/main/scala/sigmastate/Values.scala +++ b/interpreter/shared/src/main/scala/sigmastate/Values.scala @@ -7,7 +7,6 @@ import org.ergoplatform.settings.ErgoAlgos import org.ergoplatform.validation.ValidationException import sigma.data.{Nullable, RType} import sigma.util.CollectionUtil._ -import sigmastate.SCollection.{SByteArray, SIntArray} import sigmastate.crypto.CryptoConstants.EcPointType import sigmastate.interpreter.{CompanionDesc, ErgoTreeEvaluator, Interpreter, NamedDesc} import sigmastate.serialization._ @@ -24,10 +23,11 @@ import sigma.util.Extensions.ByteOps import sigmastate.interpreter.ErgoTreeEvaluator._ import debox.cfor import scorex.util.encode.Base16 +import sigma.ast.SCollection.{SByteArray, SIntArray} +import sigma.ast._ import sigmastate.exceptions.InterpreterException import scala.language.implicitConversions -import scala.reflect.ClassTag import sigmastate.lang.CheckingSigmaBuilder._ import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer import sigmastate.serialization.transformers.ProveDHTupleSerializer @@ -35,6 +35,7 @@ import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigma.{AvlTree, Coll, Colls, Header, PreHeader, _} import sigmastate.lang.SourceContext import sigma.util.safeNewArray +import sigmastate.serialization.ValueCodes.{ConstantCode, OpCode} import scala.collection.compat.immutable.ArraySeq import scala.collection.mutable @@ -846,7 +847,8 @@ object Values { override lazy val value = { val xs = items.cast[EvaluatedValue[SAny.type]].map(_.value) - Colls.fromArray(xs.toArray(SAny.classTag.asInstanceOf[ClassTag[SAny.WrappedType]]))(sigma.AnyType) + implicit val tAny: RType[Any] = sigma.AnyType + Colls.fromArray(xs.toArray) } protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { @@ -909,7 +911,7 @@ object Values { // TODO refactor: this method is not used and can be removed lazy val value = { val xs = items.cast[EvaluatedValue[V]].map(_.value) - Colls.fromArray(xs.toArray(elementType.classTag.asInstanceOf[ClassTag[V#WrappedType]])) + Colls.fromArray(xs.toArray(tElement.classTag)) } protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/DLogProtocol.scala b/interpreter/shared/src/main/scala/sigmastate/crypto/DLogProtocol.scala index a078da2ceb..6c10bda1a4 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/DLogProtocol.scala +++ b/interpreter/shared/src/main/scala/sigmastate/crypto/DLogProtocol.scala @@ -1,7 +1,6 @@ package sigmastate.crypto import java.math.BigInteger - import sigmastate.Values._ import Value.PropositionCode import scorex.util.encode.Base16 @@ -9,9 +8,9 @@ import sigmastate._ import sigmastate.eval._ import sigmastate.crypto.VerifierMessage.Challenge import CryptoConstants.{EcPointType, dlogGroup} -import sigmastate.serialization.{OpCodes, GroupElementSerializer} -import sigmastate.serialization.OpCodes.OpCode +import sigmastate.serialization.{GroupElementSerializer, OpCodes} import sigma.SigmaProp +import sigmastate.serialization.ValueCodes.OpCode object DLogProtocol { diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/DiffieHellmanTupleProtocol.scala b/interpreter/shared/src/main/scala/sigmastate/crypto/DiffieHellmanTupleProtocol.scala index a30e187105..7d5f439862 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/DiffieHellmanTupleProtocol.scala +++ b/interpreter/shared/src/main/scala/sigmastate/crypto/DiffieHellmanTupleProtocol.scala @@ -1,15 +1,14 @@ package sigmastate.crypto import java.math.BigInteger - import sigmastate.Values.Value.PropositionCode import sigmastate._ import sigmastate.crypto.VerifierMessage.Challenge import sigmastate.eval.SigmaDsl import CryptoConstants.EcPointType -import sigmastate.serialization.{OpCodes, GroupElementSerializer} -import sigmastate.serialization.OpCodes.OpCode +import sigmastate.serialization.{GroupElementSerializer, OpCodes} import sigma.SigmaProp +import sigmastate.serialization.ValueCodes.OpCode trait DiffieHellmanTupleProtocol extends SigmaProtocol[DiffieHellmanTupleProtocol] { diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/BigIntegerOps.scala b/interpreter/shared/src/main/scala/sigmastate/eval/BigIntegerOps.scala index 058676b0fe..1a465e67e9 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/BigIntegerOps.scala +++ b/interpreter/shared/src/main/scala/sigmastate/eval/BigIntegerOps.scala @@ -1,6 +1,6 @@ package sigmastate.eval -import sigma.data.{ExactOrderingImpl, ExactIntegral} +import sigma.data.{CBigInt, ExactIntegral, ExactOrderingImpl} import scala.math.{Integral, Ordering} import sigma._ diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/CostingDataContext.scala b/interpreter/shared/src/main/scala/sigmastate/eval/CostingDataContext.scala index 870cbbb5bf..20ad8481bc 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/CostingDataContext.scala +++ b/interpreter/shared/src/main/scala/sigmastate/eval/CostingDataContext.scala @@ -1,16 +1,16 @@ package sigmastate.eval import debox.cfor -import org.ergoplatform.validation.{ValidationRules, SigmaValidationSettings} -import org.ergoplatform.{SigmaConstants, ErgoBox} +import org.ergoplatform.validation.{SigmaValidationSettings, ValidationRules} +import org.ergoplatform.ErgoBox import sigma.data.OverloadHack.Overloaded1 -import sigma.data.RType +import sigma.data.{CBigInt, CollOverArrayBuilder, RType, SigmaConstants, WrapperOf} import sigma.util.Extensions.BigIntegerOps import scorex.crypto.authds.avltree.batch._ import scorex.crypto.authds.{SerializedAdProof, ADDigest, ADValue, ADKey} import scorex.crypto.hash.{Blake2b256, Digest32, Sha256} -import scorex.utils.{Longs, Ints} -import sigmastate.SCollection.SByteArray +import scorex.utils.{Ints, Longs} +import sigma.VersionContext import sigmastate.Values.ErgoTree.EmptyConstants import sigmastate.Values.{EvaluatedValue, SValue, ConstantNode, ErgoTree, SigmaBoolean} import sigmastate._ @@ -21,7 +21,9 @@ import sigmastate.eval.Extensions._ import sigmastate.interpreter.Interpreter import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer import sigmastate.serialization.{GroupElementSerializer, SigmaSerializer} -import sigma.{VersionContext, _} +import sigma._ +import sigma.ast.SCollection.SByteArray +import sigma.ast.{SInt, STuple, SType} import java.math.BigInteger import java.util.Arrays @@ -29,65 +31,9 @@ import scala.annotation.unused import scala.reflect.ClassTag import scala.util.{Success, Failure} -/** Interface implmented by wrappers to provide access to the underlying wrapped value. */ -trait WrapperOf[T] { - /** The data value wrapped by this wrapper. */ - def wrappedValue: T -} - -/** A default implementation of [[BigInt]] interface. - * @see [[BigInt]] for detailed descriptions - */ -case class CBigInt(override val wrappedValue: BigInteger) extends BigInt with WrapperOf[BigInteger] { - val dsl = CostingSigmaDslBuilder - override def toByte : Byte = wrappedValue.toByteExact - override def toShort: Short = wrappedValue.toShortExact - override def toInt : Int = wrappedValue.toIntExact - override def toLong : Long = wrappedValue.toLongExact - - override def toBytes: Coll[Byte] = dsl.Colls.fromArray(wrappedValue.toByteArray) - - override def toAbs: BigInt = dsl.BigInt(wrappedValue.abs()) - - override def compareTo(that: BigInt): Int = - wrappedValue.compareTo(that.asInstanceOf[CBigInt].wrappedValue) - - override def toBits: Coll[Boolean] = ??? - - override def modQ: BigInt = ??? - - override def plusModQ(other: BigInt): BigInt = ??? - - override def minusModQ(other: BigInt): BigInt = ??? - - override def multModQ(other: BigInt): BigInt = ??? - override def inverseModQ: BigInt = ??? - override def signum: Int = wrappedValue.signum() - override def add(that: BigInt): BigInt = dsl.BigInt(wrappedValue.add(that.asInstanceOf[CBigInt].wrappedValue).to256BitValueExact) - - override def subtract(that: BigInt): BigInt = dsl.BigInt(wrappedValue.subtract(that.asInstanceOf[CBigInt].wrappedValue).to256BitValueExact) - - override def multiply(that: BigInt): BigInt = dsl.BigInt(wrappedValue.multiply(that.asInstanceOf[CBigInt].wrappedValue).to256BitValueExact) - - override def divide(that: BigInt): BigInt = dsl.BigInt(wrappedValue.divide(that.asInstanceOf[CBigInt].wrappedValue)) - - override def mod(m: BigInt): BigInt = dsl.BigInt(wrappedValue.mod(m.asInstanceOf[CBigInt].wrappedValue)) - - override def remainder(that: BigInt): BigInt = dsl.BigInt(wrappedValue.remainder(that.asInstanceOf[CBigInt].wrappedValue)) - - override def min(that: BigInt): BigInt = dsl.BigInt(wrappedValue.min(that.asInstanceOf[CBigInt].wrappedValue)) - - override def max(that: BigInt): BigInt = dsl.BigInt(wrappedValue.max(that.asInstanceOf[CBigInt].wrappedValue)) - - override def negate(): BigInt = dsl.BigInt(wrappedValue.negate().to256BitValueExact) - - override def and(that: BigInt): BigInt = dsl.BigInt(wrappedValue.and(that.asInstanceOf[CBigInt].wrappedValue)) - - override def or(that: BigInt): BigInt = dsl.BigInt(wrappedValue.or(that.asInstanceOf[CBigInt].wrappedValue)) -} /** A default implementation of [[GroupElement]] interface. * @see [[GroupElement]] for detailed descriptions diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/Extensions.scala b/interpreter/shared/src/main/scala/sigmastate/eval/Extensions.scala index c7cac60d81..6294912a20 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/Extensions.scala +++ b/interpreter/shared/src/main/scala/sigmastate/eval/Extensions.scala @@ -3,16 +3,16 @@ package sigmastate.eval import debox.{cfor, Buffer => DBuffer} import org.ergoplatform.ErgoBox import org.ergoplatform.ErgoBox.TokenId -import sigma.data.{Nullable, RType} import scorex.util.encode.Base16 -import sigmastate.SType.AnyOps +import sigma.ast.SType.AnyOps +import sigma.ast.{SCollection, SCollectionType, SType} +import sigma.{Coll, _} +import sigma.data.{Nullable, RType} +import sigmastate.Platform import sigmastate.Values.{Constant, ConstantNode} import sigmastate.crypto.{CryptoFacade, Ecp} import sigmastate.lang.{CheckingSigmaBuilder, TransformingSigmaBuilder} import sigmastate.utils.Helpers -import sigmastate.{Platform, SCollection, SCollectionType, SType} -import sigma.Coll -import sigma._ import java.math.BigInteger diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/Profiler.scala b/interpreter/shared/src/main/scala/sigmastate/eval/Profiler.scala index 80266c9063..fb127568b2 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/Profiler.scala +++ b/interpreter/shared/src/main/scala/sigmastate/eval/Profiler.scala @@ -2,8 +2,7 @@ package sigmastate.eval import sigmastate.{FixedCost, JitCost, SMethod} import sigmastate.Values.SValue -import sigmastate.serialization.{OpCodes, ValueSerializer} -import sigmastate.serialization.OpCodes.OpCode +import sigmastate.serialization.{OpCodes, ValueCodes, ValueSerializer} import sigmastate.serialization.ValueSerializer.getSerializer import sigma.util.Extensions.ByteOps import debox.{Buffer => DBuffer, Map => DMap} @@ -11,6 +10,7 @@ import debox.sp import sigmastate.eval.Extensions.DBufferOps import sigmastate.interpreter.{CostItem, FixedCostItem, SeqCostItem, TypeBasedCostItem} import sigmastate.lang.Terms.{MethodCall, PropertyCall} +import sigmastate.serialization.ValueCodes.OpCode import scala.reflect.ClassTag @@ -256,7 +256,7 @@ class Profiler { val suggestedCost = suggestCost(time) val warn = if (suggestedCost > cost) "!!!" else "" val comment = s"count: $count, suggestedCost: $suggestedCost, actualCost: $cost$warn" - (opName, (opCode.toUByte - OpCodes.LastConstantCode).toString, time, comment) + (opName, (opCode.toUByte - ValueCodes.LastConstantCode).toString, time, comment) }.filter(line => line != null && line._1.nonEmpty) .sortBy(_._3)(Ordering[Long].reverse) diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/package.scala b/interpreter/shared/src/main/scala/sigmastate/eval/package.scala index 12b73de5f6..65b187c480 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/package.scala +++ b/interpreter/shared/src/main/scala/sigmastate/eval/package.scala @@ -1,7 +1,6 @@ package sigmastate import java.math.BigInteger - import org.ergoplatform.ErgoBox import sigma.data.RType import scorex.crypto.hash.Digest32 @@ -9,6 +8,7 @@ import sigmastate.Values.SigmaBoolean import sigmastate.crypto.CryptoConstants.EcPointType import sigma.{Coll, CollBuilder} import sigma._ +import sigmastate.exceptions.CostLimitException import supertagged.TaggedType import scala.language.implicitConversions @@ -22,12 +22,6 @@ package object eval { */ val SigmaDsl = CostingSigmaDslBuilder - /** Constructor of tuple value with more than 2 items. - * Such long tuples are represented as Coll[Any]. - * This representaion of tuples is different from representation of pairs (x, y), - * where Tuple2 type is used instead of Coll. */ - def TupleColl(items: Any*): Coll[Any] = Colls.fromItems(items:_*)(sigma.AnyType) - trait BaseDigestColl extends TaggedType[Coll[Byte]] object Digest32Coll extends BaseDigestColl @@ -53,4 +47,35 @@ package object eval { implicit def ergoBoxToBox(p: ErgoBox): Box = SigmaDsl.Box(p) implicit def boxToErgoBox(p: Box): ErgoBox = SigmaDsl.toErgoBox(p) + + def msgCostLimitError( + cost: Long, + limit: Long) = s"Estimated execution cost $cost exceeds the limit $limit" + + /** Helper method to accumulate cost while checking limit. + * + * @param current current cost value + * @param delta additional cost to add to the current value + * @param limit total cost limit + * @param msgSuffix use case-specific error message suffix + * @return new increased cost when it doesn't exceed the limit + * @throws CostLimitException + */ + def addCostChecked( + current: Long, + delta: Long, + limit: Long, + msgSuffix: => String = ""): Long = { + val newCost = java7.compat.Math.addExact(current, delta) + if (newCost > limit) { + throw new CostLimitException( + estimatedCost = newCost, + message = { + val suffix = if (msgSuffix.isEmpty) "" else s": $msgSuffix" + msgCostLimitError(newCost, limit) + suffix + }, + cause = None) + } + newCost + } } diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/CostItem.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/CostItem.scala index 27b50779cf..b0515602b2 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/CostItem.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/CostItem.scala @@ -1,6 +1,7 @@ package sigmastate.interpreter -import sigmastate.{FixedCost, JitCost, PerItemCost, SMethod, SType, TypeBasedCost} +import sigma.ast.SType +import sigmastate.{FixedCost, JitCost, PerItemCost, SMethod, TypeBasedCost} import sigmastate.Values.{FixedCostValueCompanion, PerItemCostValueCompanion, ValueCompanion} import sigmastate.lang.Terms.MethodCall diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/ErgoTreeEvaluator.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/ErgoTreeEvaluator.scala index e1bcd3119c..73a2fa24e6 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/ErgoTreeEvaluator.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/ErgoTreeEvaluator.scala @@ -1,7 +1,7 @@ package sigmastate.interpreter import org.ergoplatform.ErgoLikeContext -import sigmastate.{FixedCost, JitCost, PerItemCost, SType, TypeBasedCost} +import sigmastate.{FixedCost, JitCost, PerItemCost, TypeBasedCost} import sigmastate.Values._ import sigmastate.eval.Profiler import sigmastate.interpreter.ErgoTreeEvaluator.DataEnv @@ -12,6 +12,8 @@ import sigmastate.interpreter.EvalSettings._ import supertagged.TaggedType import debox.{Buffer => DBuffer} import sigma.VersionContext +import sigma.ast.SType + import scala.collection.compat.immutable.ArraySeq import scala.util.DynamicVariable diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala index cb519e12ae..aa2417ef6b 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala @@ -6,23 +6,23 @@ import org.ergoplatform.ErgoLikeContext import org.ergoplatform.validation.SigmaValidationSettings import org.ergoplatform.validation.ValidationRules._ import sigmastate.crypto.DLogProtocol.ProveDlog -import sigmastate.SCollection.SByteArray import sigmastate.Values._ import sigmastate.crypto.DLogProtocol.{DLogInteractiveProver, FirstDLogProverMessage, ProveDlog} import sigmastate.crypto._ import sigmastate.interpreter.Interpreter._ import sigmastate.serialization.{SigmaSerializer, ValueSerializer} import sigmastate.utxo.DeserializeContext -import sigmastate.{SType, _} -import sigmastate.eval.{Evaluation, Profiler, SigmaDsl} +import sigmastate._ +import sigmastate.eval.{Profiler, SigmaDsl, addCostChecked} import sigmastate.FiatShamirTree._ import sigmastate.SigSerializer._ -import sigmastate.eval.Evaluation.addCostChecked import sigmastate.interpreter.ErgoTreeEvaluator.fixedCostOp import sigmastate.utils.Helpers._ import sigmastate.lang.Terms.ValueOps import debox.cfor -import sigma.VersionContext +import sigma.ast.SCollection.SByteArray +import sigma.ast.{SBoolean, SSigmaProp, SType} +import sigma.{Evaluation, VersionContext} import sigma.kiama.rewriting.Strategy import sigmastate.exceptions.{CostLimitException, InterpreterException} @@ -52,6 +52,8 @@ trait Interpreter { type ProofT = UncheckedTree + private val _ = InterpreterReflection + /** Evaluation settings used by [[ErgoTreeEvaluator]] which is used by this * interpreter to perform fullReduction. */ @@ -96,7 +98,7 @@ trait Interpreter { val script = ValueSerializer.deserialize(r) // Why ValueSerializer? read NOTE above val scriptComplexity = java7.compat.Math.multiplyExact(scriptBytes.length, CostPerByteDeserialized) - val currCost = Evaluation.addCostChecked(context.initCost, scriptComplexity, context.costLimit) + val currCost = addCostChecked(context.initCost, scriptComplexity, context.costLimit) val ctx1 = context.withInitCost(currCost).asInstanceOf[CTX] (ctx1, script) } @@ -210,7 +212,7 @@ trait Interpreter { // NOTE, evaluator cost unit needs to be scaled to the cost unit of context val evalCost = Eval_SigmaPropConstant.costKind.cost.toBlockCost - val resCost = Evaluation.addCostChecked(context.initCost, evalCost, context.costLimit) + val resCost = addCostChecked(context.initCost, evalCost, context.costLimit) ReductionResult(sb, resCost) case _ if !ergoTree.hasDeserialize => val ctx = context.asInstanceOf[ErgoLikeContext] @@ -241,7 +243,7 @@ trait Interpreter { implicit val vs: SigmaValidationSettings = context.validationSettings val res = VersionContext.withVersions(context.activatedScriptVersion, ergoTree.version) { val deserializeSubstitutionCost = java7.compat.Math.multiplyExact(ergoTree.bytes.length, CostPerTreeByte) - val currCost = Evaluation.addCostChecked(context.initCost, deserializeSubstitutionCost, context.costLimit) + val currCost = addCostChecked(context.initCost, deserializeSubstitutionCost, context.costLimit) val context1 = context.withInitCost(currCost).asInstanceOf[CTX] val (propTree, context2) = trySoftForkable[(SigmaPropValue, CTX)](whenSoftFork = (TrueSigmaProp, context1)) { applyDeserializeContextJITC(context, prop) diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/InterpreterContext.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/InterpreterContext.scala index 017af3ff9b..c64c1a5e6d 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/InterpreterContext.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/InterpreterContext.scala @@ -1,12 +1,12 @@ package sigmastate.interpreter import org.ergoplatform.validation.SigmaValidationSettings -import sigmastate.SType import sigmastate.Values.EvaluatedValue import sigmastate.interpreter.ContextExtension.VarBinding import sigmastate.serialization.SigmaSerializer import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigma.AnyValue +import sigma.ast.SType import scala.collection.mutable diff --git a/interpreter/shared/src/main/scala/sigmastate/lang/SigmaBuilder.scala b/interpreter/shared/src/main/scala/sigmastate/lang/SigmaBuilder.scala index 8d87d8ffce..3c763fe395 100644 --- a/interpreter/shared/src/main/scala/sigmastate/lang/SigmaBuilder.scala +++ b/interpreter/shared/src/main/scala/sigmastate/lang/SigmaBuilder.scala @@ -2,18 +2,18 @@ package sigmastate.lang import debox.cfor import org.ergoplatform.ErgoBox.RegisterId +import sigma.ast.SCollection.{SByteArray, SIntArray} +import sigma.ast.SOption.SIntOption +import sigma.ast._ import sigma.data.Nullable -import sigma.{AnyValue, Coll, Colls, Environment} -import sigmastate.SCollection.{SByteArray, SIntArray} -import sigmastate.SOption.SIntOption +import sigma.{AnyValue, Coll, Colls, Environment, Evaluation} import sigmastate.Values._ import sigmastate._ -import sigmastate.eval._ import sigmastate.exceptions.ConstraintFailed import sigmastate.lang.Constraints._ import sigmastate.lang.Terms.{STypeSubst, _} import sigmastate.serialization.OpCodes -import sigmastate.serialization.OpCodes.OpCode +import sigmastate.serialization.ValueCodes.OpCode import sigmastate.utxo._ import scala.util.DynamicVariable diff --git a/interpreter/shared/src/main/scala/sigmastate/lang/SigmaPredef.scala b/interpreter/shared/src/main/scala/sigmastate/lang/SigmaPredef.scala index 5b1d3dc2ca..74b1d45992 100644 --- a/interpreter/shared/src/main/scala/sigmastate/lang/SigmaPredef.scala +++ b/interpreter/shared/src/main/scala/sigmastate/lang/SigmaPredef.scala @@ -3,15 +3,16 @@ package sigmastate.lang import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix import org.ergoplatform.{ErgoAddressEncoder, P2PKAddress} import sigma.data.Nullable -import scorex.util.encode.{Base64, Base58, Base16} -import sigmastate.SCollection.{SIntArray, SByteArray} -import sigmastate.SOption._ -import sigmastate.Values.{StringConstant, SValue, IntValue, SigmaPropConstant, Value, ByteArrayConstant, SigmaPropValue, ValueCompanion, Constant, EvaluatedValue, ConstantPlaceholder, BoolValue} +import scorex.util.encode.{Base16, Base58, Base64} +import sigma.ast.SCollection.{SByteArray, SIntArray} +import sigma.ast.SOption.SIntOption +import sigma.ast._ +import sigmastate.Values.{BoolValue, ByteArrayConstant, Constant, ConstantPlaceholder, EvaluatedValue, IntValue, SValue, SigmaPropConstant, SigmaPropValue, StringConstant, Value, ValueCompanion} import sigmastate._ import sigmastate.lang.Terms._ import sigmastate.exceptions.InvalidArguments import sigmastate.serialization.ValueSerializer -import sigmastate.utxo.{DeserializeRegister, SelectField, DeserializeContext, GetVar} +import sigmastate.utxo.{DeserializeContext, DeserializeRegister, GetVar, SelectField} object SigmaPredef { diff --git a/interpreter/shared/src/main/scala/sigmastate/lang/Terms.scala b/interpreter/shared/src/main/scala/sigmastate/lang/Terms.scala index bbb19434bf..a3f4076cb2 100644 --- a/interpreter/shared/src/main/scala/sigmastate/lang/Terms.scala +++ b/interpreter/shared/src/main/scala/sigmastate/lang/Terms.scala @@ -2,19 +2,20 @@ package sigmastate.lang import sigma.kiama.rewriting.Rewriter._ import sigma.data.Nullable -import sigmastate.SCollection.{SIntArray, SByteArray} +import sigma.ast.SCollection.{SByteArray, SIntArray} import sigmastate.Values._ import sigmastate.utils.Overloading.Overload1 import sigmastate._ -import sigmastate.interpreter.{Interpreter, ErgoTreeEvaluator} +import sigmastate.interpreter.{ErgoTreeEvaluator, Interpreter} import sigmastate.interpreter.ErgoTreeEvaluator.DataEnv import sigmastate.serialization.OpCodes -import sigmastate.serialization.OpCodes.OpCode import sigmastate.lang.TransformingSigmaBuilder._ import scala.language.implicitConversions import scala.collection.compat.immutable.ArraySeq import debox.cfor +import sigma.ast._ +import sigmastate.serialization.ValueCodes.OpCode object Terms { @@ -90,9 +91,10 @@ object Terms { override def companion = Select override val tpe: SType = resType.getOrElse(obj.tpe match { case p: SProduct => - val i = p.methodIndex(field) - if (i == -1) NoType - else p.methods(i).stype + MethodsContainer.getMethod(p, field) match { + case Some(m) => m.stype + case None => NoType + } case _ => NoType }) override def opType: SFunc = SFunc(obj.tpe, tpe) @@ -271,14 +273,6 @@ object Terms { override val costKind = FixedCost(JitCost(4)) } - case class STypeParam(ident: STypeVar, upperBound: Option[SType] = None, lowerBound: Option[SType] = None) { - assert(upperBound.isEmpty && lowerBound.isEmpty, s"Type parameters with bounds are not supported, but found $this") - override def toString = ident.toString + upperBound.fold("")(u => s" <: $u") + lowerBound.fold("")(l => s" >: $l") - } - object STypeParam { - implicit def typeIdentToTypeParam(id: STypeVar): STypeParam = STypeParam(id) - } - /** Frontend implementation of lambdas. Should be transformed to FuncValue. */ case class Lambda( tpeParams: Seq[STypeParam], diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ApplySerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ApplySerializer.scala index 89daeb0713..9145491518 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ApplySerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ApplySerializer.scala @@ -1,5 +1,6 @@ package sigmastate.serialization +import sigma.ast.SType import sigmastate.Values._ import sigmastate._ import sigmastate.lang.Terms.Apply diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/BlockValueSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/BlockValueSerializer.scala index 6e4056e275..ea0fad49d2 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/BlockValueSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/BlockValueSerializer.scala @@ -7,6 +7,7 @@ import ValueSerializer._ import sigma.util.safeNewArray import sigmastate.utils.SigmaByteWriter.{DataInfo, U, Vlq} import debox.cfor +import sigma.ast.SType case class BlockValueSerializer(cons: (IndexedSeq[BlockItem], Value[SType]) => Value[SType]) extends ValueSerializer[BlockValue] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/BoolToSigmaPropSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/BoolToSigmaPropSerializer.scala index bb3a282935..742355f61f 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/BoolToSigmaPropSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/BoolToSigmaPropSerializer.scala @@ -1,10 +1,11 @@ package sigmastate.serialization +import sigma.ast.SType import sigmastate.Values.{BoolValue, SigmaPropValue, SValue} import sigmastate.lang.Terms._ import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.{BoolToSigmaProp, SType, Values} +import sigmastate.{BoolToSigmaProp, Values} case class BoolToSigmaPropSerializer(cons: BoolValue => SigmaPropValue) extends ValueSerializer[BoolToSigmaProp] { import sigmastate.Operations.BoolToSigmaPropInfo._ diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/CaseObjectSerialization.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/CaseObjectSerialization.scala index a1ece38023..479cabd01c 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/CaseObjectSerialization.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/CaseObjectSerialization.scala @@ -1,6 +1,6 @@ package sigmastate.serialization -import sigmastate.SType +import sigma.ast.SType import sigmastate.Values.{Value, ValueCompanion} import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionBooleanConstantSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionBooleanConstantSerializer.scala index 0419fd6e04..c901f81285 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionBooleanConstantSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionBooleanConstantSerializer.scala @@ -1,11 +1,12 @@ package sigmastate.serialization -import sigmastate.{SCollection, SBoolean, ArgInfo} import sigmastate.Values._ import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import SigmaByteWriter._ import sigma.util.safeNewArray import debox.cfor +import sigma.ast.{SBoolean, SCollection} +import sigmastate.ArgInfo case class ConcreteCollectionBooleanConstantSerializer(cons: (IndexedSeq[Value[SBoolean.type]], SBoolean.type) => Value[SCollection[SBoolean.type]]) extends ValueSerializer[ConcreteCollection[SBoolean.type]] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionSerializer.scala index c11452dde8..5419599b61 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ConcreteCollectionSerializer.scala @@ -1,12 +1,13 @@ package sigmastate.serialization -import sigmastate.{SCollection, ArgInfo, SType} +import sigmastate.{ArgInfo} import sigmastate.Values._ import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import ValueSerializer._ import sigma.util.safeNewArray import sigmastate.utils.SigmaByteWriter.{DataInfo, U, Vlq} import debox.cfor +import sigma.ast.{SCollection, SType} case class ConcreteCollectionSerializer(cons: (IndexedSeq[Value[SType]], SType) => Value[SCollection[SType]]) extends ValueSerializer[ConcreteCollection[_ <: SType]] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantPlaceholderSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantPlaceholderSerializer.scala index 803f17079f..0cb771f370 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantPlaceholderSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantPlaceholderSerializer.scala @@ -1,7 +1,7 @@ package sigmastate.serialization +import sigma.ast.SType import sigmastate.Values._ -import sigmastate._ import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} case class ConstantPlaceholderSerializer(cons: (Int, SType) => Value[SType]) diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantSerializer.scala index 8e97117467..e23cfc984d 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantSerializer.scala @@ -1,6 +1,6 @@ package sigmastate.serialization -import sigmastate.SType +import sigma.ast.SType import sigmastate.Values._ import sigmastate.lang.SigmaBuilder import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantStore.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantStore.scala index dfa7dbb30a..45ac168ef4 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantStore.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ConstantStore.scala @@ -1,9 +1,9 @@ package sigmastate.serialization -import sigmastate.SType import sigmastate.Values.{Constant, ConstantNode, ConstantPlaceholder} import sigmastate.lang.SigmaBuilder import debox.Buffer +import sigma.ast.SType /** HOTSPOT: used in deserialization (don't beautify this code) */ class ConstantStore(private val constants: IndexedSeq[Constant[SType]] = Constant.EmptySeq) { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/CreateAvlTreeSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/CreateAvlTreeSerializer.scala index efd84f38b6..a8aaac50d3 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/CreateAvlTreeSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/CreateAvlTreeSerializer.scala @@ -1,7 +1,8 @@ package sigmastate.serialization -import sigmastate.SCollection._ -import sigmastate.SOption.SIntOption +import sigma.ast.SCollection.SByteArray +import sigma.ast.SInt +import sigma.ast.SOption.SIntOption import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate._ import sigmastate.Values._ diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/DataSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/DataSerializer.scala index 65fb2cc0c7..a2f87ac773 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/DataSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/DataSerializer.scala @@ -2,17 +2,18 @@ package sigmastate.serialization import java.math.BigInteger import java.nio.charset.StandardCharsets - import org.ergoplatform.ErgoBox import org.ergoplatform.validation.ValidationRules.CheckSerializableTypeCode import sigma.data.RType import sigmastate.Values.SigmaBoolean import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate._ -import sigmastate.eval.{Evaluation, _} -import sigma._ +import sigmastate.eval._ +import sigma.{Evaluation, _} import debox.cfor +import sigma.ast._ import sigmastate.exceptions.SerializerException + import scala.collection.mutable /** This works in tandem with ConstantSerializer, if you change one make sure to check the other.*/ diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ErgoTreeSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ErgoTreeSerializer.scala index f8c5221945..85c0c77e04 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ErgoTreeSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ErgoTreeSerializer.scala @@ -2,7 +2,6 @@ package sigmastate.serialization import org.ergoplatform.validation.ValidationRules.{CheckDeserializedScriptIsSigmaProp, CheckHeaderSizeBit, CheckPositionLimit} import org.ergoplatform.validation.{SigmaValidationSettings, ValidationException} -import sigmastate.{SType} import sigmastate.Values.{Constant, ErgoTree, UnparsedErgoTree} import sigmastate.lang.DeserializationSigmaBuilder import sigmastate.lang.Terms.ValueOps @@ -12,7 +11,9 @@ import sigma.util.safeNewArray import sigmastate.utxo.ComplexityTable import debox.cfor import sigma.VersionContext -import sigmastate.exceptions.{SerializerException, ReaderPositionLimitExceeded} +import sigma.ast.SType +import sigmastate.exceptions.{ReaderPositionLimitExceeded, SerializerException} + import java.util /** diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/FuncValueSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/FuncValueSerializer.scala index d9f9ea752d..5ff6659317 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/FuncValueSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/FuncValueSerializer.scala @@ -7,6 +7,7 @@ import ValueSerializer._ import sigma.util.safeNewArray import sigmastate.utils.SigmaByteWriter.{DataInfo, U, Vlq} import debox.cfor +import sigma.ast.SType case class FuncValueSerializer(cons: (IndexedSeq[(Int, SType)], Value[SType]) => Value[SType]) extends ValueSerializer[FuncValue] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/GetVarSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/GetVarSerializer.scala index cd9e9872c4..d3c797f896 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/GetVarSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/GetVarSerializer.scala @@ -1,5 +1,6 @@ package sigmastate.serialization +import sigma.ast.{SOption, SType} import sigmastate.Values._ import sigmastate._ import sigmastate.utils.SigmaByteWriter.DataInfo diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/MethodCallSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/MethodCallSerializer.scala index e474d8a7c2..2892463755 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/MethodCallSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/MethodCallSerializer.scala @@ -9,6 +9,7 @@ import sigmastate.utils.SigmaByteWriter.{DataInfo, valuesItemInfo} import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.ComplexityTable import debox.cfor +import sigma.ast.SType case class MethodCallSerializer(cons: (Value[SType], SMethod, IndexedSeq[Value[SType]], STypeSubst) => Value[SType]) extends ValueSerializer[MethodCall] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ModQArithOpSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ModQArithOpSerializer.scala index 765aaeb7b4..2cde4929b2 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ModQArithOpSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ModQArithOpSerializer.scala @@ -1,10 +1,11 @@ package sigmastate.serialization +import sigma.ast.SType import sigmastate.Values.{BigIntValue, Value, SValue} import sigmastate.lang.Terms._ import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.{ModQArithOpCompanion, SType, ModQArithOp} +import sigmastate.{ModQArithOpCompanion, ModQArithOp} // TODO v6.0: make sure it is covered with tests (see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/327) case class ModQArithOpSerializer(override val opDesc: ModQArithOpCompanion, cons: (BigIntValue, BigIntValue) => BigIntValue) diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ModQSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ModQSerializer.scala index 335c12c1af..374115c585 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ModQSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ModQSerializer.scala @@ -1,9 +1,10 @@ package sigmastate.serialization +import sigma.ast.SType import sigmastate.Values.Value import sigmastate.lang.Terms._ import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.{ModQ, SType} +import sigmastate.ModQ // TODO v6.0: make sure it is covered with tests (see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/327) object ModQSerializer extends ValueSerializer[ModQ] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/OneArgumentOperationSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/OneArgumentOperationSerializer.scala index fd3fd8c2ea..c70eae922a 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/OneArgumentOperationSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/OneArgumentOperationSerializer.scala @@ -1,10 +1,11 @@ package sigmastate.serialization +import sigma.ast.SType import sigmastate.Values.{Value, SValue} import sigmastate.lang.Terms._ import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.{OneArgumentOperation, OneArgumentOperationCompanion, SType} +import sigmastate.{OneArgumentOperation, OneArgumentOperationCompanion} case class OneArgumentOperationSerializer[T <: SType](opDesc: OneArgumentOperationCompanion, cons: Value[T] => SValue) extends ValueSerializer[OneArgumentOperation[T, SType]] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/OpCodes.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/OpCodes.scala index 74ec9bd58e..2e0469ffce 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/OpCodes.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/OpCodes.scala @@ -1,23 +1,14 @@ package sigmastate.serialization -import sigmastate.serialization.OpCodes.OpCode +import sigma.ast.TypeCodes +import sigmastate.serialization.ValueCodes.OpCode import supertagged.TaggedType -/** Encoding of types for serialization. */ -trait TypeCodes { - /** Decoding of types depends on the first byte and in general is a recursive procedure - * consuming some number of bytes from Reader. - * All data types are recognized by the first byte falling in the region [FirstDataType .. LastDataType] */ - val FirstDataType: OpCode = OpCode @@ 1.toByte - val LastDataType : OpCode = OpCode @@ 111.toByte - - /** SFunc types occupy remaining space of byte values [FirstFuncType .. 255] */ - val FirstFuncType: OpCode = OpCode @@ (LastDataType + 1).toByte - val LastFuncType : OpCode = OpCode @@ 255.toByte -} - /** Encoding of values for serialization. */ -trait ValueCodes extends TypeCodes { +object ValueCodes { + object OpCode extends TaggedType[Byte] + type OpCode = OpCode.Type + /** We use optimized encoding of constant values to save space in serialization. * Since Box registers are stored as Constant nodes we save 1 byte for each register. * This is due to convention that Value.opCode falling in [1..LastDataType] region is a constant. @@ -31,7 +22,7 @@ trait ValueCodes extends TypeCodes { /** The last constant code is equal to FirstFuncType which represent generic function type. * We use this single code to represent all functional constants, since we don't have enough space in single byte. * Subsequent bytes have to be read from Reader in order to decode the type of the function and the corresponding data. */ - val LastConstantCode: OpCode = OpCode @@ (LastDataType + 1).toByte + val LastConstantCode: OpCode = OpCode @@ (TypeCodes.LastDataType + 1).toByte } /** The set of all possible IR graph nodes can be split in two subsets: @@ -52,10 +43,8 @@ trait ValueCodes extends TypeCodes { * 1) For validation rule CheckValidOpCode we use OpCodes range, so we use single byte encoding. * 2) For CheckCostFuncOperation we use 1-511 range and extended encoding (see docs) */ -object OpCodes extends ValueCodes { - - object OpCode extends TaggedType[Byte] - type OpCode = OpCode.Type +object OpCodes { + import ValueCodes._ private def newOpCode(shift: Short): OpCode = OpCode @@ (LastConstantCode + shift).toByte diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/OptionGetOrElseSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/OptionGetOrElseSerializer.scala index bc0fe694e6..1c6bda46d0 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/OptionGetOrElseSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/OptionGetOrElseSerializer.scala @@ -1,5 +1,6 @@ package sigmastate.serialization +import sigma.ast.{SOption, SType} import sigmastate.Values._ import sigmastate._ import sigmastate.lang.Terms._ diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/PropertyCallSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/PropertyCallSerializer.scala index 0c4b15aaf5..00fc16268f 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/PropertyCallSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/PropertyCallSerializer.scala @@ -1,12 +1,13 @@ package sigmastate.serialization +import sigma.ast.SType import sigmastate.Values._ import sigmastate._ import sigmastate.lang.Terms import sigmastate.lang.Terms.STypeSubst import sigmastate.lang.Terms.{MethodCall, PropertyCall} import sigmastate.utils.SigmaByteWriter.DataInfo -import sigmastate.utils.{SigmaByteWriter, SigmaByteReader} +import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.ComplexityTable case class PropertyCallSerializer(cons: (Value[SType], SMethod, IndexedSeq[Value[SType]], STypeSubst) => Value[SType]) diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ProveDlogSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ProveDlogSerializer.scala index 89400938fe..f15b98cfc4 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ProveDlogSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ProveDlogSerializer.scala @@ -1,7 +1,8 @@ package sigmastate.serialization +import sigma.ast.SGroupElement import sigmastate.crypto.DLogProtocol.ProveDlog -import sigmastate.{SGroupElement, CreateProveDlog} +import sigmastate.CreateProveDlog import sigmastate.Values.{Value, SValue, SigmaPropValue} import sigmastate.crypto.CryptoConstants.EcPointType import sigmastate.lang.Terms._ diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/SelectFieldSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/SelectFieldSerializer.scala index 6abf691f8d..61085fa5c2 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/SelectFieldSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/SelectFieldSerializer.scala @@ -1,12 +1,12 @@ package sigmastate.serialization import sigmastate.Operations.SelectFieldInfo -import sigmastate.Values.{Value, SValue} +import sigmastate.Values.{SValue, Value} import sigmastate.lang.Terms._ import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.SelectField -import sigmastate.{STuple, SType} import SelectFieldInfo._ +import sigma.ast.{STuple, SType} import sigmastate.utils.SigmaByteWriter.DataInfo case class SelectFieldSerializer(cons: (Value[STuple], Byte) => Value[SType]) extends ValueSerializer[SelectField] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropBytesSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropBytesSerializer.scala index 754880cd16..658e4cdae8 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropBytesSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropBytesSerializer.scala @@ -1,7 +1,8 @@ package sigmastate.serialization +import sigma.ast.SType import sigmastate.Values.SValue -import sigmastate.{Values, SType} +import sigmastate.Values import sigmastate.lang.Terms._ import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropIsProvenSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropIsProvenSerializer.scala index 0350f582bb..fb7892f940 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropIsProvenSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaPropIsProvenSerializer.scala @@ -1,6 +1,7 @@ package sigmastate.serialization -import sigmastate.{Values, SType} +import sigma.ast.SType +import sigmastate.Values import sigmastate.lang.Terms._ import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.SigmaPropIsProven diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaSerializer.scala index eea880521a..6e3671a00b 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/SigmaSerializer.scala @@ -1,14 +1,13 @@ package sigmastate.serialization import java.nio.ByteBuffer - -import org.ergoplatform.SigmaConstants import org.ergoplatform.validation.SigmaValidationSettings import scorex.util.ByteArrayBuilder import sigmastate.utils._ import scorex.util.serialization._ +import sigma.data.SigmaConstants import sigmastate.exceptions.SerializerException -import sigmastate.serialization.OpCodes.OpCode +import sigmastate.serialization.ValueCodes.OpCode object SigmaSerializer { type Position = Int diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/SubstConstantsSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/SubstConstantsSerializer.scala index 2c55458280..127d3f0593 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/SubstConstantsSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/SubstConstantsSerializer.scala @@ -1,11 +1,12 @@ package sigmastate.serialization -import sigmastate.SCollection.{SIntArray, SByteArray} +import sigma.ast.SCollection.{SIntArray, SByteArray} import sigmastate.Values.{Value, SValue} import sigmastate.lang.Terms._ import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.{SCollection, SubstConstants, SType} +import sigma.ast.{SCollection, SType} +import sigmastate.SubstConstants object SubstConstantsSerializer extends ValueSerializer[SubstConstants[SType]] { import sigmastate.Operations.SubstConstantsInfo._ diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/TaggedVariableSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/TaggedVariableSerializer.scala index bc99becd19..6f233bf10c 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/TaggedVariableSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/TaggedVariableSerializer.scala @@ -1,5 +1,6 @@ package sigmastate.serialization +import sigma.ast.SType import sigmastate.Values._ import sigmastate._ import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/TupleSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/TupleSerializer.scala index a88a17fa5f..3ba830f349 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/TupleSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/TupleSerializer.scala @@ -1,12 +1,13 @@ package sigmastate.serialization -import sigmastate.{SType, ArgInfo} +import sigmastate.{ArgInfo} import sigmastate.Values._ import sigmastate.utils.{SigmaByteWriter, SigmaByteReader} import sigmastate.serialization.ValueSerializer._ import sigma.util.safeNewArray import sigmastate.utils.SigmaByteWriter.{DataInfo, U} import debox.cfor +import sigma.ast.SType case class TupleSerializer(cons: Seq[Value[SType]] => Value[SType]) extends ValueSerializer[Tuple] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/TwoArgumentsSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/TwoArgumentsSerializer.scala index a4bb89fa29..ec6c917e03 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/TwoArgumentsSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/TwoArgumentsSerializer.scala @@ -1,10 +1,11 @@ package sigmastate.serialization +import sigma.ast.SType import sigmastate.Values.{Value, SValue} import sigmastate.lang.Terms._ import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.{TwoArgumentsOperation, SType, TwoArgumentOperationCompanion} +import sigmastate.{TwoArgumentsOperation, TwoArgumentOperationCompanion} case class TwoArgumentsSerializer[LIV <: SType, RIV <: SType, OV <: Value[SType]] (override val opDesc: TwoArgumentOperationCompanion, constructor: (Value[LIV], Value[RIV]) => Value[SType]) diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/TypeSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/TypeSerializer.scala index 4dc9335ff3..265c7e36a3 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/TypeSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/TypeSerializer.scala @@ -6,12 +6,13 @@ import sigmastate._ import sigma.util.safeNewArray import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import debox.cfor +import sigma.ast.SCollectionType.{CollectionTypeCode, NestedCollectionTypeCode} +import sigma.ast._ import sigmastate.exceptions.InvalidTypePrefix /** Serialization of types according to specification in TypeSerialization.md. */ object TypeSerializer { - import sigmastate.SCollectionType._ /** The list of embeddable types, i.e. types 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 single byte. */ diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ValDefSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ValDefSerializer.scala index cdac6309f8..023d9fe590 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ValDefSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ValDefSerializer.scala @@ -8,6 +8,7 @@ import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import ValueSerializer._ import sigma.util.safeNewArray import debox.cfor +import sigma.ast.{SType, STypeVar} case class ValDefSerializer(override val opDesc: ValueCompanion) extends ValueSerializer[ValDef] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ValDefTypeStore.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ValDefTypeStore.scala index 62c72317d5..2fc0373a02 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ValDefTypeStore.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ValDefTypeStore.scala @@ -1,6 +1,6 @@ package sigmastate.serialization -import sigmastate.SType +import sigma.ast.SType import scala.collection.mutable diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ValUseSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ValUseSerializer.scala index 523139c3ab..8091f9bef0 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ValUseSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ValUseSerializer.scala @@ -1,5 +1,6 @@ package sigmastate.serialization +import sigma.ast.SType import sigmastate.Values._ import sigmastate._ import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/ValueSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/ValueSerializer.scala index 056da7587b..88f29c083e 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/ValueSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/ValueSerializer.scala @@ -2,12 +2,13 @@ package sigmastate.serialization import org.ergoplatform.validation.ValidationRules.CheckValidOpCode import org.ergoplatform._ +import sigma.ast.SCollection.SByteArray +import sigma.ast._ import sigma.util.Extensions.toUByte -import sigmastate.SCollection.SByteArray import sigmastate.Values._ import sigmastate._ import sigmastate.lang.DeserializationSigmaBuilder -import sigmastate.serialization.OpCodes._ +import sigmastate.serialization.ValueCodes.{LastConstantCode, OpCode} import sigmastate.serialization.transformers._ import sigmastate.serialization.trees.{QuadrupleSerializer, Relation2Serializer} import sigmastate.utils.SigmaByteWriter.DataInfo diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AppendSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AppendSerializer.scala index 970c1b66d0..000a33bbdb 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AppendSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AppendSerializer.scala @@ -6,7 +6,7 @@ import sigmastate.lang.Terms._ import sigmastate.serialization.ValueSerializer import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.Append -import sigmastate.{SCollection, SType} +import sigma.ast.{SCollection, SType} case class AppendSerializer(cons: (Value[SCollection[SType]], Value[SCollection[SType]]) => Value[SCollection[SType]]) extends ValueSerializer[Append[SType]] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AtLeastSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AtLeastSerializer.scala index a401921fed..120a7455d2 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AtLeastSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/AtLeastSerializer.scala @@ -1,7 +1,8 @@ package sigmastate.serialization.transformers +import sigma.ast.{SCollection, SInt, SSigmaProp} import sigmastate.Operations.AtLeastInfo -import sigmastate.Values.{Value, SigmaPropValue} +import sigmastate.Values.{SigmaPropValue, Value} import sigmastate.lang.Terms._ import sigmastate._ import sigmastate.serialization.ValueSerializer diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/BooleanTransformerSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/BooleanTransformerSerializer.scala index 8c5975cf8a..db32edae3f 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/BooleanTransformerSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/BooleanTransformerSerializer.scala @@ -6,7 +6,7 @@ import sigmastate.serialization.ValueSerializer import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.{BooleanTransformer, BooleanTransformerCompanion} -import sigmastate.{SCollection, SBoolean, SType, SFunc} +import sigma.ast.{SCollection, SBoolean, SType, SFunc} case class BooleanTransformerSerializer[T <: SType] (opDesc: BooleanTransformerCompanion, diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ByIndexSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ByIndexSerializer.scala index 15ea23db30..ef374782bc 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ByIndexSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ByIndexSerializer.scala @@ -8,7 +8,7 @@ import sigmastate.Operations.ByIndexInfo._ import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.ByIndex -import sigmastate.{SInt, SCollection, SType} +import sigma.ast.{SInt, SCollection, SType} case class ByIndexSerializer(cons: (Value[SCollection[SType]], Value[SInt.type], Option[Value[SType]]) => Value[SType]) extends ValueSerializer[ByIndex[SType]] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeContextSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeContextSerializer.scala index f2fe92434d..807d1212c8 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeContextSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeContextSerializer.scala @@ -1,11 +1,12 @@ package sigmastate.serialization.transformers -import sigmastate.{SType, ArgInfo} +import sigmastate.ArgInfo import sigmastate.Values._ import sigmastate.serialization.ValueSerializer import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.DeserializeContext import SigmaByteWriter._ +import sigma.ast.SType import sigmastate.Operations.DeserializeContextInfo case class DeserializeContextSerializer(cons: (Byte, SType) => Value[SType]) diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeRegisterSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeRegisterSerializer.scala index 47c1ead8e4..4287380e4d 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeRegisterSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/DeserializeRegisterSerializer.scala @@ -2,10 +2,11 @@ package sigmastate.serialization.transformers import org.ergoplatform.ErgoBox import org.ergoplatform.ErgoBox.RegisterId -import sigmastate.{ArgInfo, SType} +import sigmastate.ArgInfo import sigmastate.Values.{Value, SValue} import sigmastate.serialization.ValueSerializer import ValueSerializer._ +import sigma.ast.SType import sigmastate.Operations.DeserializeRegisterInfo._ import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ExtractRegisterAsSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ExtractRegisterAsSerializer.scala index f84933b332..004c602117 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ExtractRegisterAsSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ExtractRegisterAsSerializer.scala @@ -7,7 +7,8 @@ import sigmastate.serialization.ValueSerializer import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.ExtractRegisterAs -import sigmastate.{SBox, SOption, ArgInfo, SType} +import sigma.ast.{SBox, SOption, SType} +import sigmastate.ArgInfo case class ExtractRegisterAsSerializer(cons: (Value[SBox.type], RegisterId, SOption[SType]) => Value[SType]) extends ValueSerializer[ExtractRegisterAs[SType]] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FilterSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FilterSerializer.scala index 1c16a9d932..54aba2b7cc 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FilterSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FilterSerializer.scala @@ -5,7 +5,7 @@ import sigmastate.lang.Terms._ import sigmastate.serialization.ValueSerializer import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.Filter -import sigmastate.{SCollection, SType, SFunc} +import sigma.ast.{SCollection, SType, SFunc} case class FilterSerializer(cons: (Value[SCollection[SType]], Value[SFunc]) => Value[SCollection[SType]]) extends ValueSerializer[Filter[SType]] { override def opDesc = Filter diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FoldSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FoldSerializer.scala index 0159e10a0a..81bfa0e796 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FoldSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/FoldSerializer.scala @@ -6,7 +6,7 @@ import sigmastate.serialization.ValueSerializer import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.Fold -import sigmastate.{SCollection, SType, SFunc} +import sigma.ast.{SCollection, SType, SFunc} case class FoldSerializer(cons: (Value[SCollection[SType]], Value[SType], Value[SFunc]) => Value[SType]) extends ValueSerializer[Fold[SType, SType]] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/LogicalTransformerSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/LogicalTransformerSerializer.scala index 18b251f483..128fd07331 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/LogicalTransformerSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/LogicalTransformerSerializer.scala @@ -1,12 +1,13 @@ package sigmastate.serialization.transformers +import sigma.ast.{SBoolean, SCollection} import sigmastate.Values.{Value, SValue} import sigmastate.lang.Terms._ import sigmastate.serialization.ValueSerializer import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.Transformer -import sigmastate.{SCollection, SBoolean, LogicalTransformerCompanion} +import sigmastate.LogicalTransformerCompanion case class LogicalTransformerSerializer[I <: SCollection[SBoolean.type], O <: SBoolean.type] (opDesc: LogicalTransformerCompanion, diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/MapCollectionSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/MapCollectionSerializer.scala index 3e6fab5949..ad830a8638 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/MapCollectionSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/MapCollectionSerializer.scala @@ -6,7 +6,7 @@ import sigmastate.serialization.ValueSerializer import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.MapCollection -import sigmastate.{SCollection, SType, SFunc} +import sigma.ast.{SCollection, SType, SFunc} case class MapCollectionSerializer(cons: (Value[SCollection[SType]], Value[SFunc]) => Value[SType]) extends ValueSerializer[MapCollection[SType, SType]] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/NumericCastSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/NumericCastSerializer.scala index 88d521ae09..758bed499d 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/NumericCastSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/NumericCastSerializer.scala @@ -1,6 +1,7 @@ package sigmastate.serialization.transformers -import sigmastate.Values.{Value, SValue} +import sigma.ast.{SNumericType, SType} +import sigmastate.Values.{SValue, Value} import sigmastate._ import sigmastate.lang.Terms._ import sigmastate.serialization.ValueSerializer diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ProveDHTupleSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ProveDHTupleSerializer.scala index 39406a35c0..a5108d0b71 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ProveDHTupleSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/ProveDHTupleSerializer.scala @@ -1,6 +1,7 @@ package sigmastate.serialization.transformers -import sigmastate.{SGroupElement, CreateProveDHTuple} +import sigma.ast.SGroupElement +import sigmastate.CreateProveDHTuple import sigmastate.Values.{Value, SigmaPropValue} import sigmastate.crypto.ProveDHTuple import sigmastate.crypto.CryptoConstants.EcPointType diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SimpleTransformerSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SimpleTransformerSerializer.scala index f01ae8fd20..933ac7ce07 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SimpleTransformerSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SimpleTransformerSerializer.scala @@ -1,12 +1,12 @@ package sigmastate.serialization.transformers -import sigmastate.SType -import sigmastate.Values.{Value, SValue} +import sigma.ast.SType +import sigmastate.Values.{SValue, Value} import sigmastate.lang.Terms._ import sigmastate.serialization.ValueSerializer import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} -import sigmastate.utxo.{Transformer, SimpleTransformerCompanion} +import sigmastate.utxo.{SimpleTransformerCompanion, Transformer} case class SimpleTransformerSerializer[I <: SType, O <: SType] (opDesc: SimpleTransformerCompanion, diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SliceSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SliceSerializer.scala index ed4f2a15b7..615e199fc5 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SliceSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/transformers/SliceSerializer.scala @@ -6,7 +6,7 @@ import sigmastate.serialization.ValueSerializer import sigmastate.utils.SigmaByteWriter.DataInfo import sigmastate.utils.{SigmaByteReader, SigmaByteWriter} import sigmastate.utxo.Slice -import sigmastate.{SInt, SCollection, SType} +import sigma.ast.{SInt, SCollection, SType} case class SliceSerializer(cons: (Value[SCollection[SType]], Value[SInt.type], Value[SInt.type]) => Value[SCollection[SType]]) extends ValueSerializer[Slice[SType]] { diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/trees/QuadrupleSerializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/trees/QuadrupleSerializer.scala index f6d3f91ff1..5a7b0c714d 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/trees/QuadrupleSerializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/trees/QuadrupleSerializer.scala @@ -1,5 +1,6 @@ package sigmastate.serialization.trees +import sigma.ast.SType import sigmastate.Values._ import sigmastate.lang.Terms._ import sigmastate.serialization.ValueSerializer diff --git a/interpreter/shared/src/main/scala/sigmastate/serialization/trees/Relation2Serializer.scala b/interpreter/shared/src/main/scala/sigmastate/serialization/trees/Relation2Serializer.scala index 655fa8f2d2..f9e8abaf2d 100644 --- a/interpreter/shared/src/main/scala/sigmastate/serialization/trees/Relation2Serializer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/serialization/trees/Relation2Serializer.scala @@ -1,5 +1,6 @@ package sigmastate.serialization.trees +import sigma.ast.{SBoolean, SType} import sigmastate.Values._ import sigmastate._ import sigmastate.serialization.OpCodes._ diff --git a/interpreter/shared/src/main/scala/sigmastate/sigmastate.scala b/interpreter/shared/src/main/scala/sigmastate/sigmastate.scala index 185fbebb9d..dbaa2a01cb 100644 --- a/interpreter/shared/src/main/scala/sigmastate/sigmastate.scala +++ b/interpreter/shared/src/main/scala/sigmastate/sigmastate.scala @@ -1,7 +1,8 @@ import org.ergoplatform.{ErgoBox, ErgoBoxCandidate, ErgoLikeContext} -import sigma.data.{RType, GeneralType} +import sigma.ast._ +import sigma.data.{GeneralType, RType} import sigmastate.Values._ -import sigmastate.lang.CheckingSigmaBuilder +import sigmastate.lang.{CheckingSigmaBuilder, Terms} import scala.annotation.nowarn import scala.reflect.classTag @@ -26,6 +27,62 @@ package object sigmastate { implicit val ErgoLikeContextRType : RType[ErgoLikeContext] = RType.fromClassTag(classTag[ErgoLikeContext]) + 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]] + + /** 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) tpe + else + Terms.applySubst(tpe, subst) + } + /** Helper method to create "+" operation node. */ def Plus[T <: SNumericType](left: Value[T], right: Value[T]): Value[T] = mkPlus(left, right) diff --git a/interpreter/shared/src/main/scala/sigmastate/trees.scala b/interpreter/shared/src/main/scala/sigmastate/trees.scala index 2346ccd9e6..33d35dfaef 100644 --- a/interpreter/shared/src/main/scala/sigmastate/trees.scala +++ b/interpreter/shared/src/main/scala/sigmastate/trees.scala @@ -1,18 +1,19 @@ package sigmastate import debox.{cfor, Map => DMap} -import org.ergoplatform.SigmaConstants import org.ergoplatform.validation.SigmaValidationSettings import sigma.data.ExactIntegral._ import sigma.data.ExactOrdering._ import sigma.data.OverloadHack.Overloaded1 -import sigma.data.{ExactIntegral, ExactOrdering} +import sigma.data.{ExactIntegral, ExactOrdering, SigmaConstants} import scorex.crypto.hash.{Blake2b256, CryptographicHash32, Sha256} +import sigma.ast.SCollection +import sigma.ast.SCollection.{SByteArray, SIntArray} +import sigma.ast.SOption.SIntOption import sigma.{Coll, Colls, GroupElement, SigmaProp, VersionContext} import sigmastate.ArithOp.OperationImpl import sigmastate.Operations._ -import sigmastate.SCollection.{SByteArray, SIntArray} -import sigmastate.SOption.SIntOption +import sigma.ast._ import sigmastate.Values._ import sigmastate.eval.Extensions.EvalCollOps import sigmastate.eval.NumericOps.{BigIntIsExactIntegral, BigIntIsExactOrdering} @@ -20,6 +21,7 @@ import sigmastate.eval.SigmaDsl import sigmastate.interpreter.ErgoTreeEvaluator import sigmastate.interpreter.ErgoTreeEvaluator.DataEnv import sigmastate.serialization.OpCodes._ +import sigmastate.serialization.ValueCodes.OpCode import sigmastate.serialization._ import sigmastate.utxo.{SimpleTransformerCompanion, Transformer} @@ -1464,7 +1466,7 @@ case class TreeLookup(tree: Value[SAvlTree.type], key: Value[SByteArray], proof: Value[SByteArray]) extends Quadruple[SAvlTree.type, SByteArray, SByteArray, SOption[SByteArray]] { override def companion = TreeLookup - override def tpe = SOption[SByteArray] + override def tpe = SOption[SByteArray](SByteArray) override lazy val first = tree override lazy val second = key override lazy val third = proof diff --git a/interpreter/shared/src/main/scala/sigmastate/types.scala b/interpreter/shared/src/main/scala/sigmastate/types.scala index 586a06432e..43ac6483b2 100644 --- a/interpreter/shared/src/main/scala/sigmastate/types.scala +++ b/interpreter/shared/src/main/scala/sigmastate/types.scala @@ -1,360 +1,53 @@ package sigmastate -import java.math.BigInteger +import debox.cfor import org.ergoplatform._ import org.ergoplatform.validation._ -import sigma.data.{Nullable, RType} -import sigma.data.GeneralType -import sigmastate.SType.TypeCode -import sigmastate.interpreter._ -import sigmastate.utils.Overloading.Overload1 -import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.authds.avltree.batch.{Insert, Lookup, Remove, Update} +import scorex.crypto.authds.{ADKey, ADValue} +import sigma.ast.SCollection.{SBooleanArray, SBoxArray, SByteArray, SByteArray2, SHeaderArray} +import sigma.ast.SType.TypeCode +import sigma.ast._ +import sigma.data.{Nullable, RType, SigmaConstants} +import sigma.reflection.RClass +import sigma.{Coll, _} +import sigmastate.SMethod.{MethodCallIrBuilder, MethodCostFunc, javaMethodOf} import sigmastate.Values._ +import sigmastate.eval._ +import sigmastate.interpreter._ +import sigmastate.lang.Terms import sigmastate.lang.Terms._ -import sigmastate.lang.{SigmaBuilder, Terms} -import sigmastate.SCollection._ -import sigmastate.crypto.CryptoConstants.EcPointType -import sigmastate.serialization.OpCodes -import sigma.Coll -import sigma._ - -import scala.language.implicitConversions -import scala.reflect.{ClassTag, classTag} -import scala.collection.compat.immutable.ArraySeq -import sigmastate.SMethod.{InvokeDescBuilder, MethodCallIrBuilder, MethodCostFunc, javaMethodOf} +import sigmastate.utils.Overloading.Overload1 +import sigmastate.utils.SparseArrayContainer import sigmastate.utxo._ -import sigmastate.lang.Terms.STypeSubst -import sigmastate.eval.Evaluation.stypeToRType -import sigmastate.eval._ -import debox.cfor -import sigma.reflection.{RClass, RMethod} -import sigma.util.Extensions.{IntOps, LongOps, ShortOps} +import scala.language.implicitConversions import scala.util.{Failure, Success} -/** 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.type = SByte - implicit val typeShort : SShort.type = SShort - implicit val typeInt : SInt.type = SInt - implicit val typeLong : SLong.type = SLong - implicit val typeBigInt : SBigInt.type = SBigInt - implicit val typeBoolean : SBoolean.type = SBoolean - implicit val typeAvlTree : SAvlTree.type = SAvlTree - implicit val typeGroupElement: SGroupElement.type = SGroupElement - implicit val typeSigmaProp : SSigmaProp.type = SSigmaProp - implicit val typeBox : SBox.type = SBox - - /** Costructs a collection type with the given type of elements. */ - implicit def typeCollection[V <: SType](implicit tV: V): SCollection[V] = SCollection[V](tV) - - /** 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: 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[BigInt] - 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 { +trait MethodByNameUnapply extends MethodsContainer { def unapply(methodName: String): Option[SMethod] = methods.find(_.name == methodName) } -/** Base trait for all types which have methods (and properties) */ -trait SProduct extends SType { +/** 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) @@ -362,432 +55,125 @@ trait SProduct extends SType { 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)` */ + * 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() + 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 lazy val _methodsMap: Map[Byte, Map[Byte, SMethod]] = methods + .groupBy(_.objType.typeId) + .map { case (typeId, ms) => (typeId -> ms.map(m => m.methodId -> m).toMap) } - /** 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) + /** 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 } - 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. + /** 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. * - * @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 + * @see getMethodById */ - 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))) + def methodById(methodId: Byte): SMethod = { + ValidationRules.CheckAndGetMethod(this, methodId) } - /** 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))) - } + /** Finds a method descriptor [[SMethod]] for the given name. */ + def method(methodName: String): Option[SMethod] = methods.find(_.name == methodName) - /** 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))) - } + /** Looks up the method descriptor by the method name. */ + def getMethodByName(name: String): SMethod = methods.find(_.name == name).get - /** 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. +object MethodsContainer { + private val containers = new SparseArrayContainer[MethodsContainer](Array( + SByteMethods, + SShortMethods, + SIntMethods, + SLongMethods, + SBigIntMethods, + SBooleanMethods, + SStringMethods, + SGroupElementMethods, + SSigmaPropMethods, + SBoxMethods, + SAvlTreeMethods, + SHeaderMethods, + SPreHeaderMethods, + SGlobalMethods, + SContextMethods, + SCollectionMethods, + SOptionMethods, + STupleMethods, + SUnitMethods, + SAnyMethods + ).map(m => (m.typeId, m))) + + def contains(typeId: TypeCode): Boolean = containers.contains(typeId) + + def apply(typeId: TypeCode): MethodsContainer = containers(typeId) + + /** Finds the method of the give type. * - * @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 + * @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 fromIds(typeId: Byte, methodId: Byte): SMethod = { - ValidationRules.CheckTypeWithMethods(typeId, SType.types.contains(typeId)) - val typeCompanion = SType.types(typeId) - val method = typeCompanion.methodById(methodId) - method + def getMethod(tpe: SType, methodName: String): Option[SMethod] = tpe match { + case tup: STuple => + STupleMethods.getTupleMethod(tup, methodName) + case _ => + containers.get(tpe.typeCode).flatMap(_.method(methodName)) } } -/** 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 +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, "") - /** Max possible number of primitive types. */ - final val PrimRange: Byte = (MaxPrimTypeCode + 1).toByte + /** 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, "") } -/** Marker trait for all numeric types. */ -trait SNumericType extends SProduct { - import SNumericType._ +trait SNumericTypeMethods extends MonoTypeMethods { + import SNumericTypeMethods.tNum protected override def getMethods(): Seq[SMethod] = { - super.getMethods() ++ SNumericType.methods.map { - m => m.copy(stype = Terms.applySubst(m.stype, Map(tNum -> this)).asFunc) + super.getMethods() ++ SNumericTypeMethods.methods.map { + m => m.copy(stype = Terms.applySubst(m.stype, Map(tNum -> this.ownerType)).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: 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.") +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") @@ -795,47 +181,53 @@ object SNumericType extends STypeCompanion { /** 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 = { + 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 + 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 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}") + .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]}. + .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 @@ -844,18 +236,18 @@ object SNumericType extends STypeCompanion { 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. + .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 + protected override def getMethods: Seq[SMethod] = Array( + ToByteMethod, // see Downcast + ToShortMethod, // see Downcast + ToIntMethod, // see Downcast + ToLongMethod, // see Downcast + ToBigIntMethod, // see Downcast ToBytesMethod, ToBitsMethod ) @@ -863,48 +255,28 @@ object SNumericType extends STypeCompanion { /** Collection of names of numeric casting methods (like `toByte`, `toInt`, etc). */ val castMethods: Array[String] = Array(ToByteMethod, ToShortMethod, ToIntMethod, ToLongMethod, ToBigIntMethod) - .map(_.name) + .map(_.name) - /** Checks the given name is numeric type cast method (like toByte, toInt, etc.).*/ + /** 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 { + 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 + 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]) +/** 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() @@ -916,140 +288,47 @@ case object SBoolean extends SPrimType with SEmbeddable with SLogical with SProd */ } -/** 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") - } +/** Methods of ErgoTree type `Byte`. */ +case object SByteMethods extends SNumericTypeMethods { + /** Type for which this container defines methods. */ + override def ownerType: SMonoType = SByte } -/** 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") - } +/** 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` - 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 `Int`. */ +case object SIntMethods extends SNumericTypeMethods { + /** Type for which this container defines methods. */ + override def ownerType: SMonoType = SInt } -/** 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 - case x: Short => x.toLong - case x: Int => x.toLong - case x: Long => x - case _ => sys.error(s"Cannot upcast value $v to the type $this") - } - override def downcast(v: AnyVal): Long = v match { - case b: Byte => b.toLong - case s: Short => s.toLong - case i: Int => i.toLong - case l: Long => l - case _ => sys.error(s"Cannot downcast value $v to the type $this") - } +/** Descriptor of ErgoTree type `Long`. */ +case object SLongMethods extends SNumericTypeMethods { + /** Type for which this container defines methods. */ + override def ownerType: SMonoType = SLong } -/** Type of 256 bit integet values. Implemented using [[java.math.BigInteger]]. */ -case object SBigInt extends SPrimType with SEmbeddable with SNumericType with SMonoType { - override type WrappedType = BigInt - override val typeCode: TypeCode = 6: Byte - override val reprClass: RClass[_] = RClass(classOf[BigInt]) - - override def typeId = typeCode - - /** Type of Relation binary op like GE, LE, etc. */ - val RelationOpType = SFunc(Array(SBigInt, SBigInt), SBoolean) - - /** The maximum size of BigInteger value in byte array representation. */ - val MaxSizeInBytes: Long = SigmaConstants.MaxBigIntSizeInBytes.value - - override def numericTypeIndex: Int = 4 - - override def upcast(v: AnyVal): BigInt = { - val bi = v match { - case x: Byte => BigInteger.valueOf(x.toLong) - case x: Short => BigInteger.valueOf(x.toLong) - case x: Int => BigInteger.valueOf(x.toLong) - case x: Long => BigInteger.valueOf(x) - case _ => sys.error(s"Cannot upcast value $v to the type $this") - } - SigmaDsl.BigInt(bi) - } - override def downcast(v: AnyVal): BigInt = { - val bi = v match { - case x: Byte => BigInteger.valueOf(x.toLong) - case x: Short => BigInteger.valueOf(x.toLong) - case x: Int => BigInteger.valueOf(x.toLong) - case x: Long => BigInteger.valueOf(x) - case _ => sys.error(s"Cannot downcast value $v to the type $this") - } - SigmaDsl.BigInt(bi) - } +/** 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 /** The following `modQ` methods are not fully implemented in v4.x and this descriptors. * This descritors are remain here in the code and are waiting for full implementation * is upcoming soft-forks at which point the cost parameters should be calculated and * changed. */ - val ModQMethod = SMethod(this, "modQ", SFunc(this, SBigInt), 1, FixedCost(JitCost(1))) + val ModQMethod = SMethod(this, "modQ", SFunc(this.ownerType, SBigInt), 1, FixedCost(JitCost(1))) .withInfo(ModQ, "Returns this \\lst{mod} Q, i.e. remainder of division by Q, where Q is an order of the cryprographic group.") - val PlusModQMethod = SMethod(this, "plusModQ", SFunc(IndexedSeq(this, SBigInt), SBigInt), 2, FixedCost(JitCost(1))) + val PlusModQMethod = SMethod(this, "plusModQ", SFunc(IndexedSeq(this.ownerType, SBigInt), SBigInt), 2, FixedCost(JitCost(1))) .withInfo(ModQArithOp.PlusModQ, "Adds this number with \\lst{other} by module Q.", ArgInfo("other", "Number to add to this.")) - val MinusModQMethod = SMethod(this, "minusModQ", SFunc(IndexedSeq(this, SBigInt), SBigInt), 3, FixedCost(JitCost(1))) + val MinusModQMethod = SMethod(this, "minusModQ", SFunc(IndexedSeq(this.ownerType, SBigInt), SBigInt), 3, FixedCost(JitCost(1))) .withInfo(ModQArithOp.MinusModQ, "Subtracts \\lst{other} number from this by module Q.", ArgInfo("other", "Number to subtract from this.")) - val MultModQMethod = SMethod(this, "multModQ", SFunc(IndexedSeq(this, SBigInt), SBigInt), 4, FixedCost(JitCost(1))) + val MultModQMethod = SMethod(this, "multModQ", SFunc(IndexedSeq(this.ownerType, SBigInt), SBigInt), 4, FixedCost(JitCost(1))) .withIRInfo(MethodCallIrBuilder) .withInfo(MethodCall, "Multiply this number with \\lst{other} by module Q.", ArgInfo("other", "Number to multiply with this.")) @@ -1062,35 +341,28 @@ case object SBigInt extends SPrimType with SEmbeddable with SNumericType with SM ) } -/** Descriptor of type `String` which is not used in ErgoTree, but used in ErgoScript. - * NOTE: this descriptor both type and type companion */ -case object SString extends SProduct with SMonoType { - override type WrappedType = String - override val typeCode: TypeCode = 102: Byte - override def typeId = typeCode - override def reprClass: RClass[_] = RClass(classOf[String]) +/** Methods of type `String`. */ +case object SStringMethods extends MonoTypeMethods { + /** Type for which this container defines methods. */ + override def ownerType: SMonoType = SString } -/** Descriptor of ErgoTree type `GroupElement`. - * NOTE: this descriptor both type and type companion */ -case object SGroupElement extends SProduct with SPrimType with SEmbeddable with SMonoType { - override type WrappedType = GroupElement - override val typeCode: TypeCode = 7: Byte - override val reprClass: RClass[_] = RClass(classOf[GroupElement]) - - override def typeId = typeCode +/** 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), SByteArray), 2, GetEncodedCostKind) + 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, SBigInt), this), 3, Exponentiate.costKind) + this, "exp", SFunc(Array(this.ownerType, SBigInt), this.ownerType), 3, Exponentiate.costKind) .withIRInfo({ case (builder, obj, _, Seq(arg), _) => builder.mkExponentiate(obj.asGroupElement, arg.asBigInt) }) @@ -1099,7 +371,7 @@ case object SGroupElement extends SProduct with SPrimType with SEmbeddable with ArgInfo("k", "The power")) lazy val MultiplyMethod: SMethod = SMethod( - this, "multiply", SFunc(Array(this, SGroupElement), this), 4, MultiplyGroup.costKind) + this, "multiply", SFunc(Array(this.ownerType, SGroupElement), this.ownerType), 4, MultiplyGroup.costKind) .withIRInfo({ case (builder, obj, _, Seq(arg), _) => builder.mkMultiplyGroup(obj.asGroupElement, arg.asGroupElement) }) @@ -1109,7 +381,7 @@ case object SGroupElement extends SProduct with SPrimType with SEmbeddable with val Negate_CostKind = FixedCost(JitCost(45)) lazy val NegateMethod: SMethod = SMethod( - this, "negate", SFunc(this, this), 5, Negate_CostKind) + this, "negate", SFunc(this.ownerType, this.ownerType), 5, Negate_CostKind) .withIRInfo(MethodCallIrBuilder) .withInfo(PropertyCall, "Inverse element of the group.") @@ -1125,13 +397,10 @@ case object SGroupElement extends SProduct with SPrimType with SEmbeddable with ) } -/** Descriptor of ErgoTree type `SigmaProp` which represent sigma-protocol propositions. */ -case object SSigmaProp extends SProduct with SPrimType with SEmbeddable with SLogical with SMonoType { - import SType._ - override type WrappedType = SigmaProp - override val typeCode: TypeCode = 8: Byte - override val reprClass: RClass[_] = RClass(classOf[SigmaProp]) - override def typeId = typeCode +/** 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 @@ -1139,10 +408,10 @@ case object SSigmaProp extends SProduct with SPrimType with SEmbeddable with SLo val PropBytes = "propBytes" val IsProven = "isProven" lazy val PropBytesMethod = SMethod( - this, PropBytes, SFunc(this, SByteArray), 1, SigmaPropBytes.costKind) + 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, SBoolean), 2, null) + 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.") @@ -1152,30 +421,20 @@ case object SSigmaProp extends SProduct with SPrimType with SEmbeddable with SLo } /** Any other type is implicitly subtype of this type. */ -case object SAny extends SPrimType { - override type WrappedType = Any - override val typeCode: TypeCode = 97: Byte +case object SAnyMethods extends MonoTypeMethods { + override def ownerType: SMonoType = SAny } /** The type with single inhabitant value `()` */ -case object SUnit extends SPrimType { - override type WrappedType = Unit - override val typeCode: TypeCode = 98: Byte +case object SUnitMethods extends MonoTypeMethods { + /** Type for which this container defines methods. */ + override def ownerType = SUnit } -/** Type description of optional values. Instances of `Option` - * are either constructed by `Some` or by `None` constructors. */ -case class SOption[ElemType <: SType](elemType: ElemType) extends SProduct with SGenericType { - import SOption._ - override type WrappedType = Option[ElemType#WrappedType] - override val typeCode: TypeCode = SOption.OptionTypeCode - protected override def getMethods() = super.getMethods() ++ SOption.methods - override def toString = s"Option[$elemType]" - override def toTermString: String = s"Option[${elemType.toTermString}]" - override lazy val typeParams: Seq[STypeParam] = Array(SType.paramT) -} +object SOptionMethods extends MethodsContainer { + /** Type for which this container defines methods. */ + override def ownerType: STypeCompanion = SOption -object SOption extends STypeCompanion { /** Code of `Option[_]` type constructor. */ val OptionTypeConstrId = 3 /** Type code for `Option[T] for some T` type used in TypeSerializer. */ @@ -1185,38 +444,11 @@ object SOption extends STypeCompanion { /** Type code for `Option[Coll[T]] for some T` type used in TypeSerializer. */ val OptionCollectionTypeCode: TypeCode = ((SPrimType.MaxPrimTypeCode + 1) * OptionCollectionTypeConstrId).toByte - override def typeId = OptionTypeCode - - override val reprClass: RClass[_] = RClass(classOf[Option[_]]) - - type SBooleanOption = SOption[SBoolean.type] - type SByteOption = SOption[SByte.type] - type SShortOption = SOption[SShort.type] - type SIntOption = SOption[SInt.type] - type SLongOption = SOption[SLong.type] - type SBigIntOption = SOption[SBigInt.type] - type SGroupElementOption = SOption[SGroupElement.type] - type SBoxOption = SOption[SBox.type] - type SAvlTreeOption = SOption[SAvlTree.type] - - /** This descriptors are instantiated once here and then reused. */ - implicit val SByteOption = SOption(SByte) - implicit val SByteArrayOption = SOption(SByteArray) - implicit val SShortOption = SOption(SShort) - implicit val SIntOption = SOption(SInt) - implicit val SLongOption = SOption(SLong) - implicit val SBigIntOption = SOption(SBigInt) - implicit val SBooleanOption = SOption(SBoolean) - implicit val SAvlTreeOption = SOption(SAvlTree) - implicit val SGroupElementOption = SOption(SGroupElement) - implicit val SSigmaPropOption = SOption(SSigmaProp) - implicit val SBoxOption = SOption(SBox) - val IsDefined = "isDefined" val Get = "get" val GetOrElse = "getOrElse" - import SType.{tT, tR, paramT, paramR} + import SType.{paramR, paramT, tR, tT} /** Type descriptor of `this` argument used in the methods below. */ val ThisType = SOption(tT) @@ -1276,56 +508,26 @@ object SOption extends STypeCompanion { | this option's value returns true. Otherwise, return \lst{None}. """.stripMargin, ArgInfo("p", "the predicate used for testing")) - val methods: Seq[SMethod] = Seq( - IsDefinedMethod, - GetMethod, - GetOrElseMethod, - /* TODO soft-fork: https://github.com/ScorexFoundation/sigmastate-interpreter/issues/479 - FoldMethod, - */ - MapMethod, - FilterMethod - ) - def apply[T <: SType](implicit elemType: T, ov: Overload1): SOption[T] = SOption(elemType) -} + 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 + ) -/** Base class for descriptors of `Coll[T]` ErgoTree type for some elemType T. */ -trait SCollection[T <: SType] extends SProduct with SGenericType { - def elemType: T - override type WrappedType = Coll[T#WrappedType] -} - -/** Descriptor of `Coll[T]` ErgoTree type for some elemType T. */ -case class SCollectionType[T <: SType](elemType: T) extends SCollection[T] { - override val typeCode: TypeCode = SCollectionType.CollectionTypeCode - override def typeParams: Seq[STypeParam] = SCollectionType.typeParams - protected override def getMethods() = super.getMethods() ++ SCollection.methods - override def toString = s"Coll[$elemType]" - override def toTermString = s"Coll[${elemType.toTermString}]" -} - -object SCollectionType { - /** Code of `Coll[_]` type constructor. */ - val CollectionTypeConstrId = 1 - - /** Type code for `Coll[T] for some T` type used in TypeSerializer. */ - val CollectionTypeCode: TypeCode = ((SPrimType.MaxPrimTypeCode + 1) * CollectionTypeConstrId).toByte - - /** Code of `Coll[Coll[_]]` type constructor. */ - val NestedCollectionTypeConstrId = 2 - - /** Type code for `Coll[Coll[T]] for some T` type used in TypeSerializer. */ - val NestedCollectionTypeCode: TypeCode = ((SPrimType.MaxPrimTypeCode + 1) * NestedCollectionTypeConstrId).toByte - - /** Array of generic type parameters reused in all SCollectionType instances. */ - val typeParams: Seq[STypeParam] = Array(SType.paramIV) + def apply[T <: SType](implicit elemType: T, ov: Overload1): SOption[T] = SOption(elemType) } -object SCollection extends STypeCompanion with MethodByNameUnapply { - override val reprClass: RClass[_] = RClass(classOf[Coll[_]]) - override def typeId = SCollectionType.CollectionTypeCode +object SCollectionMethods extends MethodsContainer with MethodByNameUnapply { + import SType.{paramIV, paramIVSeq, paramOV} - import SType.{tK, tV, 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 @@ -1724,224 +926,69 @@ object SCollection extends STypeCompanion with MethodByNameUnapply { } } - override lazy val methods: Seq[SMethod] = Seq( - SizeMethod, - GetOrElseMethod, - MapMethod, - ExistsMethod, - FoldMethod, - ForallMethod, - SliceMethod, - FilterMethod, - AppendMethod, - ApplyMethod, - IndicesMethod, - FlatMapMethod, - PatchMethod, - UpdatedMethod, - UpdateManyMethod, - IndexOfMethod, - ZipMethod - ) - - /** Helper constructors. */ - def apply[T <: SType](elemType: T): SCollection[T] = SCollectionType(elemType) - def apply[T <: SType](implicit elemType: T, ov: Overload1): SCollection[T] = SCollectionType(elemType) - - type SBooleanArray = SCollection[SBoolean.type] - type SByteArray = SCollection[SByte.type] - type SShortArray = SCollection[SShort.type] - type SIntArray = SCollection[SInt.type] - type SLongArray = SCollection[SLong.type] - type SBigIntArray = SCollection[SBigInt.type] - type SGroupElementArray = SCollection[SGroupElement.type] - type SBoxArray = SCollection[SBox.type] - type SAvlTreeArray = SCollection[SAvlTree.type] - - /** This descriptors are instantiated once here and then reused. */ - val SBooleanArray = SCollection(SBoolean) - val SByteArray = SCollection(SByte) - val SByteArray2 = SCollection(SCollection(SByte)) - val SShortArray = SCollection(SShort) - val SIntArray = SCollection(SInt) - val SLongArray = SCollection(SLong) - val SBigIntArray = SCollection(SBigInt) - val SGroupElementArray = SCollection(SGroupElement) - val SSigmaPropArray = SCollection(SSigmaProp) - val SBoxArray = SCollection(SBox) - val SAvlTreeArray = SCollection(SAvlTree) - val SHeaderArray = SCollection(SHeader) -} - -/** Type descriptor of tuple type. */ -case class STuple(items: IndexedSeq[SType]) extends SCollection[SAny.type] { - import STuple._ - override val typeCode = STuple.TupleTypeCode - - /** Lazily computed value representing true | false | none. - * 0 - none, 1 - false, 2 - true + /** This method should be overriden in derived classes to add new methods in addition to inherited. + * Typical override: `super.getMethods() ++ Seq(m1, m2, m3)` */ - @volatile - private var _isConstantSizeCode: Byte = 0.toByte - - override def elemType: SAny.type = SAny - - protected override def getMethods() = { - val tupleMethods = Array.tabulate(items.size) { i => - SMethod( - STuple, componentNameByIndex(i), SFunc(this, items(i)), - (i + 1).toByte, SelectField.costKind) - } - colMethods ++ tupleMethods - } - - override val typeParams = Nil - - override def toTermString = s"(${items.map(_.toTermString).mkString(",")})" - override def toString = s"(${items.mkString(",")})" + override protected def getMethods(): Seq[SMethod] = super.getMethods() ++ + Seq( + SizeMethod, + GetOrElseMethod, + MapMethod, + ExistsMethod, + FoldMethod, + ForallMethod, + SliceMethod, + FilterMethod, + AppendMethod, + ApplyMethod, + IndicesMethod, + FlatMapMethod, + PatchMethod, + UpdatedMethod, + UpdateManyMethod, + IndexOfMethod, + ZipMethod + ) } -object STuple extends STypeCompanion { - /** Code of `(_, T) for some embeddable T` type constructor. */ - val Pair1TypeConstrId = 5 - /** Type code for `(E, T) for some embeddable T` type used in TypeSerializer. */ - val Pair1TypeCode: TypeCode = ((SPrimType.MaxPrimTypeCode + 1) * Pair1TypeConstrId).toByte +object STupleMethods extends MethodsContainer { + /** Type for which this container defines methods. */ + override def ownerType: STypeCompanion = STuple - /** Code of `(T, _) for some embeddable T` type constructor. */ - val Pair2TypeConstrId = 6 - /** Type code for `(T, E) for some embeddable T` type used in TypeSerializer. */ - val Pair2TypeCode: TypeCode = ((SPrimType.MaxPrimTypeCode + 1) * Pair2TypeConstrId).toByte - val TripleTypeCode: TypeCode = Pair2TypeCode - - /** Type constructor code of symmetric pair `(T, T)` for some embeddable T. */ - val PairSymmetricTypeConstrId = 7 - /** Type code of symmetric pair `(T, T)` for some embeddable T. */ - val PairSymmetricTypeCode: TypeCode = ((SPrimType.MaxPrimTypeCode + 1) * PairSymmetricTypeConstrId).toByte - val QuadrupleTypeCode: TypeCode = PairSymmetricTypeCode - - /** Type code of generic tuple type. */ - val TupleTypeCode = ((SPrimType.MaxPrimTypeCode + 1) * 8).toByte - - override def typeId = TupleTypeCode + private val MaxTupleLength: Int = SigmaConstants.MaxTupleLength.value - override val reprClass: RClass[_] = RClass(classOf[Product2[_,_]]) + private val componentNames = Array.tabulate(MaxTupleLength) { i => s"_${i + 1}" } /** A list of Coll methods inherited from Coll type and available as method of tuple. */ lazy val colMethods: Seq[SMethod] = { val subst = Map(SType.tIV -> SAny) // TODO: implement other methods val activeMethods = Set(1.toByte /*Coll.size*/, 10.toByte /*Coll.apply*/) - SCollection.methods.filter(m => activeMethods.contains(m.methodId)).map { m => + SCollectionMethods.methods.filter(m => activeMethods.contains(m.methodId)).map { m => m.copy(stype = Terms.applySubst(m.stype, subst).asFunc) } } - override def methods: Seq[SMethod] = sys.error(s"Shouldn't be called.") - - /** Helper factory method. */ - def apply(items: SType*): STuple = STuple(items.toArray) - - private val MaxTupleLength: Int = SigmaConstants.MaxTupleLength.value - private val componentNames = Array.tabulate(MaxTupleLength){ i => s"_${i + 1}" } - - /** Returns method name for the tuple component accessor (i.e. `_1`, `_2`, etc.) */ - def componentNameByIndex(i: Int): String = - try componentNames(i) - catch { - case e: IndexOutOfBoundsException => - throw new IllegalArgumentException( - s"Tuple component '_${i+1}' is not defined: valid range (1 .. $MaxTupleLength)", e) + def getTupleMethod(tup: STuple, name: String): Option[SMethod] = { + colMethods.find(_.name == name).orElse { + val iComponent = componentNames.lastIndexOf(name, end = tup.items.length - 1) + if (iComponent == -1) None + else + Some(SMethod( + STupleMethods, name, SFunc(tup, tup.items(iComponent)), + (iComponent + 1).toByte, SelectField.costKind)) } -} - -/** Helper constuctor/extractor for tuples of two types. */ -object SPair { - def apply(l: SType, r: SType) = STuple(Array(l, r)) - def unapply(t: STuple): Nullable[(SType, SType)] = t match { - case STuple(IndexedSeq(l, r)) => Nullable((l, r)) - case _ => Nullable.None } -} -/** Type descriptor of lambda types. */ -case class SFunc(tDom: IndexedSeq[SType], tRange: SType, tpeParams: Seq[STypeParam] = Nil) - extends SType with SGenericType -{ - override type WrappedType = Any => tRange.WrappedType - override val typeCode = SFunc.FuncTypeCode - override def toString = { - val args = if (tpeParams.isEmpty) "" else tpeParams.mkString("[", ",", "]") - s"$args(${tDom.mkString(",")}) => $tRange" - } - override def toTermString = { - val args = if (tpeParams.isEmpty) "" else tpeParams.mkString("[", ",", "]") - s"$args(${tDom.map(_.toTermString).mkString(",")}) => ${tRange.toTermString}" - } - import SFunc._ - override val typeParams: Seq[STypeParam] = tpeParams - - /** Generalize this type and return a new descriptor. */ - def getGenericType: SFunc = { - val typeParams: Seq[STypeParam] = tDom.zipWithIndex - .map { case (_, i) => STypeParam(SType.tD.name + (i + 1)) } :+ STypeParam(SType.tR.name) - val ts = typeParams.map(_.ident) - SFunc(ts.init.toIndexedSeq, ts.last, Nil) - } - - /** Transform function into method type by adding the given `objType` as the first - * argument type (aka method receiver type). - */ - def withReceiverType(objType: SType) = this.copy(tDom = objType +: tDom) -} - -object SFunc { - final val FuncTypeCode: TypeCode = OpCodes.FirstFuncType - def apply(tDom: SType, tRange: SType): SFunc = SFunc(Array(tDom), tRange) // HOTSPOT: - val identity = { x: Any => x } -} - -/** Used by ErgoScript compiler IR and eliminated during compilation. - * It is not used in ErgoTree. - */ -case class STypeApply(name: String, args: IndexedSeq[SType] = IndexedSeq()) extends SType { - override type WrappedType = Any - override val typeCode = STypeApply.TypeCode -} -object STypeApply { - val TypeCode = 94: Byte -} - -/** Type variable which is used in generic method/func signatures. - * Used by ErgoScript compiler IR and eliminated during compilation. - * It is not used in ErgoTree. - */ -case class STypeVar(name: String) extends SType { - require(name.length <= 255, "name is too long") - override type WrappedType = Any - override val typeCode = STypeVar.TypeCode - override def toString = name - override def toTermString: String = name -} -object STypeVar { - val TypeCode: TypeCode = 103: Byte - implicit def liftString(n: String): STypeVar = STypeVar(n) - - /** Immutable empty array, can be used to avoid repeated allocations. */ - val EmptyArray = Array.empty[STypeVar] - - /** Immutable empty IndexedSeq, can be used to avoid repeated allocations. */ - val EmptySeq: IndexedSeq[STypeVar] = EmptyArray + override protected def getMethods(): Seq[SMethod] = super.getMethods() } /** Type descriptor of `Box` type of ErgoTree. */ -case object SBox extends SProduct with SPredefType with SMonoType { +case object SBoxMethods extends MonoTypeMethods { import ErgoBox._ - override type WrappedType = Box - override val typeCode: TypeCode = 99: Byte - override val reprClass: RClass[_] = RClass(classOf[Box]) - override def typeId = typeCode + import SType.{paramT, tT} - import SType.{tT, paramT} + override def ownerType: SMonoType = SBox /** Defined once here and then reused in SMethod descriptors. */ lazy val GetRegFuncType = SFunc(Array(SBox), SOption(tT), Array(paramT)) @@ -2032,19 +1079,17 @@ case object SBox extends SProduct with SPredefType with SMonoType { } /** Type descriptor of `AvlTree` type of ErgoTree. */ -case object SAvlTree extends SProduct with SPredefType with SMonoType { - override type WrappedType = AvlTree - override val typeCode: TypeCode = 100: Byte - override val reprClass: RClass[_] = RClass(classOf[AvlTree]) - override def typeId = typeCode - +case object SAvlTreeMethods extends MonoTypeMethods { import SOption._ + + override def ownerType: SMonoType = SAvlTree + lazy val TCollOptionCollByte = SCollection(SByteArrayOption) lazy val CollKeyValue = SCollection(STuple(SByteArray, SByteArray)) type KeyValueColl = Coll[(Coll[Byte], Coll[Byte])] - lazy val digestMethod = SMethod(this, "digest", SFunc(this, SByteArray), 1, FixedCost(JitCost(15))) + lazy val digestMethod = SMethod(this, "digest", SFunc(SAvlTree, SByteArray), 1, FixedCost(JitCost(15))) .withIRInfo(MethodCallIrBuilder) .withInfo(PropertyCall, """Returns digest of the state represented by this tree. @@ -2058,7 +1103,7 @@ case object SAvlTree extends SProduct with SPredefType with SMonoType { } lazy val enabledOperationsMethod = SMethod( - this, "enabledOperations", SFunc(this, SByte), 2, FixedCost(JitCost(15))) + this, "enabledOperations", SFunc(SAvlTree, SByte), 2, FixedCost(JitCost(15))) .withIRInfo(MethodCallIrBuilder) .withInfo(PropertyCall, """ Flags of enabled operations packed in single byte. @@ -2068,7 +1113,7 @@ case object SAvlTree extends SProduct with SPredefType with SMonoType { """.stripMargin) lazy val keyLengthMethod = SMethod( - this, "keyLength", SFunc(this, SInt), 3, FixedCost(JitCost(15))) + this, "keyLength", SFunc(SAvlTree, SInt), 3, FixedCost(JitCost(15))) .withIRInfo(MethodCallIrBuilder) .withInfo(PropertyCall, """ @@ -2076,7 +1121,7 @@ case object SAvlTree extends SProduct with SPredefType with SMonoType { """.stripMargin) lazy val valueLengthOptMethod = SMethod( - this, "valueLengthOpt", SFunc(this, SIntOption), 4, FixedCost(JitCost(15))) + this, "valueLengthOpt", SFunc(SAvlTree, SIntOption), 4, FixedCost(JitCost(15))) .withIRInfo(MethodCallIrBuilder) .withInfo(PropertyCall, """ @@ -2084,7 +1129,7 @@ case object SAvlTree extends SProduct with SPredefType with SMonoType { """.stripMargin) lazy val isInsertAllowedMethod = SMethod( - this, "isInsertAllowed", SFunc(this, SBoolean), 5, FixedCost(JitCost(15))) + this, "isInsertAllowed", SFunc(SAvlTree, SBoolean), 5, FixedCost(JitCost(15))) .withIRInfo(MethodCallIrBuilder) .withInfo(PropertyCall, """ @@ -2097,7 +1142,7 @@ case object SAvlTree extends SProduct with SPredefType with SMonoType { } lazy val isUpdateAllowedMethod = SMethod( - this, "isUpdateAllowed", SFunc(this, SBoolean), 6, FixedCost(JitCost(15))) + this, "isUpdateAllowed", SFunc(SAvlTree, SBoolean), 6, FixedCost(JitCost(15))) .withIRInfo(MethodCallIrBuilder) .withInfo(PropertyCall, """ @@ -2110,7 +1155,7 @@ case object SAvlTree extends SProduct with SPredefType with SMonoType { } lazy val isRemoveAllowedMethod = SMethod( - this, "isRemoveAllowed", SFunc(this, SBoolean), 7, FixedCost(JitCost(15))) + this, "isRemoveAllowed", SFunc(SAvlTree, SBoolean), 7, FixedCost(JitCost(15))) .withIRInfo(MethodCallIrBuilder) .withInfo(PropertyCall, """ @@ -2466,17 +1511,14 @@ case object SAvlTree extends SProduct with SPredefType with SMonoType { } /** Type descriptor of `Context` type of ErgoTree. */ -case object SContext extends SProduct with SPredefType with SMonoType { - override type WrappedType = Context - override val typeCode: TypeCode = 101: Byte - override def reprClass: RClass[_] = RClass(classOf[Context]) - override def typeId = typeCode +case object SContextMethods extends MonoTypeMethods { + override def ownerType: SMonoType = SContext /** Arguments on context operation such as getVar, DeserializeContext etc. * This value can be reused where necessary to avoid allocations. */ val ContextFuncDom: IndexedSeq[SType] = Array(SContext, SByte) - import SType.{tT, paramT} + import SType.{paramT, tT} lazy val dataInputsMethod = propertyCall("dataInputs", SBoxArray, 1, FixedCost(JitCost(15))) lazy val headersMethod = propertyCall("headers", SHeaderArray, 2, FixedCost(JitCost(15))) @@ -2500,11 +1542,8 @@ case object SContext extends SProduct with SPredefType with SMonoType { } /** Type descriptor of `Header` type of ErgoTree. */ -case object SHeader extends SProduct with SPredefType with SMonoType { - override type WrappedType = Header - override val typeCode: TypeCode = 104: Byte - override val reprClass: RClass[_] = RClass(classOf[Header]) - override def typeId = typeCode +case object SHeaderMethods extends MonoTypeMethods { + override def ownerType: SMonoType = SHeader lazy val idMethod = propertyCall("id", SByteArray, 1, FixedCost(JitCost(10))) lazy val versionMethod = propertyCall("version", SByte, 2, FixedCost(JitCost(10))) @@ -2530,11 +1569,8 @@ case object SHeader extends SProduct with SPredefType with SMonoType { } /** Type descriptor of `PreHeader` type of ErgoTree. */ -case object SPreHeader extends SProduct with SPredefType with SMonoType { - override type WrappedType = PreHeader - override val typeCode: TypeCode = 105: Byte - override val reprClass: RClass[_] = RClass(classOf[PreHeader]) - override def typeId = typeCode +case object SPreHeaderMethods extends MonoTypeMethods { + override def ownerType: SMonoType = SPreHeader lazy val versionMethod = propertyCall("version", SByte, 1, FixedCost(JitCost(10))) lazy val parentIdMethod = propertyCall("parentId", SByteArray, 2, FixedCost(JitCost(10))) @@ -2563,21 +1599,16 @@ case object SPreHeader extends SProduct with SPredefType with SMonoType { * * @see sigmastate.lang.SigmaPredef * */ -case object SGlobal extends SProduct with SPredefType with SMonoType { - override type WrappedType = SigmaDslBuilder - override val typeCode: TypeCode = 106: Byte - override val reprClass: RClass[_] = RClass(classOf[SigmaDslBuilder]) - override def typeId = typeCode - - import SType.tT +case object SGlobalMethods extends MonoTypeMethods { + override def ownerType: SMonoType = SGlobal lazy val groupGeneratorMethod = SMethod( - this, "groupGenerator", SFunc(this, SGroupElement), 1, GroupGenerator.costKind) + this, "groupGenerator", SFunc(SGlobal, SGroupElement), 1, GroupGenerator.costKind) .withIRInfo({ case (builder, obj, method, args, tparamSubst) => GroupGenerator }) .withInfo(GroupGenerator, "") lazy val xorMethod = SMethod( - this, "xor", SFunc(Array(this, SByteArray, SByteArray), SByteArray), 2, Xor.costKind) + this, "xor", SFunc(Array(SGlobal, SByteArray, SByteArray), SByteArray), 2, Xor.costKind) .withIRInfo({ case (_, _, _, Seq(l, r), _) => Xor(l.asByteArray, r.asByteArray) }) diff --git a/interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteReader.scala b/interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteReader.scala index 00f900c741..da2b442235 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteReader.scala +++ b/interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteReader.scala @@ -3,11 +3,11 @@ package sigmastate.utils import org.ergoplatform.validation.ValidationRules.CheckPositionLimit import scorex.util.Extensions._ import scorex.util.serialization.Reader -import sigmastate.SType import sigmastate.Values.{SValue, Value} import sigmastate.serialization._ import sigma.util.safeNewArray import debox.cfor +import sigma.ast.SType import sigmastate.exceptions.DeserializeCallDepthExceeded /** Reader used in the concrete implementations of [[SigmaSerializer]]. diff --git a/interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteWriter.scala b/interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteWriter.scala index 4c3ef03610..f30f1130bb 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteWriter.scala +++ b/interpreter/shared/src/main/scala/sigmastate/utils/SigmaByteWriter.scala @@ -2,9 +2,10 @@ package sigmastate.utils import scorex.util.serialization.{VLQByteBufferWriter, Writer} import scorex.util.serialization.Writer.Aux -import sigmastate.{ArgInfo, SType} -import sigmastate.Values.{Value, SValue} -import sigmastate.serialization.{TypeSerializer, ValueSerializer, ConstantStore} +import sigma.ast.SType +import sigmastate.ArgInfo +import sigmastate.Values.{SValue, Value} +import sigmastate.serialization.{ConstantStore, TypeSerializer, ValueSerializer} class SigmaByteWriter(val w: Writer, val constantExtractionStore: Option[ConstantStore]) extends Writer { diff --git a/interpreter/shared/src/main/scala/sigmastate/utils/SparseArrayContainer.scala b/interpreter/shared/src/main/scala/sigmastate/utils/SparseArrayContainer.scala index dad6437f5d..4d159f89a6 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utils/SparseArrayContainer.scala +++ b/interpreter/shared/src/main/scala/sigmastate/utils/SparseArrayContainer.scala @@ -1,6 +1,6 @@ package sigmastate.utils -import sigmastate.SType +import sigma.ast.SType import sigmastate.Values.Value import sigmastate.serialization.ValueSerializer @@ -20,15 +20,20 @@ class SparseArrayContainer[T: ClassTag](values: Seq[(Byte, T)]) { val dupGroups = sers.groupBy { case (b, _) => b }.filter { case (_, g) => g.size > 1 }.toList s"expected distinct codes, got duplicated: $dupGroups" }) - val array = Array.fill[T](256)(null.asInstanceOf[T]) // one item for each OpCode + val array = Array.fill[T](256)(null.asInstanceOf[T]) // one item for each code sers.foreach { case (code, value) => - array(codeToIndex(code)) = value + array(codeToIndex(code)) = value } array } @inline - private def codeToIndex(code: Byte): Int = code + 128 + private def codeToIndex(code: Byte): Int = code + 128 // -128..127 -> 0..255 + + /** @return true if value for the given code is defined + * @param code of a value + */ + @inline def contains(code: Byte): Boolean = sparseArray(codeToIndex(code)) != null /** * Returns value for the given code @@ -62,7 +67,7 @@ class SparseArrayContainer[T: ClassTag](values: Seq[(Byte, T)]) { } object SparseArrayContainer { - + /** Build a container for the given serializers. */ def buildForSerializers(sers: Seq[ValueSerializer[_ <: Value[SType]]]): SparseArrayContainer[ValueSerializer[_ <: Value[SType]]] = { new SparseArrayContainer(sers.map(s => (s.opCode, s))) } diff --git a/interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTable.scala b/interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTable.scala index 2613426257..dbda6eef4d 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTable.scala +++ b/interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTable.scala @@ -4,7 +4,7 @@ import org.ergoplatform._ import sigmastate._ import sigmastate.Values._ import sigmastate.lang.Terms._ -import sigmastate.serialization.OpCodes.OpCode +import sigmastate.serialization.ValueCodes.OpCode object ComplexityTable { diff --git a/interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTableStat.scala b/interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTableStat.scala index e595fa2b6a..ad3453a4c5 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTableStat.scala +++ b/interpreter/shared/src/main/scala/sigmastate/utxo/ComplexityTableStat.scala @@ -1,10 +1,10 @@ package sigmastate.utxo import sigmastate.serialization.ValueSerializer.getSerializer -import sigmastate.serialization.OpCodes.OpCode import sigma.util.Extensions.ByteOps import sigmastate.SMethod -import sigmastate.serialization.OpCodes +import sigmastate.serialization.{OpCodes, ValueCodes} +import sigmastate.serialization.ValueCodes.OpCode import scala.collection.mutable @@ -51,7 +51,7 @@ object ComplexityTableStat { val time = avgTime / 1000 val ser = getSerializer(opCode) val opName = ser.opDesc.typeName - (opName, (opCode.toUByte - OpCodes.LastConstantCode).toString, time, item.count.toString) + (opName, (opCode.toUByte - ValueCodes.LastConstantCode).toString, time, item.count.toString) }.toList.sortBy(_._3)(Ordering[Long].reverse) val mcLines = mcStat.map { case (id @ (typeId, methodId), item) => diff --git a/interpreter/shared/src/main/scala/sigmastate/utxo/transformers.scala b/interpreter/shared/src/main/scala/sigmastate/utxo/transformers.scala index 3d1ec92872..235272df63 100644 --- a/interpreter/shared/src/main/scala/sigmastate/utxo/transformers.scala +++ b/interpreter/shared/src/main/scala/sigmastate/utxo/transformers.scala @@ -1,20 +1,21 @@ package sigmastate.utxo -import sigmastate.SCollection.SByteArray import sigmastate.Values._ import sigmastate.lang.Terms._ import sigmastate._ -import sigmastate.serialization.OpCodes.OpCode import sigmastate.serialization.OpCodes import org.ergoplatform.ErgoBox.RegisterId +import sigma.ast.SCollection.SByteArray +import sigma.ast._ import sigma.data.RType import sigmastate.Operations._ -import sigmastate.eval.{Evaluation, SigmaDsl} +import sigmastate.eval.SigmaDsl import sigmastate.exceptions.InterpreterException import sigmastate.interpreter.ErgoTreeEvaluator import sigmastate.interpreter.ErgoTreeEvaluator.{DataEnv, error} -import sigma.Coll +import sigma.{Coll, Evaluation} import sigma.{Box, SigmaProp} +import sigmastate.serialization.ValueCodes.OpCode // TODO refactor: remove this trait as it doesn't have semantic meaning @@ -40,7 +41,7 @@ case class MapCollection[IV <: SType, OV <: SType]( extends Transformer[SCollection[IV], SCollection[OV]] { override def companion = MapCollection override val tpe = SCollection[OV](mapper.tpe.tRange.asInstanceOf[OV]) - override val opType = SCollection.MapMethod.stype.asFunc + override val opType = SCollectionMethods.MapMethod.stype.asFunc protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { val inputV = input.evalTo[Coll[Any]](env) val mapperV = mapper.evalTo[Any => Any](env) @@ -64,7 +65,7 @@ case class Append[IV <: SType](input: Value[SCollection[IV]], col2: Value[SColle extends Transformer[SCollection[IV], SCollection[IV]] { override def companion = Append override val tpe = input.tpe - override val opType = SCollection.AppendMethod.stype + override val opType = SCollectionMethods.AppendMethod.stype protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { val inputV = input.evalTo[Coll[IV#WrappedType]](env) val col2V = col2.evalTo[Coll[IV#WrappedType]](env) @@ -123,7 +124,7 @@ case class Filter[IV <: SType](input: Value[SCollection[IV]], extends Transformer[SCollection[IV], SCollection[IV]] { override def companion = Filter override def tpe: SCollection[IV] = input.tpe - override val opType = SCollection.FilterMethod.stype + override val opType = SCollectionMethods.FilterMethod.stype protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { val inputV = input.evalTo[Coll[Any]](env) val conditionV = condition.evalTo[Any => Boolean](env) @@ -160,7 +161,7 @@ case class Exists[IV <: SType](override val input: Value[SCollection[IV]], override val condition: Value[SFunc]) extends BooleanTransformer[IV] { override def companion = Exists - override val opType = SCollection.ExistsMethod.stype + override val opType = SCollectionMethods.ExistsMethod.stype protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { val inputV = input.evalTo[Coll[Any]](env) val conditionV = condition.evalTo[Any => Boolean](env) @@ -187,7 +188,7 @@ case class ForAll[IV <: SType](override val input: Value[SCollection[IV]], override val condition: Value[SFunc]) extends BooleanTransformer[IV] { override def companion = ForAll - override val opType = SCollection.ForallMethod.stype + override val opType = SCollectionMethods.ForallMethod.stype protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { val inputV = input.evalTo[Coll[Any]](env) val conditionV = condition.evalTo[Any => Boolean](env) @@ -224,7 +225,7 @@ case class Fold[IV <: SType, OV <: SType](input: Value[SCollection[IV]], extends Transformer[SCollection[IV], OV] { override def companion = Fold implicit override def tpe: OV = zero.tpe - val opType: SFunc = SCollection.FoldMethod.stype + val opType: SFunc = SCollectionMethods.FoldMethod.stype protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { val inputV = input.evalTo[Coll[IV#WrappedType]](env) val zeroV = zero.evalTo[OV#WrappedType](env) @@ -264,7 +265,7 @@ case class ByIndex[V <: SType](input: Value[SCollection[V]], extends Transformer[SCollection[V], V] with NotReadyValue[V] { override def companion = ByIndex override val tpe = input.tpe.elemType - override val opType = SCollection.ApplyMethod.stype.asFunc + override val opType = SCollectionMethods.ApplyMethod.stype.asFunc protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { val inputV = input.evalTo[Coll[V#WrappedType]](env) val indexV = index.evalTo[Int](env) @@ -551,7 +552,7 @@ trait Deserialize[V <: SType] extends NotReadyValue[V] */ case class DeserializeContext[V <: SType](id: Byte, tpe: V) extends Deserialize[V] { override def companion = DeserializeContext - override val opType = SFunc(SContext.ContextFuncDom, tpe) + override val opType = SFunc(SContextMethods.ContextFuncDom, tpe) } object DeserializeContext extends ValueCompanion { override def opCode: OpCode = OpCodes.DeserializeContextCode @@ -575,7 +576,7 @@ object DeserializeRegister extends ValueCompanion { /** See [[sigma.Context.getVar()]] for detailed description. */ case class GetVar[V <: SType](varId: Byte, override val tpe: SOption[V]) extends NotReadyValue[SOption[V]] { override def companion = GetVar - override val opType = SFunc(SContext.ContextFuncDom, tpe) + override val opType = SFunc(SContextMethods.ContextFuncDom, tpe) protected final override def eval(env: DataEnv)(implicit E: ErgoTreeEvaluator): Any = { val t = Evaluation.stypeToRType(tpe.elemType) addCost(GetVar.costKind) diff --git a/interpreter/shared/src/test/scala/sigmastate/CalcSha256Specification.scala b/interpreter/shared/src/test/scala/sigmastate/CalcSha256Specification.scala index 9fc8333784..db4312872d 100644 --- a/interpreter/shared/src/test/scala/sigmastate/CalcSha256Specification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/CalcSha256Specification.scala @@ -2,6 +2,7 @@ package sigmastate import org.scalatest.prop.TableFor2 import scorex.util.encode.Base16 +import sigma.ast.SByte import sigmastate.Values.{ByteArrayConstant, CollectionConstant} import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, TestingCommons} diff --git a/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingProverInterpreter.scala b/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingProverInterpreter.scala index f88d30ddcc..91155d96ca 100644 --- a/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingProverInterpreter.scala +++ b/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingProverInterpreter.scala @@ -1,6 +1,6 @@ package sigmastate.helpers -import sigmastate.SType +import sigma.ast.SType import sigmastate.Values.{ErgoTree, EvaluatedValue} import sigmastate.interpreter.Interpreter.ScriptEnv import sigmastate.interpreter.{ContextExtension, CostedProverResult, HintsBag, ProverInterpreter} diff --git a/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingTestProvingInterpreter.scala b/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingTestProvingInterpreter.scala index 641142f43c..3d9e7192d3 100644 --- a/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingTestProvingInterpreter.scala +++ b/interpreter/shared/src/test/scala/sigmastate/helpers/ContextEnrichingTestProvingInterpreter.scala @@ -1,7 +1,7 @@ package sigmastate.helpers import scorex.utils.Random -import sigmastate.SType +import sigma.ast.SType import sigmastate.Values._ import sigmastate.crypto.DLogProtocol.DLogProverInput import sigmastate.crypto.DiffieHellmanTupleProverInput diff --git a/interpreter/shared/src/test/scala/sigmastate/lang/SigmaBuilderTest.scala b/interpreter/shared/src/test/scala/sigmastate/lang/SigmaBuilderTest.scala index 657ded51ce..d850308c7b 100644 --- a/interpreter/shared/src/test/scala/sigmastate/lang/SigmaBuilderTest.scala +++ b/interpreter/shared/src/test/scala/sigmastate/lang/SigmaBuilderTest.scala @@ -12,6 +12,7 @@ import sigmastate.eval.{CAnyValue, CAvlTree, CostingBox, SigmaDsl} import sigmastate.exceptions.ConstraintFailed import sigmastate.serialization.OpCodes import sigma.SigmaTestingData +import sigma.ast._ import java.math.BigInteger diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala index bfa922ab69..9911583dc5 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala @@ -5,6 +5,7 @@ import sigmastate._ import sigmastate.eval.Extensions._ import sigmastate.serialization.OpCodes._ import scorex.util.encode.ZigZagEncoder.encodeZigZagInt +import sigma.ast.{SBoolean, SCollection, SCollectionType, SInt} class AndSerializerSpecification extends TableSerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/BlockSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/BlockSerializerSpecification.scala index c07081b816..54b03ba188 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/BlockSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/BlockSerializerSpecification.scala @@ -1,9 +1,9 @@ package sigmastate.serialization import org.scalacheck.Gen -import sigmastate.SType +import sigma.ast.SType import sigmastate.Values.Constant -import sigmastate.lang.{SigmaBuilder, DeserializationSigmaBuilder} +import sigmastate.lang.{DeserializationSigmaBuilder, SigmaBuilder} class BlockSerializerSpecification extends SerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/ConcreteCollectionSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/ConcreteCollectionSerializerSpecification.scala index a0812597e5..bb82ced30f 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/ConcreteCollectionSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/ConcreteCollectionSerializerSpecification.scala @@ -1,10 +1,10 @@ package sigmastate.serialization -import sigmastate.Values.{FalseLeaf, Constant, TrueLeaf, IntConstant, TaggedInt, ConcreteCollection} -import sigmastate._ -import sigmastate.eval.Evaluation +import sigma.Evaluation +import sigma.ast.SType +import sigmastate.Values.{ConcreteCollection, Constant, FalseLeaf, IntConstant, TaggedInt, TrueLeaf} import sigmastate.lang.Terms._ - +import sigma.ast._ import scala.util.Random class ConcreteCollectionSerializerSpecification extends TableSerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/ConstantSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/ConstantSerializerSpecification.scala index 04b016376a..8b67f7907a 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/ConstantSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/ConstantSerializerSpecification.scala @@ -3,18 +3,18 @@ package sigmastate.serialization import java.math.BigInteger import org.ergoplatform._ import org.scalacheck.Arbitrary._ -import sigma.data.RType -import sigmastate.SCollection.SByteArray +import sigma.data.{RType, TupleColl} +import sigma.ast.SCollection.SByteArray import sigmastate.Values.{BigIntConstant, ByteArrayConstant, Constant, FalseLeaf, GroupGenerator, LongConstant, SValue, TrueLeaf} import sigmastate.crypto.CryptoConstants.EcPointType import sigmastate._ import sigmastate.eval._ import sigmastate.eval.Extensions._ import sigmastate.Values._ -import sigmastate.eval.Evaluation -import sigma.{AvlTree, Colls} -import SType.AnyOps +import sigma.{AvlTree, Colls, Evaluation} +import sigma.ast.SType.AnyOps import scorex.util.encode.Base16 +import sigma.ast._ import sigmastate.exceptions.SerializerException import sigmastate.lang.DeserializationSigmaBuilder diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/ConstantStoreSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/ConstantStoreSpecification.scala index 70764b5e1f..563c535ac5 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/ConstantStoreSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/ConstantStoreSpecification.scala @@ -1,8 +1,9 @@ package sigmastate.serialization +import sigma.ast.SType import sigmastate.Values.{Constant, IntConstant} import sigmastate._ -import sigmastate.lang.{SigmaBuilder, DeserializationSigmaBuilder} +import sigmastate.lang.{DeserializationSigmaBuilder, SigmaBuilder} class ConstantStoreSpecification extends SerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/DataSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/DataSerializerSpecification.scala index c02df973dc..aa5b158472 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/DataSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/DataSerializerSpecification.scala @@ -3,22 +3,24 @@ package sigmastate.serialization import java.math.BigInteger import org.ergoplatform.ErgoBox import org.scalacheck.Arbitrary._ -import sigma.data.RType -import sigmastate.SCollection.SByteArray +import sigma.data.{RType, TupleColl} +import sigma.ast.SCollection.SByteArray import sigmastate.Values.{ErgoTree, SigmaBoolean} import sigmastate._ -import sigmastate.eval.Evaluation import sigmastate.eval._ import sigmastate.eval.Extensions._ import sigmastate.crypto.CryptoConstants.EcPointType -import sigma.{AvlTree, Colls} -import SType.AnyOps +import sigma.{AvlTree, Colls, Evaluation} +import sigma.ast.SType.AnyOps +import sigma.ast._ +import org.scalacheck.Gen import sigmastate.exceptions.SerializerException import sigmastate.interpreter.{CostAccumulator, ErgoTreeEvaluator} import sigmastate.interpreter.ErgoTreeEvaluator.DefaultProfiler import sigmastate.utils.Helpers import scala.annotation.nowarn +import scala.reflect.ClassTag class DataSerializerSpecification extends SerializationSpecification { @@ -76,9 +78,10 @@ class DataSerializerSpecification extends SerializationSpecification { } def testTuples[T <: SType](tpe: T) = { - implicit val wWrapped = wrappedTypeGen(tpe) - @nowarn implicit val tag = tpe.classTag[T#WrappedType] - implicit val tAny: RType[Any] = sigma.AnyType + implicit val wWrapped: Gen[T#WrappedType] = wrappedTypeGen(tpe) + val tT = Evaluation.stypeToRType(tpe) + @nowarn implicit val tag: ClassTag[T#WrappedType] = tT.classTag + implicit val tAny : RType[Any] = sigma.AnyType forAll { in: (T#WrappedType, T#WrappedType) => val (x,y) = (in._1, in._2) roundtrip[SType]((x, y).asWrappedType, STuple(tpe, tpe)) diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/MethodCallSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/MethodCallSerializerSpecification.scala index e84f2f64a4..a8cb79f2d6 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/MethodCallSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/MethodCallSerializerSpecification.scala @@ -1,6 +1,7 @@ package sigmastate.serialization import org.ergoplatform.Outputs +import sigma.ast.{SBox, SByte, SCollection} import sigmastate.Values.{FuncValue, ValUse} import sigmastate.lang.Terms.MethodCall import sigmastate.utxo.ExtractScriptBytes @@ -10,7 +11,7 @@ class MethodCallSerializerSpecification extends SerializationSpecification { property("MethodCall deserialization round trip") { val expr = MethodCall(Outputs, - SCollection.FlatMapMethod.withConcreteTypes(Map(SCollection.tIV -> SBox, SCollection.tOV -> SByte)), + SCollectionMethods.FlatMapMethod.withConcreteTypes(Map(SCollection.tIV -> SBox, SCollection.tOV -> SByte)), Vector(FuncValue(1, SBox, ExtractScriptBytes(ValUse(1, SBox)))), Map() ) @@ -19,7 +20,7 @@ class MethodCallSerializerSpecification extends SerializationSpecification { property("MethodCall deserialization round trip (non-generic method)") { val expr = MethodCall(Outputs, - SCollection.SizeMethod.withConcreteTypes(Map(SCollection.tIV -> SBox)), + SCollectionMethods.SizeMethod.withConcreteTypes(Map(SCollection.tIV -> SBox)), Vector(), Map() ) diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala index b7fbf54c66..38d13054e9 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala @@ -5,6 +5,7 @@ import sigmastate._ import sigmastate.eval.Extensions._ import sigmastate.serialization.OpCodes._ import scorex.util.encode.ZigZagEncoder.encodeZigZagInt +import sigma.ast.{SBoolean, SCollection, SCollectionType, SInt} class OrSerializerSpecification extends TableSerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/RelationsSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/RelationsSpecification.scala index fc9d18330f..7526cebd49 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/RelationsSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/RelationsSpecification.scala @@ -5,6 +5,7 @@ import sigmastate._ import sigmastate.serialization.OpCodes._ import sigmastate.serialization.ValueSerializer._ import scorex.util.encode.ZigZagEncoder.encodeZigZagLong +import sigma.ast.{SInt, SLong} class RelationsSpecification extends TableSerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/SerializationSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/SerializationSpecification.scala index 03b8801459..dc7457ed74 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/SerializationSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/SerializationSpecification.scala @@ -8,8 +8,8 @@ import org.scalacheck.Arbitrary._ import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.{ScalaCheckDrivenPropertyChecks, ScalaCheckPropertyChecks} +import sigma.ast.SType import sigmastate.Values._ -import sigmastate.SType import sigmastate.helpers.NegativeTesting import sigmastate.serialization.generators._ diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/SubstConstantsSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/SubstConstantsSerializerSpecification.scala index 0a6e73dac1..67de9b89a2 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/SubstConstantsSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/SubstConstantsSerializerSpecification.scala @@ -1,8 +1,9 @@ package sigmastate.serialization +import sigma.ast.SInt import sigmastate.Values.{ConcreteCollection, IntConstant, IntArrayConstant, IntValue} import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.{CrossVersionProps, SInt, EQ, SubstConstants} +import sigmastate.{CrossVersionProps, EQ, SubstConstants} class SubstConstantsSerializerSpecification extends SerializationSpecification with CrossVersionProps { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/TableSerializationSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/TableSerializationSpecification.scala index 543be44806..ef60e4a051 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/TableSerializationSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/TableSerializationSpecification.scala @@ -1,8 +1,8 @@ package sigmastate.serialization import org.scalatest.prop.TableFor2 +import sigma.ast.SType import sigmastate.Values._ -import sigmastate.SType trait TableSerializationSpecification extends SerializationSpecification { def objects: TableFor2[_ <: Value[_ <: SType], Array[Byte]] diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/TaggedVariableSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/TaggedVariableSerializerSpecification.scala index af0e04cf3b..f754157558 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/TaggedVariableSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/TaggedVariableSerializerSpecification.scala @@ -2,7 +2,7 @@ package sigmastate.serialization import sigmastate.Values._ import OpCodes._ -import sigmastate.SBox +import sigma.ast.SBox class TaggedVariableSerializerSpecification extends SerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/TransformersSerializationSpec.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/TransformersSerializationSpec.scala index 1239495bba..96738e78ac 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/TransformersSerializationSpec.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/TransformersSerializationSpec.scala @@ -1,5 +1,6 @@ package sigmastate.serialization +import sigma.ast.{SBoolean, SInt} import sigmastate._ import sigmastate.utxo._ diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/TwoArgumentSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/TwoArgumentSerializerSpecification.scala index 8d7a4dfa88..ed59095336 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/TwoArgumentSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/TwoArgumentSerializerSpecification.scala @@ -3,10 +3,11 @@ package sigmastate.serialization import sigmastate.Values.{BigIntConstant, ByteArrayConstant, GroupElementConstant, LongConstant} import sigmastate._ import sigmastate.Values._ -import sigmastate.serialization.OpCodes.OpCode import sigmastate.utxo.Append import OpCodes._ import scorex.util.encode.ZigZagEncoder.encodeZigZagLong +import sigma.ast.SLong +import sigmastate.serialization.ValueCodes.OpCode class TwoArgumentSerializerSpecification extends TableSerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/TypeSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/TypeSerializerSpecification.scala index 6521ec55f7..bcb045f687 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/TypeSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/TypeSerializerSpecification.scala @@ -2,7 +2,7 @@ package sigmastate.serialization import org.scalacheck.Arbitrary._ import org.scalatest.Assertion -import sigmastate._ +import sigma.ast._ class TypeSerializerSpecification extends SerializationSpecification { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/UpcastOnDeserializationSpecification.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/UpcastOnDeserializationSpecification.scala index de54b62295..17bce3e652 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/UpcastOnDeserializationSpecification.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/UpcastOnDeserializationSpecification.scala @@ -1,10 +1,11 @@ package sigmastate.serialization import org.ergoplatform.Outputs +import sigma.ast.{SInt, SLong} import sigmastate.Values.{ByteConstant, IntConstant, LongConstant} import sigmastate.lang.CheckingSigmaBuilder import sigmastate.utxo.ByIndex -import sigmastate.{SInt, SLong, Upcast} +import sigmastate.Upcast class UpcastOnDeserializationSpecification extends SerializationSpecification { import CheckingSigmaBuilder._ diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/ConcreteCollectionGenerators.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/generators/ConcreteCollectionGenerators.scala index 08ae08bd3f..c59e0c58f4 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/ConcreteCollectionGenerators.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/generators/ConcreteCollectionGenerators.scala @@ -1,8 +1,9 @@ package sigmastate.serialization.generators import org.scalacheck.{Arbitrary, Gen} +import sigma.ast.{SBoolean, SInt, SSigmaProp, SType} import sigmastate._ -import sigmastate.Values.{ConcreteCollection, Value, IntConstant} +import sigmastate.Values.{ConcreteCollection, IntConstant, Value} trait ConcreteCollectionGenerators { self: ObjectGenerators => val minCollLength = 1 diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala index 4c57f86246..5943e8913b 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala @@ -1,7 +1,7 @@ package sigmastate.serialization.generators import org.ergoplatform.ErgoBox._ -import org.ergoplatform.SigmaConstants.MaxPropositionBytes +import sigma.data.SigmaConstants.MaxPropositionBytes import org.ergoplatform.validation._ import org.ergoplatform._ import org.scalacheck.Arbitrary._ @@ -16,7 +16,7 @@ import sigmastate.Values._ import sigmastate.crypto.DLogProtocol.ProveDlog import sigmastate.crypto.{CryptoConstants, ProveDHTuple} import sigmastate.eval.Extensions._ -import sigmastate.eval.{CostingBox, SigmaDsl, _} +import sigmastate.eval._ import sigmastate.crypto.CryptoConstants.{EcPointType, dlogGroup} import sigmastate.interpreter.{ContextExtension, ProverResult} import sigmastate.lang.TransformingSigmaBuilder._ @@ -24,6 +24,7 @@ import sigmastate._ import sigmastate.utxo._ import sigma.Coll import sigma._ +import sigma.ast._ import java.math.BigInteger import scala.collection.compat.immutable.ArraySeq diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/OpcodesGen.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/generators/OpcodesGen.scala index f0b3ef092b..a11b80f5c8 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/OpcodesGen.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/generators/OpcodesGen.scala @@ -2,6 +2,7 @@ package sigmastate.serialization.generators import org.scalacheck.Gen import sigmastate.serialization.OpCodes._ +import sigmastate.serialization.ValueCodes.OpCode trait OpcodesGen { diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/RelationGenerators.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/generators/RelationGenerators.scala index fc7193a4f5..7c50a84c26 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/RelationGenerators.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/generators/RelationGenerators.scala @@ -1,8 +1,9 @@ package sigmastate.serialization.generators import org.scalacheck.{Arbitrary, Gen} +import sigma.ast.SInt import sigmastate.Values.{FalseLeaf, TrueLeaf} -import sigmastate.{If, SInt, TreeLookup} +import sigmastate.{If, TreeLookup} trait RelationGenerators { this: ObjectGenerators with ConcreteCollectionGenerators => diff --git a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala b/interpreter/shared/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala index 2582d1305c..d71de0b6b5 100644 --- a/interpreter/shared/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala +++ b/interpreter/shared/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala @@ -1,8 +1,8 @@ package sigmastate.serialization.generators -import org.scalacheck.{Gen, Arbitrary} +import org.scalacheck.{Arbitrary, Gen} import org.scalacheck.Arbitrary.arbString -import sigmastate._ +import sigma.ast._ trait TypeGenerators { implicit val booleanTypeGen: Gen[SBoolean.type] = Gen.const(SBoolean) diff --git a/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala b/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala index f5e695e32d..979634f36c 100644 --- a/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala +++ b/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala @@ -6,7 +6,7 @@ import org.scalacheck.Arbitrary.arbitrary import org.scalacheck.Gen.containerOfN import org.scalacheck.util.Buildable import org.scalacheck.{Arbitrary, Gen} -import sigma.data.RType +import sigma.data.{CBigInt, RType} import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.util.ModifierId @@ -16,13 +16,14 @@ import sigmastate.crypto.DLogProtocol.ProveDlog import sigmastate.crypto.ProveDHTuple import sigmastate.eval._ import sigmastate.eval.Extensions._ -import sigmastate.eval.{CAvlTree, CBigInt, CHeader, CPreHeader, CSigmaProp, CostingBox, CostingSigmaDslBuilder, SigmaDsl} +import sigmastate.eval.{CAvlTree, CHeader, CPreHeader, CSigmaProp, CostingBox, CostingSigmaDslBuilder, SigmaDsl} import sigmastate.helpers.TestingCommons import sigmastate.serialization.ErgoTreeSerializer import sigmastate.serialization.generators.ObjectGenerators import sigmastate.utils.Helpers import sigmastate._ import sigma.Coll +import sigma.ast.{SBoolean, SSigmaProp} import java.math.BigInteger import scala.reflect.ClassTag diff --git a/parsers/shared/src/main/scala/sigmastate/lang/SigmaParser.scala b/parsers/shared/src/main/scala/sigmastate/lang/SigmaParser.scala index 155e4ab879..7ad72ecb30 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/SigmaParser.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/SigmaParser.scala @@ -3,6 +3,7 @@ package sigmastate.lang import fastparse.internal.Logger import sigmastate._ import Values._ +import sigma.ast.{NoType, SInt, SLong, SType} import sigma.data.Nullable import sigmastate.lang.Terms._ import sigmastate.lang.syntax.Basic._ diff --git a/parsers/shared/src/main/scala/sigmastate/lang/Types.scala b/parsers/shared/src/main/scala/sigmastate/lang/Types.scala index e4869e4190..b3b3f48ce9 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/Types.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/Types.scala @@ -7,6 +7,7 @@ import Values._ import sigmastate.lang.Terms.Ident import sigmastate.lang.syntax.Core import syntax.Basic.error +import sigma.ast._ //noinspection ForwardReference /** Parsers of type terms. Can produce values of SType. */ diff --git a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Core.scala b/parsers/shared/src/main/scala/sigmastate/lang/syntax/Core.scala index 05f0952b20..83c5e76065 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Core.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/syntax/Core.scala @@ -1,5 +1,6 @@ package sigmastate.lang.syntax +import sigma.ast.{NoType, SType} import sigmastate._ import sigmastate.Values._ import sigmastate.lang.syntax diff --git a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Exprs.scala b/parsers/shared/src/main/scala/sigmastate/lang/syntax/Exprs.scala index f2b8c68b12..edca50650a 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Exprs.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/syntax/Exprs.scala @@ -2,9 +2,9 @@ package sigmastate.lang.syntax import fastparse._ import ScalaWhitespace._ -import sigmastate._ +import sigma.ast._ import sigmastate.Values._ -import sigmastate.lang.Terms.{Val, Ident, ValueOps} +import sigmastate.lang.Terms.{Ident, Val, ValueOps} import sigmastate.lang._ import sigmastate.lang.SigmaPredef._ import sigmastate.lang.syntax.Basic._ diff --git a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Literals.scala b/parsers/shared/src/main/scala/sigmastate/lang/syntax/Literals.scala index 007e4057b5..ad790d3599 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/syntax/Literals.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/syntax/Literals.scala @@ -1,12 +1,14 @@ package sigmastate.lang.syntax -import fastparse._; import NoWhitespace._ +import fastparse._ +import NoWhitespace._ import Identifiers._ import sigmastate._ import Values._ +import sigma.ast.{SBoolean, SInt, SLong, SString, SType} + import java.lang.Long.parseLong import java.lang.Integer.parseInt - import sigmastate.lang.{SigmaBuilder, SourceContext, StdSigmaBuilder} /** Parsers of literal expressions. */ diff --git a/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala b/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala index a1da3d0766..1c99f8a8f8 100644 --- a/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala +++ b/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala @@ -7,13 +7,14 @@ import sigmastate._ import java.math.BigInteger import sigmastate.crypto.DLogProtocol.ProveDlog -import sigmastate.SCollection.SByteArray -import sigmastate.crypto.{ProveDHTuple, CryptoConstants} +import sigma.ast.SCollection.SByteArray +import sigmastate.crypto.{CryptoConstants, ProveDHTuple} import sigmastate.interpreter.Interpreter.ScriptEnv import sigma._ import sigmastate.eval._ import sigmastate.helpers.NegativeTesting import sigma.Coll +import sigma.ast._ trait LangTests extends Matchers with NegativeTesting { diff --git a/parsers/shared/src/test/scala/sigmastate/lang/SigmaParserTest.scala b/parsers/shared/src/test/scala/sigmastate/lang/SigmaParserTest.scala index 42d02fefb5..a7854ed827 100644 --- a/parsers/shared/src/test/scala/sigmastate/lang/SigmaParserTest.scala +++ b/parsers/shared/src/test/scala/sigmastate/lang/SigmaParserTest.scala @@ -6,7 +6,8 @@ import org.ergoplatform.ErgoBox import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -import sigmastate.SCollection._ +import sigma.ast.SCollection.{SByteArray, SLongArray} +import sigma.ast._ import sigmastate.Values._ import sigmastate._ import sigmastate.lang.SigmaPredef.PredefinedFuncRegistry @@ -538,7 +539,7 @@ class SigmaParserTest extends AnyPropSpec with ScalaCheckPropertyChecks with Mat property("Box properties") { parse("{ (box: Box) => box.value }") shouldBe Lambda(IndexedSeq("box" -> SBox), NoType, Select(Ident("box"), "value")) - parse("{ (box: Box) => box.propositionBytes }") shouldBe Lambda(IndexedSeq("box" -> SBox), NoType, Select(Ident("box"), SBox.PropositionBytes)) + parse("{ (box: Box) => box.propositionBytes }") shouldBe Lambda(IndexedSeq("box" -> SBox), NoType, Select(Ident("box"), SBoxMethods.PropositionBytes)) parse("{ (box: Box) => box.bytes }") shouldBe Lambda(IndexedSeq("box" -> SBox), NoType, Select(Ident("box"), "bytes")) parse("{ (box: Box) => box.id }") shouldBe Lambda(IndexedSeq("box" -> SBox), NoType, Select(Ident("box"), "id")) } diff --git a/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala b/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala index d428a75294..a624589396 100644 --- a/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala +++ b/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala @@ -7,7 +7,7 @@ import org.scalablytyped.runtime.StringDictionary import scala.scalajs.js import scala.scalajs.js.annotation.JSExportTopLevel import org.ergoplatform.sdk.js.{ErgoTree, Value} -import sigmastate.Values +import sigmastate.{STypeOps, Values} import sigmastate.eval.CompiletimeIRContext import sigmastate.lang.Terms.ValueOps @@ -58,7 +58,7 @@ object SigmaCompiler extends js.Object { * @return SigmaCompiler instance */ private def create(networkPrefix: Byte): SigmaCompiler = { - val compiler = new sigmastate.lang.SigmaCompiler(networkPrefix) + val compiler = sigmastate.lang.SigmaCompiler(networkPrefix) new SigmaCompiler(compiler) } } diff --git a/sc/jvm/src/test/scala/sigmastate/ErgoTreeBenchmarks.scala b/sc/jvm/src/test/scala/sigmastate/ErgoTreeBenchmarks.scala index f5741dcb42..cacbf72a3e 100644 --- a/sc/jvm/src/test/scala/sigmastate/ErgoTreeBenchmarks.scala +++ b/sc/jvm/src/test/scala/sigmastate/ErgoTreeBenchmarks.scala @@ -3,6 +3,7 @@ package sigmastate import debox.cfor import org.scalameter.api.Bench import sigma.BenchmarkGens +import sigma.ast.SType import sigmastate.Values.{IntConstant, SValue} import sigmastate.serialization.OpCodes.PlusCode diff --git a/sc/jvm/src/test/scala/sigmastate/helpers/SigmaPPrintSpec.scala b/sc/jvm/src/test/scala/sigmastate/helpers/SigmaPPrintSpec.scala index 5a2c65d565..895b0fbe53 100644 --- a/sc/jvm/src/test/scala/sigmastate/helpers/SigmaPPrintSpec.scala +++ b/sc/jvm/src/test/scala/sigmastate/helpers/SigmaPPrintSpec.scala @@ -13,6 +13,7 @@ import sigmastate.serialization.OpCodes import sigmastate.utils.Helpers import sigmastate.utxo.SelectField import sigma.SigmaDslTesting +import sigma.ast._ import java.math.BigInteger import scala.collection.mutable.ArrayBuffer @@ -149,13 +150,13 @@ class SigmaPPrintSpec extends SigmaDslTesting { test( MethodCall.typed[Value[SCollection[SBox.type]]]( ValUse(1, SContext), - SContext.getMethodByName("dataInputs"), + SContextMethods.getMethodByName("dataInputs"), Vector(), Map() ), """MethodCall.typed[Value[SCollection[SBox.type]]]( | ValUse(1, SContext), - | SContext.getMethodByName("dataInputs"), + | SContextMethods.getMethodByName("dataInputs"), | Vector(), | Map() |)""".stripMargin) @@ -165,13 +166,13 @@ class SigmaPPrintSpec extends SigmaDslTesting { test( MethodCall.typed[Value[SCollection[SInt.type]]]( ValUse(1, SCollectionType(SBox)), - SCollection.IndicesMethod.withConcreteTypes(Map(SCollection.tIV -> SBox)), + SCollectionMethods.IndicesMethod.withConcreteTypes(Map(SCollection.tIV -> SBox)), Vector(), Map() ), """MethodCall.typed[Value[SCollection[SInt.type]]]( | ValUse(1, SCollectionType(SBox)), - | SCollection.getMethodByName("indices").withConcreteTypes(Map(STypeVar("IV") -> SBox)), + | SCollectionMethods.getMethodByName("indices").withConcreteTypes(Map(STypeVar("IV") -> SBox)), | Vector(), | Map() |)""".stripMargin) diff --git a/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala b/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala index b8c0db379a..9ce000448d 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala @@ -1,9 +1,9 @@ package org.ergoplatform -import sigmastate.SType import sigmastate.lang.SigmaCompiler import sigmastate.eval.IRContext import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix +import sigma.ast.SType import sigmastate.Values.{SigmaPropValue, Value} import sigmastate.lang.Terms.ValueOps @@ -12,7 +12,7 @@ object ErgoScriptPredef { /** Compiles the given ErgoScript `code` into ErgoTree expression. */ def compileWithCosting(env: ScriptEnv, code: String, networkPrefix: NetworkPrefix)(implicit IR: IRContext): Value[SType] = { - val compiler = new SigmaCompiler(networkPrefix) + val compiler = SigmaCompiler(networkPrefix) val res = compiler.compile(env, code) res.buildTree } diff --git a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala index de3012ff8f..10f702579c 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala @@ -1,13 +1,20 @@ package org.ergoplatform.dsl +import org.ergoplatform.ErgoBox import org.ergoplatform.ErgoBox.TokenId import sigma.data.RType -import sigmastate.SType -import sigmastate.SType.AnyOps import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition} -import sigmastate.eval.{CostingSigmaDslBuilder, Evaluation} +import org.ergoplatform.sdk.JavaHelpers.collRType +import sigmastate.eval.CostingSigmaDslBuilder import sigmastate.interpreter.Interpreter.ScriptEnv -import sigma.{SigmaProp, SigmaContract, Context, SigmaDslBuilder} +import sigma._ +import sigma.ast.SType +import sigma.ast.SType.AnyOps +import sigmastate.AvlTreeData +import sigmastate.Values.SigmaBoolean + +import scala.reflect.ClassTag +import scala.util.Try /** Defines methods to be used in contract implementations based on [[SigmaContract]]. */ trait ContractSyntax { contract: SigmaContract => @@ -29,6 +36,41 @@ trait ContractSyntax { contract: SigmaContract => /** Helper method to support Scala <-> ErgoScript equivalence. */ def Coll[T](items: T*)(implicit cT: RType[T]) = builder.Colls.fromItems(items:_*) + /** Tries to reconstruct RType of the given value. + * If not successfull returns failure. */ + def rtypeOf(value: Any): Try[RType[_]] = Try { + value match { + case arr if arr.getClass.isArray => + val itemClass = arr.getClass.getComponentType + if (itemClass.isPrimitive) { + val itemTag = ClassTag[Any](itemClass) + RType.fromClassTag(itemTag) + } else + sys.error(s"Cannot compute rtypeOf($value): non-primitive type of array items") + case coll: Coll[_] => collRType(coll.tItem) + + // all primitive types + case _: Boolean => BooleanType + case _: Byte => ByteType + case _: Short => ShortType + case _: Int => IntType + case _: Long => LongType + case _: String => StringType + case _: Unit => UnitType + case _: sigma.BigInt => BigIntRType + case _: GroupElement => GroupElementRType + case _: ErgoBox => sigmastate.ErgoBoxRType // TODO remove this RType + case _: Box => BoxRType + case _: AvlTreeData => sigmastate.AvlTreeDataRType // TODO remove this RType + case _: AvlTree => AvlTreeRType + case _: SigmaBoolean => sigmastate.SigmaBooleanRType // TODO remove this RType + case _: SigmaProp => SigmaPropRType + case _: Context => ContextRType + case _ => + sys.error(s"Don't know how to compute typeOf($value)") + } + } + /** Call this function in [[SigmaContract]] implementations to define propositions. * * @param name name of the proposition (aka contract name) @@ -44,7 +86,7 @@ trait ContractSyntax { contract: SigmaContract => scriptCode: String, scriptVersion: Option[Byte] = None): spec.PropositionSpec = { val env = contractEnv.map { case (k, v) => - val tV = Evaluation.rtypeOf(v).get + val tV = rtypeOf(v).get val elemTpe = Evaluation.rtypeToSType(tV) k -> spec.IR.builder.mkConstant[SType](v.asWrappedType, elemTpe) }.toMap diff --git a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala index 99467289f2..d323225b8d 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala @@ -11,9 +11,9 @@ import sigmastate.Values._ import sigmastate.interpreter.Interpreter.ScriptEnv import sigmastate.lang.{SourceContext, Terms} import sigmastate.lang.Terms.{Ident, Select, Val, ValueOps} -import sigmastate.serialization.OpCodes +import sigmastate.serialization.{OpCodes, ValueCodes} import sigmastate.utxo._ -import sigmastate._ +import sigma.ast._ import sigmastate.crypto.CryptoConstants.EcPointType import sigmastate.exceptions.{GraphBuildingException, SigmaException} @@ -298,7 +298,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => case _: BigIntElem[_] => SBigInt case _: GroupElementElem[_] => SGroupElement case _: AvlTreeElem[_] => SAvlTree - case oe: WOptionElem[_, _] => sigmastate.SOption(elemToSType(oe.eItem)) + case oe: WOptionElem[_, _] => SOption(elemToSType(oe.eItem)) case _: BoxElem[_] => SBox case _: ContextElem[_] => SContext case _: SigmaDslBuilderElem[_] => SGlobal @@ -390,7 +390,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => case OpCodes.LtCode => OrderingLT[A](elemToExactOrdering(eA)) case OpCodes.GeCode => OrderingGTEQ[A](elemToExactOrdering(eA)) case OpCodes.LeCode => OrderingLTEQ[A](elemToExactOrdering(eA)) - case _ => error(s"Cannot find BinOp for opcode newOpCode(${opCode.toUByte-OpCodes.LastConstantCode}) and type $eA") + case _ => error(s"Cannot find BinOp for opcode newOpCode(${opCode.toUByte - ValueCodes.LastConstantCode}) and type $eA") } import sigmastate._ @@ -510,11 +510,11 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => error(s"The type of $obj is expected to be Collection to select 'size' property", obj.sourceContext.toOption) // Rule: proof.isProven --> IsValid(proof) - case Select(p, SSigmaProp.IsProven, _) if p.tpe == SSigmaProp => + case Select(p, SSigmaPropMethods.IsProven, _) if p.tpe == SSigmaProp => eval(SigmaPropIsProven(p.asSigmaProp)) // Rule: prop.propBytes --> SigmaProofBytes(prop) - case Select(p, SSigmaProp.PropBytes, _) if p.tpe == SSigmaProp => + case Select(p, SSigmaPropMethods.PropBytes, _) if p.tpe == SSigmaProp => eval(SigmaPropBytes(p.asSigmaProp)) // box.R$i[valType] => @@ -525,12 +525,12 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => case sel @ Select(obj, field, _) if obj.tpe == SBox => (obj.asValue[SBox.type], field) match { - case (box, SBox.Value) => eval(mkExtractAmount(box)) - case (box, SBox.PropositionBytes) => eval(mkExtractScriptBytes(box)) - case (box, SBox.Id) => eval(mkExtractId(box)) - case (box, SBox.Bytes) => eval(mkExtractBytes(box)) - case (box, SBox.BytesWithoutRef) => eval(mkExtractBytesWithNoRef(box)) - case (box, SBox.CreationInfo) => eval(mkExtractCreationInfo(box)) + case (box, SBoxMethods.Value) => eval(mkExtractAmount(box)) + case (box, SBoxMethods.PropositionBytes) => eval(mkExtractScriptBytes(box)) + case (box, SBoxMethods.Id) => eval(mkExtractId(box)) + case (box, SBoxMethods.Bytes) => eval(mkExtractBytes(box)) + case (box, SBoxMethods.BytesWithoutRef) => eval(mkExtractBytesWithNoRef(box)) + case (box, SBoxMethods.CreationInfo) => eval(mkExtractCreationInfo(box)) case _ => error(s"Invalid access to Box property in $sel: field $field is not found", sel.sourceContext.toOption) } @@ -539,7 +539,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => eval(mkSelectField(tuple.asTuple, index)) case Select(obj, method, Some(tRes: SNumericType)) - if obj.tpe.isNumType && obj.asNumValue.tpe.isCastMethod(method) => + if obj.tpe.isNumType && SNumericTypeMethods.isCastMethod(method) => val numValue = obj.asNumValue if (numValue.tpe == tRes) eval(numValue) @@ -940,217 +940,217 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => val objV = eval(obj) val argsV = args.map(eval) (objV, method.objType) match { - case (xs: RColl[t]@unchecked, SCollection) => method.name match { - case SCollection.IndicesMethod.name => + case (xs: RColl[t]@unchecked, SCollectionMethods) => method.name match { + case SCollectionMethods.IndicesMethod.name => xs.indices - case SCollection.PatchMethod.name => + case SCollectionMethods.PatchMethod.name => val from = asRep[Int](argsV(0)) val patch = asRep[Coll[t]](argsV(1)) val replaced = asRep[Int](argsV(2)) xs.patch(from, patch, replaced) - case SCollection.UpdatedMethod.name => + case SCollectionMethods.UpdatedMethod.name => val index = asRep[Int](argsV(0)) val value = asRep[t](argsV(1)) xs.updated(index, value) - case SCollection.AppendMethod.name => + case SCollectionMethods.AppendMethod.name => val ys = asRep[Coll[t]](argsV(0)) xs.append(ys) - case SCollection.SliceMethod.name => + case SCollectionMethods.SliceMethod.name => val from = asRep[Int](argsV(0)) val until = asRep[Int](argsV(1)) xs.slice(from, until) - case SCollection.UpdateManyMethod.name => + case SCollectionMethods.UpdateManyMethod.name => val indexes = asRep[Coll[Int]](argsV(0)) val values = asRep[Coll[t]](argsV(1)) xs.updateMany(indexes, values) - case SCollection.IndexOfMethod.name => + case SCollectionMethods.IndexOfMethod.name => val elem = asRep[t](argsV(0)) val from = asRep[Int](argsV(1)) xs.indexOf(elem, from) - case SCollection.ZipMethod.name => + case SCollectionMethods.ZipMethod.name => val ys = asRep[Coll[Any]](argsV(0)) xs.zip(ys) - case SCollection.FlatMapMethod.name => + case SCollectionMethods.FlatMapMethod.name => val f = asRep[Any => Coll[Any]](argsV(0)) xs.flatMap(f) - case SCollection.MapMethod.name => + case SCollectionMethods.MapMethod.name => val f = asRep[Any => Any](argsV(0)) xs.map(f) - case SCollection.FilterMethod.name => + case SCollectionMethods.FilterMethod.name => val p = asRep[Any => Boolean](argsV(0)) xs.filter(p) - case SCollection.ForallMethod.name => + case SCollectionMethods.ForallMethod.name => val p = asRep[Any => Boolean](argsV(0)) xs.forall(p) - case SCollection.ExistsMethod.name => + case SCollectionMethods.ExistsMethod.name => val p = asRep[Any => Boolean](argsV(0)) xs.exists(p) - case SCollection.FoldMethod.name => + case SCollectionMethods.FoldMethod.name => val zero = asRep[Any](argsV(0)) val op = asRep[((Any, Any)) => Any](argsV(1)) xs.foldLeft(zero, op) - case SCollection.GetOrElseMethod.name => + case SCollectionMethods.GetOrElseMethod.name => val i = asRep[Int](argsV(0)) val d = asRep[t](argsV(1)) xs.getOrElse(i, d) case _ => throwError } - case (opt: ROption[t]@unchecked, SOption) => method.name match { - case SOption.GetMethod.name => + case (opt: ROption[t]@unchecked, SOptionMethods) => method.name match { + case SOptionMethods.GetMethod.name => opt.get - case SOption.GetOrElseMethod.name => + case SOptionMethods.GetOrElseMethod.name => val defaultTh = asRep[t](argsV(0)) opt.getOrElse(Thunk(defaultTh)) - case SOption.IsDefinedMethod.name => + case SOptionMethods.IsDefinedMethod.name => opt.isDefined - case SOption.MapMethod.name => + case SOptionMethods.MapMethod.name => opt.map(asRep[t => Any](argsV(0))) - case SOption.FilterMethod.name => + case SOptionMethods.FilterMethod.name => opt.filter(asRep[t => Boolean](argsV(0))) case _ => throwError } - case (ge: Ref[GroupElement]@unchecked, SGroupElement) => method.name match { - case SGroupElement.GetEncodedMethod.name => + case (ge: Ref[GroupElement]@unchecked, SGroupElementMethods) => method.name match { + case SGroupElementMethods.GetEncodedMethod.name => ge.getEncoded - case SGroupElement.NegateMethod.name => + case SGroupElementMethods.NegateMethod.name => ge.negate - case SGroupElement.MultiplyMethod.name => + case SGroupElementMethods.MultiplyMethod.name => val g2 = asRep[GroupElement](argsV(0)) ge.multiply(g2) - case SGroupElement.ExponentiateMethod.name => + case SGroupElementMethods.ExponentiateMethod.name => val k = asRep[BigInt](argsV(0)) ge.exp(k) case _ => throwError } - case (box: Ref[Box]@unchecked, SBox) => method.name match { - case SBox.tokensMethod.name => + case (box: Ref[Box]@unchecked, SBoxMethods) => method.name match { + case SBoxMethods.tokensMethod.name => box.tokens case _ => throwError } - case (ctx: Ref[Context]@unchecked, SContext) => method.name match { - case SContext.dataInputsMethod.name => + case (ctx: Ref[Context]@unchecked, SContextMethods) => method.name match { + case SContextMethods.dataInputsMethod.name => ctx.dataInputs - case SContext.headersMethod.name => + case SContextMethods.headersMethod.name => ctx.headers - case SContext.preHeaderMethod.name => + case SContextMethods.preHeaderMethod.name => ctx.preHeader - case SContext.inputsMethod.name => + case SContextMethods.inputsMethod.name => ctx.INPUTS - case SContext.outputsMethod.name => + case SContextMethods.outputsMethod.name => ctx.OUTPUTS - case SContext.heightMethod.name => + case SContextMethods.heightMethod.name => ctx.HEIGHT - case SContext.selfMethod.name => + case SContextMethods.selfMethod.name => ctx.SELF - case SContext.selfBoxIndexMethod.name => + case SContextMethods.selfBoxIndexMethod.name => ctx.selfBoxIndex - case SContext.lastBlockUtxoRootHashMethod.name => + case SContextMethods.lastBlockUtxoRootHashMethod.name => ctx.LastBlockUtxoRootHash - case SContext.minerPubKeyMethod.name => + case SContextMethods.minerPubKeyMethod.name => ctx.minerPubKey case _ => throwError } - case (tree: Ref[AvlTree]@unchecked, SAvlTree) => method.name match { - case SAvlTree.digestMethod.name => + case (tree: Ref[AvlTree]@unchecked, SAvlTreeMethods) => method.name match { + case SAvlTreeMethods.digestMethod.name => tree.digest - case SAvlTree.keyLengthMethod.name => + case SAvlTreeMethods.keyLengthMethod.name => tree.keyLength - case SAvlTree.valueLengthOptMethod.name => + case SAvlTreeMethods.valueLengthOptMethod.name => tree.valueLengthOpt - case SAvlTree.enabledOperationsMethod.name => + case SAvlTreeMethods.enabledOperationsMethod.name => tree.enabledOperations - case SAvlTree.isInsertAllowedMethod.name => + case SAvlTreeMethods.isInsertAllowedMethod.name => tree.isInsertAllowed - case SAvlTree.isRemoveAllowedMethod.name => + case SAvlTreeMethods.isRemoveAllowedMethod.name => tree.isRemoveAllowed - case SAvlTree.isUpdateAllowedMethod.name => + case SAvlTreeMethods.isUpdateAllowedMethod.name => tree.isUpdateAllowed - case SAvlTree.updateDigestMethod.name => + case SAvlTreeMethods.updateDigestMethod.name => val digest = asRep[Coll[Byte]](argsV(0)) tree.updateDigest(digest) - case SAvlTree.updateOperationsMethod.name => + case SAvlTreeMethods.updateOperationsMethod.name => val operations = asRep[Byte](argsV(0)) tree.updateOperations(operations) - case SAvlTree.getMethod.name => + case SAvlTreeMethods.getMethod.name => val key = asRep[Coll[Byte]](argsV(0)) val proof = asRep[Coll[Byte]](argsV(1)) tree.get(key, proof) - case SAvlTree.getManyMethod.name => + case SAvlTreeMethods.getManyMethod.name => val keys = asRep[Coll[Coll[Byte]]](argsV(0)) val proof = asRep[Coll[Byte]](argsV(1)) tree.getMany(keys, proof) - case SAvlTree.containsMethod.name => + case SAvlTreeMethods.containsMethod.name => val key = asRep[Coll[Byte]](argsV(0)) val proof = asRep[Coll[Byte]](argsV(1)) tree.contains(key, proof) - case SAvlTree.insertMethod.name => + case SAvlTreeMethods.insertMethod.name => val operations = asRep[Coll[(Coll[Byte], Coll[Byte])]](argsV(0)) val proof = asRep[Coll[Byte]](argsV(1)) tree.insert(operations, proof) - case SAvlTree.removeMethod.name => + case SAvlTreeMethods.removeMethod.name => val operations = asRep[Coll[Coll[Byte]]](argsV(0)) val proof = asRep[Coll[Byte]](argsV(1)) tree.remove(operations, proof) - case SAvlTree.updateMethod.name => + case SAvlTreeMethods.updateMethod.name => val operations = asRep[Coll[(Coll[Byte], Coll[Byte])]](argsV(0)) val proof = asRep[Coll[Byte]](argsV(1)) tree.update(operations, proof) case _ => throwError } - case (ph: Ref[PreHeader]@unchecked, SPreHeader) => method.name match { - case SPreHeader.versionMethod.name => + case (ph: Ref[PreHeader]@unchecked, SPreHeaderMethods) => method.name match { + case SPreHeaderMethods.versionMethod.name => ph.version - case SPreHeader.parentIdMethod.name => + case SPreHeaderMethods.parentIdMethod.name => ph.parentId - case SPreHeader.timestampMethod.name => + case SPreHeaderMethods.timestampMethod.name => ph.timestamp - case SPreHeader.nBitsMethod.name => + case SPreHeaderMethods.nBitsMethod.name => ph.nBits - case SPreHeader.heightMethod.name => + case SPreHeaderMethods.heightMethod.name => ph.height - case SPreHeader.minerPkMethod.name => + case SPreHeaderMethods.minerPkMethod.name => ph.minerPk - case SPreHeader.votesMethod.name => + case SPreHeaderMethods.votesMethod.name => ph.votes case _ => throwError } - case (h: Ref[Header]@unchecked, SHeader) => method.name match { - case SHeader.idMethod.name => + case (h: Ref[Header]@unchecked, SHeaderMethods) => method.name match { + case SHeaderMethods.idMethod.name => h.id - case SHeader.versionMethod.name => + case SHeaderMethods.versionMethod.name => h.version - case SHeader.parentIdMethod.name => + case SHeaderMethods.parentIdMethod.name => h.parentId - case SHeader.ADProofsRootMethod.name => + case SHeaderMethods.ADProofsRootMethod.name => h.ADProofsRoot - case SHeader.stateRootMethod.name => + case SHeaderMethods.stateRootMethod.name => h.stateRoot - case SHeader.transactionsRootMethod.name => + case SHeaderMethods.transactionsRootMethod.name => h.transactionsRoot - case SHeader.timestampMethod.name => + case SHeaderMethods.timestampMethod.name => h.timestamp - case SHeader.nBitsMethod.name => + case SHeaderMethods.nBitsMethod.name => h.nBits - case SHeader.heightMethod.name => + case SHeaderMethods.heightMethod.name => h.height - case SHeader.extensionRootMethod.name => + case SHeaderMethods.extensionRootMethod.name => h.extensionRoot - case SHeader.minerPkMethod.name => + case SHeaderMethods.minerPkMethod.name => h.minerPk - case SHeader.powOnetimePkMethod.name => + case SHeaderMethods.powOnetimePkMethod.name => h.powOnetimePk - case SHeader.powNonceMethod.name => + case SHeaderMethods.powNonceMethod.name => h.powNonce - case SHeader.powDistanceMethod.name => + case SHeaderMethods.powDistanceMethod.name => h.powDistance - case SHeader.votesMethod.name => + case SHeaderMethods.votesMethod.name => h.votes case _ => throwError } - case (g: Ref[SigmaDslBuilder]@unchecked, SGlobal) => method.name match { - case SGlobal.groupGeneratorMethod.name => + case (g: Ref[SigmaDslBuilder]@unchecked, SGlobalMethods) => method.name match { + case SGlobalMethods.groupGeneratorMethod.name => g.groupGenerator - case SGlobal.xorMethod.name => + case SGlobalMethods.xorMethod.name => val c1 = asRep[Coll[Byte]](argsV(0)) val c2 = asRep[Coll[Byte]](argsV(1)) g.xor(c1, c2) diff --git a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala index 13fc8c7bd1..657e73cc1e 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala @@ -7,12 +7,13 @@ import sigmastate._ import sigmastate.lang.Terms.ValueOps import sigmastate.serialization.OpCodes._ import sigmastate.serialization.ConstantStore - -import scala.collection.mutable.ArrayBuffer -import SType._ +import sigma.ast._ import sigmastate.crypto.DLogProtocol.ProveDlog import sigmastate.crypto.ProveDHTuple + +import scala.collection.mutable.ArrayBuffer import sigmastate.lang.Terms +import sigmastate.serialization.ValueCodes.OpCode /** Implementation of IR-graph to ErgoTree expression translation. * This, in a sense, is inverse to [[GraphBuilding]], however roundtrip identity is not @@ -273,12 +274,12 @@ trait TreeBuilding extends SigmaLibrary { IR: IRContext => val args = argsSyms.map(_.asInstanceOf[Sym]).map(recurse) val col = recurse(colSym).asCollection[SType] val colTpe = col.tpe - val method = SCollection.methods.find(_.name == m.getName).getOrElse(error(s"unknown method Coll.${m.getName}")) + val method = SCollectionMethods.methods.find(_.name == m.getName).getOrElse(error(s"unknown method Coll.${m.getName}")) val typeSubst = (method, args) match { - case (mth @ SCollection.FlatMapMethod, Seq(f)) => + case (mth @ SCollectionMethods.FlatMapMethod, Seq(f)) => val typeSubst = Map(SCollection.tOV -> f.asFunc.tpe.tRange.asCollection.elemType) typeSubst - case (mth @ SCollection.ZipMethod, Seq(coll)) => + case (mth @ SCollectionMethods.ZipMethod, Seq(coll)) => val typeSubst = Map(SCollection.tOV -> coll.asCollection[SType].tpe.elemType) typeSubst case (mth, _) => Terms.EmptySubst @@ -402,10 +403,13 @@ trait TreeBuilding extends SigmaLibrary { IR: IRContext => case Def(MethodCall(objSym, m, argSyms, _)) => val obj = recurse[SType](objSym) val args = argSyms.collect { case argSym: Sym => recurse[SType](argSym) } - val method = obj.tpe.asProduct.method(m.getName) - .getOrElse(error(s"Cannot find method ${m.getName} in object $obj")) - val specMethod = method.specializeFor(obj.tpe, args.map(_.tpe)) - builder.mkMethodCall(obj, specMethod, args.toIndexedSeq, Map()) + MethodsContainer.getMethod(obj.tpe, m.getName) match { + case Some(method) => + val specMethod = method.specializeFor(obj.tpe, args.map(_.tpe)) + builder.mkMethodCall(obj, specMethod, args.toIndexedSeq, Map()) + case None => + error(s"Cannot find method ${m.getName} in object $obj") + } case Def(d) => !!!(s"Don't know how to buildValue($mainG, $s -> $d, $env, $defId)") diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala index 3295429ffe..5d390f5f66 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala @@ -2,6 +2,7 @@ package sigmastate.lang import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix import org.ergoplatform._ +import sigma.ast.NoType import sigma.data.Nullable import sigma.kiama.rewriting.CallbackRewriter import sigmastate.Values._ diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala index d37a037a58..865d58df51 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala @@ -5,6 +5,7 @@ import fastparse.Parsed.Success import sigma.kiama.rewriting.Rewriter.{everywherebu, rewrite, rule} import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix import org.ergoplatform.Global +import scalan.GraphIRReflection import sigmastate.Values.{SValue, Value} import sigmastate.eval.IRContext import sigmastate.interpreter.Interpreter.ScriptEnv @@ -12,7 +13,9 @@ import sigmastate.lang.SigmaPredef.PredefinedFuncRegistry import sigmastate.lang.Terms.MethodCall import sigmastate.lang.syntax.ParserException import sigmastate.utxo._ -import sigmastate.{Exponentiate, MultiplyGroup, SCollection, SGlobal, SGroupElement, SType, STypeVar, Xor} +import sigma.ast._ +import sigmastate.SCollectionMethods.{ExistsMethod, ForallMethod, MapMethod} +import sigmastate.{Exponentiate, InterpreterReflection, MultiplyGroup, SCollectionMethods, SGlobalMethods, SGroupElementMethods, Xor} /** * @param networkPrefix network prefix to decode an ergo address from string (PK op) @@ -49,9 +52,9 @@ case class CompilerResult[Ctx <: IRContext]( /** Compiler which compiles ErgoScript source code into ErgoTree. * @param settings compilation parameters \ */ -class SigmaCompiler(settings: CompilerSettings) { +class SigmaCompiler private(settings: CompilerSettings) { /** Constructs an instance for the given network type and with default settings. */ - def this(networkPrefix: Byte) = this( + private def this(networkPrefix: Byte) = this( CompilerSettings(networkPrefix, TransformingSigmaBuilder, lowerMethodCalls = true) ) @@ -104,9 +107,9 @@ class SigmaCompiler(settings: CompilerSettings) { import SCollection._ val r = rule[Any]({ case MultiplyGroup(l, r) => - MethodCall(l, SGroupElement.MultiplyMethod, Vector(r), Map()) + MethodCall(l, SGroupElementMethods.MultiplyMethod, Vector(r), Map()) case Exponentiate(l, r) => - MethodCall(l, SGroupElement.ExponentiateMethod, Vector(r), Map()) + MethodCall(l, SGroupElementMethods.ExponentiateMethod, Vector(r), Map()) case ForAll(xs, p) => MethodCall(xs, ForallMethod.withConcreteTypes(Map(tIV -> xs.tpe.elemType)), Vector(p), Map()) case Exists(xs, p) => @@ -117,21 +120,21 @@ class SigmaCompiler(settings: CompilerSettings) { Vector(f), Map()) case Fold(xs, z, op) => MethodCall(xs, - SCollection.FoldMethod.withConcreteTypes(Map(tIV -> xs.tpe.elemType, tOV -> z.tpe)), + SCollectionMethods.FoldMethod.withConcreteTypes(Map(tIV -> xs.tpe.elemType, tOV -> z.tpe)), Vector(z, op), Map()) case Slice(xs, from, until) => MethodCall(xs, - SCollection.SliceMethod.withConcreteTypes(Map(tIV -> xs.tpe.elemType)), + SCollectionMethods.SliceMethod.withConcreteTypes(Map(tIV -> xs.tpe.elemType)), Vector(from, until), Map()) case Append(xs, ys) => MethodCall(xs, - SCollection.AppendMethod.withConcreteTypes(Map(tIV -> xs.tpe.elemType)), + SCollectionMethods.AppendMethod.withConcreteTypes(Map(tIV -> xs.tpe.elemType)), Vector(ys), Map()) case Xor(l, r) => - MethodCall(Global, SGlobal.xorMethod, Vector(l, r), Map()) + MethodCall(Global, SGlobalMethods.xorMethod, Vector(l, r), Map()) case ByIndex(xs, index, Some(default)) => MethodCall(xs, - SCollection.GetOrElseMethod.withConcreteTypes(Map(tIV -> xs.tpe.elemType)), + SCollectionMethods.GetOrElseMethod.withConcreteTypes(Map(tIV -> xs.tpe.elemType)), Vector(index, default), Map()) }) rewrite(everywherebu(r))(expr) @@ -139,6 +142,14 @@ class SigmaCompiler(settings: CompilerSettings) { } object SigmaCompiler { + /** Force initialization of reflection before any instance of SigmaCompiler is used. */ + val _ = (InterpreterReflection, GraphIRReflection) + + /** Constructs an instance for the given settings. */ def apply(settings: CompilerSettings): SigmaCompiler = new SigmaCompiler(settings) + + /** Constructs an instance for the given network type. */ + def apply(networkPrefix: Byte): SigmaCompiler = + new SigmaCompiler(networkPrefix) } diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala index beb17a98b0..2c9f5bd92d 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala @@ -1,10 +1,10 @@ package sigmastate.lang import org.ergoplatform._ -import sigmastate.SCollection._ +import sigma.ast.SCollection.{SBooleanArray, SByteArray} import sigmastate.Values._ import sigmastate._ -import SCollection.SBooleanArray +import sigma.ast._ import sigma.data.Nullable import sigma.util.Extensions.Ensuring import sigmastate.lang.Terms._ @@ -74,7 +74,7 @@ class SigmaTyper(val builder: SigmaBuilder, env.get(n) match { case Some(t) => mkIdent(n, t) case None => - SGlobal.method(n) match { + SGlobalMethods.method(n) match { case Some(method) if method.stype.tDom.length == 1 => // this is like `groupGenerator` without parentheses val srcCtx = i.sourceContext processGlobalMethod(srcCtx, method, IndexedSeq()) @@ -87,11 +87,10 @@ class SigmaTyper(val builder: SigmaBuilder, val newObj = assignType(env, obj) newObj.tpe match { case tNewObj: SProduct => - val iField = tNewObj.methodIndex(n) - val method = if (iField != -1) { - tNewObj.methods(iField) - } else - throw new MethodNotFound(s"Cannot find method '$n' in in the object $obj of Product type with methods ${tNewObj.methods}", obj.sourceContext.toOption) + val method = MethodsContainer.getMethod(tNewObj, n).getOrElse( + throw new MethodNotFound( + s"Cannot find method '$n' in in the object $obj of Product type with methods", + obj.sourceContext.toOption)) val tMeth = method.stype val tRes = tMeth match { case SFunc(args, _, _) => @@ -138,7 +137,7 @@ class SigmaTyper(val builder: SigmaBuilder, val newArgs = args.map(assignType(env, _)) obj.tpe match { case p: SProduct => - p.method(n) match { + MethodsContainer.getMethod(p, n) match { case Some(method @ SMethod(_, _, genFunTpe @ SFunc(_, _, _), _, _, _, _, _)) => val subst = Map(genFunTpe.tpeParams.head.ident -> rangeTpe) val concrFunTpe = applySubst(genFunTpe, subst) @@ -159,7 +158,7 @@ class SigmaTyper(val builder: SigmaBuilder, case Some(method) => error(s"Don't know how to handle method $method in obj $p", sel.sourceContext) case None => - throw new MethodNotFound(s"Cannot find method '$n' in in the object $obj of Product type with methods ${p.methods}", obj.sourceContext.toOption) + throw new MethodNotFound(s"Cannot find method '$n' in in the object $obj of Product type $p", obj.sourceContext.toOption) } case _ => error(s"Cannot get field '$n' in in the object $obj of non-product type ${obj.tpe}", sel.sourceContext) @@ -176,7 +175,7 @@ class SigmaTyper(val builder: SigmaBuilder, unifyTypeLists(argTypes, newArgTypes) match { case Some(subst) => val concrFunTpe = applySubst(genFunTpe, subst) - newObj.tpe.asInstanceOf[SProduct].method(n) match { + MethodsContainer.getMethod(newObj.tpe.asInstanceOf[SProduct], n) match { case Some(method) if method.irInfo.irBuilder.isDefined => val expectedArgs = concrFunTpe.asFunc.tDom if (expectedArgs.length != newArgTypes.length @@ -198,8 +197,8 @@ class SigmaTyper(val builder: SigmaBuilder, mkApply(newSel, newArgs.toArray[SValue]) } - case a @ Apply(ident: Ident, args) if SGlobal.hasMethod(ident.name) => // example: groupGenerator() - val method = SGlobal.method(ident.name).get + case a @ Apply(ident: Ident, args) if SGlobalMethods.hasMethod(ident.name) => // example: groupGenerator() + val method = SGlobalMethods.method(ident.name).get val srcCtx = a.sourceContext val newArgs = args.map(assignType(env, _)) processGlobalMethod(srcCtx, method, newArgs) @@ -280,7 +279,7 @@ class SigmaTyper(val builder: SigmaBuilder, mkAppend(newObj.asCollection[a], r.asCollection[a]) else error(s"Invalid argument type for $m, expected $tColl but was ${r.tpe}", r.sourceContext) - case (SCollection(method), _) => + case (SCollectionMethods(method), _) => val typeSubst = method.stype match { case sfunc @ SFunc(_, _, _) => val newArgsTypes = newArgs.map(_.tpe) @@ -335,7 +334,7 @@ class SigmaTyper(val builder: SigmaBuilder, case SSigmaProp => (m, newArgs) match { case ("||" | "&&" | "^", Seq(r)) => r.tpe match { case SBoolean => - val (a, b) = (Select(newObj, SSigmaProp.IsProven, Some(SBoolean)).asBoolValue, r.asBoolValue) + val (a, b) = (Select(newObj, SSigmaPropMethods.IsProven, Some(SBoolean)).asBoolValue, r.asBoolValue) val res = m match { case "||" => mkBinOr(a, b) case "&&" => mkBinAnd(a, b) @@ -364,7 +363,7 @@ class SigmaTyper(val builder: SigmaBuilder, case "^" => mkBinXor(newObj.asBoolValue, r.asBoolValue) } case SSigmaProp => - val (a, b) = (newObj.asBoolValue, Select(r, SSigmaProp.IsProven, Some(SBoolean)).asBoolValue) + val (a, b) = (newObj.asBoolValue, Select(r, SSigmaPropMethods.IsProven, Some(SBoolean)).asBoolValue) val res = m match { case "||" => mkBinOr(a, b) case "&&" => mkBinAnd(a, b) diff --git a/sc/shared/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala b/sc/shared/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala index 73156ca1b8..f667753389 100644 --- a/sc/shared/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala +++ b/sc/shared/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala @@ -20,9 +20,9 @@ import sigmastate.lang.Terms.ValueOps import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer import sigmastate.serialization.{GroupElementSerializer, ValueSerializer} import sigmastate.utils.Helpers._ -import sigmastate.{CompilerCrossVersionProps, SType, SigmaAnd} +import sigmastate.{CompilerCrossVersionProps, SigmaAnd} import sigma.SigmaDslTesting - +import sigma.ast.SType import java.math.BigInteger class ErgoAddressSpecification extends SigmaDslTesting diff --git a/sc/shared/src/test/scala/org/ergoplatform/ErgoLikeTransactionSpec.scala b/sc/shared/src/test/scala/org/ergoplatform/ErgoLikeTransactionSpec.scala index b8579ddedf..7f66d3f7d6 100644 --- a/sc/shared/src/test/scala/org/ergoplatform/ErgoLikeTransactionSpec.scala +++ b/sc/shared/src/test/scala/org/ergoplatform/ErgoLikeTransactionSpec.scala @@ -4,15 +4,15 @@ import org.ergoplatform.ErgoBox.TokenId import org.ergoplatform.settings.ErgoAlgos import scorex.util.encode.Base16 import scorex.util.{Random, ModifierId} -import sigmastate.SCollection.SByteArray -import sigmastate.{SSigmaProp, TrivialProp, SType, SPair, SInt} +import sigma.ast.SCollection.SByteArray +import sigma.ast.{SSigmaProp, SType, SPair, SInt} import sigmastate.Values._ import sigmastate.interpreter.{ContextExtension, ProverResult} import sigmastate.serialization.SigmaSerializer import sigmastate.eval._ import sigmastate.eval.Extensions._ -import sigmastate._ -import sigmastate.SType._ +import sigmastate.{TrivialProp, _} +import sigma.ast.SType._ import sigmastate.helpers.TestingHelpers.copyTransaction import sigmastate.utils.Helpers import sigma.SigmaDslTesting diff --git a/sc/shared/src/test/scala/org/ergoplatform/ErgoTreePredefSpec.scala b/sc/shared/src/test/scala/org/ergoplatform/ErgoTreePredefSpec.scala index d017b6ca35..33a0eb1d89 100644 --- a/sc/shared/src/test/scala/org/ergoplatform/ErgoTreePredefSpec.scala +++ b/sc/shared/src/test/scala/org/ergoplatform/ErgoTreePredefSpec.scala @@ -8,6 +8,7 @@ import org.scalacheck.Gen import scorex.crypto.hash.Blake2b256 import scorex.util.Random import sigma.Colls +import sigma.ast.SByte import sigma.util.BenchmarkUtil.measure import sigmastate.Values.{ByteArrayConstant, CollectionConstant, ErgoTree, IntConstant, SigmaPropConstant} import sigmastate._ diff --git a/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala b/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala index 46668c3b1a..5a17f01448 100644 --- a/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala +++ b/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala @@ -12,13 +12,14 @@ import sigma.data.Nullable import scala.util.Try import org.ergoplatform.{ErgoBox, ErgoLikeContext} import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition, Token} -import sigmastate.{AvlTreeData, SType} +import sigma.ast.SType +import sigmastate.AvlTreeData import sigmastate.Values.{ErgoTree, EvaluatedValue} -import sigmastate.eval.{CSigmaProp, Evaluation, IRContext, CAnyValue} +import sigmastate.eval.{CSigmaProp, IRContext, CAnyValue} import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, CompilerTestingCommons} import sigmastate.helpers.TestingHelpers._ import sigmastate.lang.Terms.ValueOps -import sigma.{AnyValue, SigmaProp} +import sigma.{AnyValue, Evaluation, SigmaProp} case class TestContractSpec(testSuite: CompilerTestingCommons)(implicit val IR: IRContext) extends ContractSpec { diff --git a/sc/shared/src/test/scala/sigma/SigmaDslSpecification.scala b/sc/shared/src/test/scala/sigma/SigmaDslSpecification.scala index f5c47a055f..af14fca2a9 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslSpecification.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslSpecification.scala @@ -4,13 +4,13 @@ import java.math.BigInteger import org.ergoplatform._ import org.ergoplatform.settings.ErgoAlgos import org.scalacheck.{Arbitrary, Gen} -import sigma.data.{ExactIntegral, ExactNumeric, ExactOrdering, RType} +import sigma.data.{CBigInt, ExactIntegral, ExactNumeric, ExactOrdering, RType} import scorex.crypto.authds.avltree.batch._ import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash.{Blake2b256, Digest32} import sigma.util.Extensions._ import sigmastate.utils.Extensions._ -import sigmastate.SCollection._ +import sigma.ast.SCollection._ import sigmastate.Values.IntConstant import sigmastate._ import sigmastate.crypto.DLogProtocol._ @@ -22,7 +22,6 @@ import sigmastate.lang.Terms.{MethodCall, PropertyCall} import sigmastate.utxo._ import sigma._ import sigma.Extensions._ -import sigmastate.serialization.OpCodes.OpCode import sigmastate.utils.Helpers import sigmastate.utils.Helpers._ import sigmastate.helpers.TestingHelpers._ @@ -39,8 +38,10 @@ import sigmastate.crypto.ProveDHTuple import sigmastate.interpreter._ import org.scalactic.source.Position import sigma.VersionContext +import sigma.ast._ import sigmastate.helpers.SigmaPPrint import sigmastate.exceptions.GraphBuildingException +import sigmastate.serialization.ValueCodes.OpCode import scala.collection.compat.immutable.ArraySeq @@ -2695,7 +2696,7 @@ class SigmaDslSpecification extends SigmaDslTesting property("GroupElement.getEncoded equivalence") { verifyCases( { - def success[T](v: T) = Expected(Success(v), 1790, methodCostDetails(SGroupElement.GetEncodedMethod, 250), 1790) + def success[T](v: T) = Expected(Success(v), 1790, methodCostDetails(SGroupElementMethods.GetEncodedMethod, 250), 1790) Seq( (ge1, success(Helpers.decodeBytes(ge1str))), (ge2, success(Helpers.decodeBytes(ge2str))), @@ -2710,7 +2711,7 @@ class SigmaDslSpecification extends SigmaDslTesting "{ (x: GroupElement) => x.getEncoded }", FuncValue( Vector((1, SGroupElement)), - MethodCall(ValUse(1, SGroupElement), SGroupElement.getMethodByName("getEncoded"), Vector(), Map()) + MethodCall(ValUse(1, SGroupElement), SGroupElementMethods.getMethodByName("getEncoded"), Vector(), Map()) ))) } @@ -2720,7 +2721,7 @@ class SigmaDslSpecification extends SigmaDslTesting val costDetails = TracedCost( traceBase ++ Array( FixedCostItem(PropertyCall), - FixedCostItem(MethodDesc(SGroupElement.GetEncodedMethod), FixedCost(JitCost(250))), + FixedCostItem(MethodDesc(SGroupElementMethods.GetEncodedMethod), FixedCost(JitCost(250))), FixedCostItem(DecodePoint), FixedCostItem(ValUse), FixedCostItem(NamedDesc("EQ_GroupElement"), FixedCost(JitCost(172))) @@ -2743,7 +2744,7 @@ class SigmaDslSpecification extends SigmaDslTesting DecodePoint( MethodCall.typed[Value[SCollection[SByte.type]]]( ValUse(1, SGroupElement), - SGroupElement.getMethodByName("getEncoded"), + SGroupElementMethods.getMethodByName("getEncoded"), Vector(), Map() ) @@ -2756,7 +2757,7 @@ class SigmaDslSpecification extends SigmaDslTesting property("GroupElement.negate equivalence") { verifyCases( { - def success[T](v: T) = Expected(Success(v), 1785, methodCostDetails(SGroupElement.NegateMethod, 45), 1785) + def success[T](v: T) = Expected(Success(v), 1785, methodCostDetails(SGroupElementMethods.NegateMethod, 45), 1785) Seq( (ge1, success(Helpers.decodeGroupElement("02358d53f01276211f92d0aefbd278805121d4ff6eb534b777af1ee8abae5b2056"))), (ge2, success(Helpers.decodeGroupElement("03dba7b94b111f3894e2f9120b577da595ec7d58d488485adf73bf4e153af63575"))), @@ -2769,7 +2770,7 @@ class SigmaDslSpecification extends SigmaDslTesting "{ (x: GroupElement) => x.negate }", FuncValue( Vector((1, SGroupElement)), - MethodCall(ValUse(1, SGroupElement), SGroupElement.getMethodByName("negate"), Vector(), Map()) + MethodCall(ValUse(1, SGroupElement), SGroupElementMethods.getMethodByName("negate"), Vector(), Map()) ))) } @@ -2822,7 +2823,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(MethodCall), FixedCostItem(ValUse), FixedCostItem(SelectField), - FixedCostItem(SGroupElement.ExponentiateMethod, FixedCost(JitCost(900))) + FixedCostItem(SGroupElementMethods.ExponentiateMethod, FixedCost(JitCost(900))) ) ) verifyCases(cases(1873, costDetails), @@ -2836,7 +2837,7 @@ class SigmaDslSpecification extends SigmaDslTesting ValUse(1, STuple(Vector(SGroupElement, SBigInt))), 1.toByte ), - SGroupElement.getMethodByName("exp"), + SGroupElementMethods.getMethodByName("exp"), Vector( SelectField.typed[Value[SBigInt.type]]( ValUse(1, STuple(Vector(SGroupElement, SBigInt))), @@ -2868,7 +2869,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(MethodCall), FixedCostItem(ValUse), FixedCostItem(SelectField), - FixedCostItem(SGroupElement.MultiplyMethod, FixedCost(JitCost(40))) + FixedCostItem(SGroupElementMethods.MultiplyMethod, FixedCost(JitCost(40))) ) ) ) @@ -2908,7 +2909,7 @@ class SigmaDslSpecification extends SigmaDslTesting ValUse(1, SPair(SGroupElement, SGroupElement)), 1.toByte ), - SGroupElement.getMethodByName("multiply"), + SGroupElementMethods.getMethodByName("multiply"), Vector( SelectField.typed[Value[SGroupElement.type]]( ValUse(1, SPair(SGroupElement, SGroupElement)), @@ -2927,7 +2928,7 @@ class SigmaDslSpecification extends SigmaDslTesting Vector((1, SAvlTree)), MethodCall( ValUse(1, SAvlTree), - SAvlTree.getMethodByName(propName), + SAvlTreeMethods.getMethodByName(propName), Vector(), Map() ) @@ -2935,7 +2936,7 @@ class SigmaDslSpecification extends SigmaDslTesting } verifyCases( { - def success[T](v: T) = Expected(Success(v), 1767, methodCostDetails(SAvlTree.digestMethod, 15), 1767) + def success[T](v: T) = Expected(Success(v), 1767, methodCostDetails(SAvlTreeMethods.digestMethod, 15), 1767) Seq( (t1, success(Helpers.decodeBytes("000183807f66b301530120ff7fc6bd6601ff01ff7f7d2bedbbffff00187fe89094"))), (t2, success(Helpers.decodeBytes("ff000d937f80ffd731ed802d24358001ff8080ff71007f00ad37e0a7ae43fff95b"))), @@ -2948,7 +2949,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyCases( { - def success[T](v: T) = Expected(Success(v), 1765, methodCostDetails(SAvlTree.enabledOperationsMethod, 15), 1765) + def success[T](v: T) = Expected(Success(v), 1765, methodCostDetails(SAvlTreeMethods.enabledOperationsMethod, 15), 1765) Seq( (t1, success(6.toByte)), (t2, success(0.toByte)), @@ -2961,7 +2962,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyCases( { - def success[T](v: T) = Expected(Success(v), 1765, methodCostDetails(SAvlTree.keyLengthMethod, 15), 1765) + def success[T](v: T) = Expected(Success(v), 1765, methodCostDetails(SAvlTreeMethods.keyLengthMethod, 15), 1765) Seq( (t1, success(1)), (t2, success(32)), @@ -2974,7 +2975,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyCases( { - def success[T](v: T, newCost: Int) = Expected(Success(v), newCost, methodCostDetails(SAvlTree.valueLengthOptMethod, 15), newCost) + def success[T](v: T, newCost: Int) = Expected(Success(v), newCost, methodCostDetails(SAvlTreeMethods.valueLengthOptMethod, 15), newCost) Seq( (t1, success(Some(1), 1766)), (t2, success(Some(64), 1766)), @@ -2987,7 +2988,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyCases( { - def success[T](v: T) = Expected(Success(v), 1765, methodCostDetails(SAvlTree.isInsertAllowedMethod, 15), 1765) + def success[T](v: T) = Expected(Success(v), 1765, methodCostDetails(SAvlTreeMethods.isInsertAllowedMethod, 15), 1765) Seq( (t1, success(false)), (t2, success(false)), @@ -3000,7 +3001,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyCases( { - def success[T](v: T) = Expected(Success(v), 1765, methodCostDetails(SAvlTree.isUpdateAllowedMethod, 15), 1765) + def success[T](v: T) = Expected(Success(v), 1765, methodCostDetails(SAvlTreeMethods.isUpdateAllowedMethod, 15), 1765) Seq( (t1, success(true)), (t2, success(false)), @@ -3013,7 +3014,7 @@ class SigmaDslSpecification extends SigmaDslTesting verifyCases( { - def success[T](v: T) = Expected(Success(v), 1765, methodCostDetails(SAvlTree.isRemoveAllowedMethod, 15), 1765) + def success[T](v: T) = Expected(Success(v), 1765, methodCostDetails(SAvlTreeMethods.isRemoveAllowedMethod, 15), 1765) Seq( (t1, success(true)), (t2, success(false)), @@ -3055,7 +3056,7 @@ class SigmaDslSpecification extends SigmaDslTesting ), 1.toByte ), - SAvlTree.getMethodByName("contains"), + SAvlTreeMethods.getMethodByName("contains"), Vector( SelectField.typed[Value[SCollection[SByte.type]]]( ValUse(3, STuple(Vector(SCollectionType(SByte), SCollectionType(SByte)))), @@ -3099,7 +3100,7 @@ class SigmaDslSpecification extends SigmaDslTesting ), 1.toByte ), - SAvlTree.getMethodByName("get"), + SAvlTreeMethods.getMethodByName("get"), Vector( SelectField.typed[Value[SCollection[SByte.type]]]( ValUse(3, STuple(Vector(SCollectionType(SByte), SCollectionType(SByte)))), @@ -3162,7 +3163,7 @@ class SigmaDslSpecification extends SigmaDslTesting ), 1.toByte ), - SAvlTree.getMethodByName("getMany"), + SAvlTreeMethods.getMethodByName("getMany"), Vector( SelectField.typed[Value[SCollection[SCollection[SByte.type]]]]( ValUse(3, STuple(Vector(SCollectionType(SCollectionType(SByte)), SCollectionType(SByte)))), @@ -3188,7 +3189,7 @@ class SigmaDslSpecification extends SigmaDslTesting ValUse(1, STuple(Vector(SAvlTree, SCollectionType(SByte)))), 1.toByte ), - SAvlTree.getMethodByName("updateDigest"), + SAvlTreeMethods.getMethodByName("updateDigest"), Vector( SelectField.typed[Value[SCollection[SByte.type]]]( ValUse(1, STuple(Vector(SAvlTree, SCollectionType(SByte)))), @@ -3205,7 +3206,7 @@ class SigmaDslSpecification extends SigmaDslTesting Vector((1, STuple(Vector(SAvlTree, SByte)))), MethodCall.typed[Value[SAvlTree.type]]( SelectField.typed[Value[SAvlTree.type]](ValUse(1, STuple(Vector(SAvlTree, SByte))), 1.toByte), - SAvlTree.getMethodByName("updateOperations"), + SAvlTreeMethods.getMethodByName("updateOperations"), Vector( SelectField.typed[Value[SByte.type]](ValUse(1, STuple(Vector(SAvlTree, SByte))), 2.toByte) ), @@ -3323,7 +3324,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(MethodCall), FixedCostItem(ValUse), FixedCostItem(SelectField), - FixedCostItem(SAvlTree.updateDigestMethod, FixedCost(JitCost(40))) + FixedCostItem(SAvlTreeMethods.updateDigestMethod, FixedCost(JitCost(40))) ) ) @@ -3339,7 +3340,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(MethodCall), FixedCostItem(ValUse), FixedCostItem(SelectField), - FixedCostItem(SAvlTree.updateOperationsMethod, FixedCost(JitCost(45))) + FixedCostItem(SAvlTreeMethods.updateOperationsMethod, FixedCost(JitCost(45))) ) ) @@ -3473,7 +3474,7 @@ class SigmaDslSpecification extends SigmaDslTesting ), 1.toByte ), - SAvlTree.getMethodByName("insert"), + SAvlTreeMethods.getMethodByName("insert"), Vector( SelectField.typed[Value[SCollection[STuple]]]( ValUse( @@ -3512,14 +3513,14 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - FixedCostItem(SAvlTree.isInsertAllowedMethod, FixedCost(JitCost(15))) + FixedCostItem(SAvlTreeMethods.isInsertAllowedMethod, FixedCost(JitCost(15))) ) val costDetails1 = TracedCost(testTraceBase) val costDetails2 = TracedCost( testTraceBase ++ Array( SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 70), SeqCostItem(NamedDesc("InsertIntoAvlTree"), PerItemCost(JitCost(40), JitCost(10), 1), 1), - FixedCostItem(SAvlTree.updateDigestMethod, FixedCost(JitCost(40))) + FixedCostItem(SAvlTreeMethods.updateDigestMethod, FixedCost(JitCost(40))) ) ) @@ -3611,7 +3612,7 @@ class SigmaDslSpecification extends SigmaDslTesting ), 1.toByte ), - SAvlTree.getMethodByName("update"), + SAvlTreeMethods.getMethodByName("update"), Vector( SelectField.typed[Value[SCollection[STuple]]]( ValUse( @@ -3650,14 +3651,14 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - FixedCostItem(SAvlTree.isUpdateAllowedMethod, FixedCost(JitCost(15))) + FixedCostItem(SAvlTreeMethods.isUpdateAllowedMethod, FixedCost(JitCost(15))) ) val costDetails1 = TracedCost(testTraceBase) val costDetails2 = TracedCost( testTraceBase ++ Array( SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 111), SeqCostItem(NamedDesc("UpdateAvlTree"), PerItemCost(JitCost(120), JitCost(20), 1), 1), - FixedCostItem(SAvlTree.updateDigestMethod, FixedCost(JitCost(40))) + FixedCostItem(SAvlTreeMethods.updateDigestMethod, FixedCost(JitCost(40))) ) ) val costDetails3 = TracedCost( @@ -3746,7 +3747,7 @@ class SigmaDslSpecification extends SigmaDslTesting ValUse(1, STuple(Vector(SAvlTree, STuple(Vector(SByteArray2, SByteArray))))), 1.toByte ), - SAvlTree.getMethodByName("remove"), + SAvlTreeMethods.getMethodByName("remove"), Vector( SelectField.typed[Value[SCollection[SCollection[SByte.type]]]]( ValUse(3, STuple(Vector(SByteArray2, SByteArray))), @@ -3779,23 +3780,23 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - FixedCostItem(SAvlTree.isRemoveAllowedMethod, FixedCost(JitCost(15))) + FixedCostItem(SAvlTreeMethods.isRemoveAllowedMethod, FixedCost(JitCost(15))) ) val costDetails1 = TracedCost( testTraceBase ++ Array( SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 436), SeqCostItem(NamedDesc("RemoveAvlTree"), PerItemCost(JitCost(100), JitCost(15), 1), 3), SeqCostItem(NamedDesc("RemoveAvlTree"), PerItemCost(JitCost(100), JitCost(15), 1), 3), - FixedCostItem(SAvlTree.digestMethod, FixedCost(JitCost(15))), - FixedCostItem(SAvlTree.updateDigestMethod, FixedCost(JitCost(40))) + FixedCostItem(SAvlTreeMethods.digestMethod, FixedCost(JitCost(15))), + FixedCostItem(SAvlTreeMethods.updateDigestMethod, FixedCost(JitCost(40))) ) ) val costDetails2 = TracedCost( testTraceBase ++ Array( SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 140), SeqCostItem(NamedDesc("RemoveAvlTree"), PerItemCost(JitCost(100), JitCost(15), 1), 1), - FixedCostItem(SAvlTree.digestMethod, FixedCost(JitCost(15))), - FixedCostItem(SAvlTree.updateDigestMethod, FixedCost(JitCost(40))) + FixedCostItem(SAvlTreeMethods.digestMethod, FixedCost(JitCost(15))), + FixedCostItem(SAvlTreeMethods.updateDigestMethod, FixedCost(JitCost(40))) ) ) val costDetails3 = TracedCost(testTraceBase) @@ -3803,7 +3804,7 @@ class SigmaDslSpecification extends SigmaDslTesting testTraceBase ++ Array( SeqCostItem(NamedDesc("CreateAvlVerifier"), PerItemCost(JitCost(110), JitCost(20), 64), 140), SeqCostItem(NamedDesc("RemoveAvlTree"), PerItemCost(JitCost(100), JitCost(15), 1), 1), - FixedCostItem(SAvlTree.digestMethod, FixedCost(JitCost(15))) + FixedCostItem(SAvlTreeMethods.digestMethod, FixedCost(JitCost(15))) ) ) @@ -4047,8 +4048,8 @@ class SigmaDslSpecification extends SigmaDslTesting b1 -> Expected(Success(Coll[(Coll[Byte], Long)]( (Helpers.decodeBytes("6e789ab7b2fffff12280a6cd01557f6fb22b7f80ff7aff8e1f7f15973d7f0001"), 10000000L), (Helpers.decodeBytes("a3ff007f00057600808001ff8f8000019000ffdb806fff7cc0b6015eb37fa600"), 500L) - ).map(identity)), 1772, methodCostDetails(SBox.tokensMethod, 15), 1772), - b2 -> Expected(Success(Coll[(Coll[Byte], Long)]().map(identity)), 1766, methodCostDetails(SBox.tokensMethod, 15), 1766) + ).map(identity)), 1772, methodCostDetails(SBoxMethods.tokensMethod, 15), 1772), + b2 -> Expected(Success(Coll[(Coll[Byte], Long)]().map(identity)), 1766, methodCostDetails(SBoxMethods.tokensMethod, 15), 1766) ), existingFeature({ (x: Box) => x.tokens }, "{ (x: Box) => x.tokens }", @@ -4056,7 +4057,7 @@ class SigmaDslSpecification extends SigmaDslTesting Vector((1, SBox)), MethodCall.typed[Value[SCollection[STuple]]]( ValUse(1, SBox), - SBox.getMethodByName("tokens"), + SBoxMethods.getMethodByName("tokens"), Vector(), Map() ) @@ -4481,11 +4482,11 @@ class SigmaDslSpecification extends SigmaDslTesting val tA = RType[A] val typeName = tA.name val stypeA = Evaluation.rtypeToSType(tA) - val typeCompanion = stypeA.asInstanceOf[STypeCompanion] + val m = MethodsContainer.getMethod(stypeA, propName).get existingFeature(scalaFunc, s"{ (x: $typeName) => x.$propName }", FuncValue(Vector((1, stypeA)), - MethodCall(ValUse(1, stypeA), typeCompanion.getMethodByName(propName), Vector(), Map() ) + MethodCall(ValUse(1, stypeA), m, Vector(), Map() ) )) } @@ -4493,35 +4494,35 @@ class SigmaDslSpecification extends SigmaDslTesting verifyCases( - Seq((preH1, Expected(Success(0.toByte), cost = 1765, methodCostDetails(SPreHeader.versionMethod, 10), 1765))), + Seq((preH1, Expected(Success(0.toByte), cost = 1765, methodCostDetails(SPreHeaderMethods.versionMethod, 10), 1765))), existingPropTest("version", { (x: PreHeader) => x.version })) verifyCases( Seq((preH1, Expected(Success( Helpers.decodeBytes("7fff7fdd6f62018bae0001006d9ca888ff7f56ff8006573700a167f17f2c9f40")), - cost = 1766, methodCostDetails(SPreHeader.parentIdMethod, 10), 1766))), + cost = 1766, methodCostDetails(SPreHeaderMethods.parentIdMethod, 10), 1766))), existingPropTest("parentId", { (x: PreHeader) => x.parentId })) verifyCases( - Seq((preH1, Expected(Success(6306290372572472443L), cost = 1765, methodCostDetails(SPreHeader.timestampMethod, 10), 1765))), + Seq((preH1, Expected(Success(6306290372572472443L), cost = 1765, methodCostDetails(SPreHeaderMethods.timestampMethod, 10), 1765))), existingPropTest("timestamp", { (x: PreHeader) => x.timestamp })) verifyCases( - Seq((preH1, Expected(Success(-3683306095029417063L), cost = 1765, methodCostDetails(SPreHeader.nBitsMethod, 10), 1765))), + Seq((preH1, Expected(Success(-3683306095029417063L), cost = 1765, methodCostDetails(SPreHeaderMethods.nBitsMethod, 10), 1765))), existingPropTest("nBits", { (x: PreHeader) => x.nBits })) verifyCases( - Seq((preH1, Expected(Success(1), cost = 1765, methodCostDetails(SPreHeader.heightMethod, 10), 1765))), + Seq((preH1, Expected(Success(1), cost = 1765, methodCostDetails(SPreHeaderMethods.heightMethod, 10), 1765))), existingPropTest("height", { (x: PreHeader) => x.height })) verifyCases( Seq((preH1, Expected(Success( Helpers.decodeGroupElement("026930cb9972e01534918a6f6d6b8e35bc398f57140d13eb3623ea31fbd069939b")), - cost = 1782, methodCostDetails(SPreHeader.minerPkMethod, 10), 1782))), + cost = 1782, methodCostDetails(SPreHeaderMethods.minerPkMethod, 10), 1782))), existingPropTest("minerPk", { (x: PreHeader) => x.minerPk })) verifyCases( - Seq((preH1, Expected(Success(Helpers.decodeBytes("ff8087")), cost = 1766, methodCostDetails(SPreHeader.votesMethod,10), 1766))), + Seq((preH1, Expected(Success(Helpers.decodeBytes("ff8087")), cost = 1766, methodCostDetails(SPreHeaderMethods.votesMethod,10), 1766))), existingPropTest("votes", { (x: PreHeader) => x.votes })) } @@ -4529,81 +4530,81 @@ class SigmaDslSpecification extends SigmaDslTesting verifyCases( Seq((h1, Expected(Success( Helpers.decodeBytes("957f008001808080ffe4ffffc8f3802401df40006aa05e017fa8d3f6004c804a")), - cost = 1766, methodCostDetails(SHeader.idMethod, 10), 1766))), + cost = 1766, methodCostDetails(SHeaderMethods.idMethod, 10), 1766))), existingPropTest("id", { (x: Header) => x.id })) verifyCases( - Seq((h1, Expected(Success(0.toByte), cost = 1765, methodCostDetails(SHeader.versionMethod, 10), 1765))), + Seq((h1, Expected(Success(0.toByte), cost = 1765, methodCostDetails(SHeaderMethods.versionMethod, 10), 1765))), existingPropTest("version", { (x: Header) => x.version })) verifyCases( Seq((h1, Expected(Success( Helpers.decodeBytes("0180dd805b0000ff5400b997fd7f0b9b00de00fb03c47e37806a8186b94f07ff")), - cost = 1766, methodCostDetails(SHeader.parentIdMethod, 10), 1766))), + cost = 1766, methodCostDetails(SHeaderMethods.parentIdMethod, 10), 1766))), existingPropTest("parentId", { (x: Header) => x.parentId })) verifyCases( Seq((h1, Expected(Success( Helpers.decodeBytes("01f07f60d100ffb970c3007f60ff7f24d4070bb8fffa7fca7f34c10001ffe39d")), - cost = 1766, methodCostDetails(SHeader.ADProofsRootMethod, 10), 1766))), + cost = 1766, methodCostDetails(SHeaderMethods.ADProofsRootMethod, 10), 1766))), existingPropTest("ADProofsRoot", { (x: Header) => x.ADProofsRoot})) verifyCases( - Seq((h1, Expected(Success(CAvlTree(createAvlTreeData())), cost = 1765, methodCostDetails(SHeader.stateRootMethod, 10), 1765))), + Seq((h1, Expected(Success(CAvlTree(createAvlTreeData())), cost = 1765, methodCostDetails(SHeaderMethods.stateRootMethod, 10), 1765))), existingPropTest("stateRoot", { (x: Header) => x.stateRoot })) verifyCases( Seq((h1, Expected(Success( Helpers.decodeBytes("804101ff01000080a3ffbd006ac080098df132a7017f00649311ec0e00000100")), - cost = 1766, methodCostDetails(SHeader.transactionsRootMethod, 10), 1766))), + cost = 1766, methodCostDetails(SHeaderMethods.transactionsRootMethod, 10), 1766))), existingPropTest("transactionsRoot", { (x: Header) => x.transactionsRoot })) verifyCases( - Seq((h1, Expected(Success(1L), cost = 1765, methodCostDetails(SHeader.timestampMethod, 10), 1765))), + Seq((h1, Expected(Success(1L), cost = 1765, methodCostDetails(SHeaderMethods.timestampMethod, 10), 1765))), existingPropTest("timestamp", { (x: Header) => x.timestamp })) verifyCases( - Seq((h1, Expected(Success(-1L), cost = 1765, methodCostDetails(SHeader.nBitsMethod, 10), 1765))), + Seq((h1, Expected(Success(-1L), cost = 1765, methodCostDetails(SHeaderMethods.nBitsMethod, 10), 1765))), existingPropTest("nBits", { (x: Header) => x.nBits })) verifyCases( - Seq((h1, Expected(Success(1), cost = 1765, methodCostDetails(SHeader.heightMethod, 10), 1765))), + Seq((h1, Expected(Success(1), cost = 1765, methodCostDetails(SHeaderMethods.heightMethod, 10), 1765))), existingPropTest("height", { (x: Header) => x.height })) verifyCases( Seq((h1, Expected(Success( Helpers.decodeBytes("e57f80885601b8ff348e01808000bcfc767f2dd37f0d01015030ec018080bc62")), - cost = 1766, methodCostDetails(SHeader.extensionRootMethod, 10), 1766))), + cost = 1766, methodCostDetails(SHeaderMethods.extensionRootMethod, 10), 1766))), existingPropTest("extensionRoot", { (x: Header) => x.extensionRoot })) verifyCases( Seq((h1, Expected(Success( Helpers.decodeGroupElement("039bdbfa0b49cc6bef58297a85feff45f7bbeb500a9d2283004c74fcedd4bd2904")), - cost = 1782, methodCostDetails(SHeader.minerPkMethod, 10), 1782))), + cost = 1782, methodCostDetails(SHeaderMethods.minerPkMethod, 10), 1782))), existingPropTest("minerPk", { (x: Header) => x.minerPk })) verifyCases( Seq((h1, Expected(Success( Helpers.decodeGroupElement("0361299207fa392231e23666f6945ae3e867b978e021d8d702872bde454e9abe9c")), - cost = 1782, methodCostDetails(SHeader.powOnetimePkMethod, 10), 1782))), + cost = 1782, methodCostDetails(SHeaderMethods.powOnetimePkMethod, 10), 1782))), existingPropTest("powOnetimePk", { (x: Header) => x.powOnetimePk })) verifyCases( Seq((h1, Expected(Success( Helpers.decodeBytes("7f4f09012a807f01")), - cost = 1766, methodCostDetails(SHeader.powNonceMethod, 10), 1766))), + cost = 1766, methodCostDetails(SHeaderMethods.powNonceMethod, 10), 1766))), existingPropTest("powNonce", { (x: Header) => x.powNonce })) verifyCases( Seq((h1, Expected(Success( CBigInt(new BigInteger("-e24990c47e15ed4d0178c44f1790cc72155d516c43c3e8684e75db3800a288", 16))), - cost = 1765, methodCostDetails(SHeader.powDistanceMethod, 10), 1765))), + cost = 1765, methodCostDetails(SHeaderMethods.powDistanceMethod, 10), 1765))), existingPropTest("powDistance", { (x: Header) => x.powDistance })) verifyCases( Seq((h1, Expected(Success( Helpers.decodeBytes("7f0180")), - cost = 1766, methodCostDetails(SHeader.votesMethod, 10), 1766))), + cost = 1766, methodCostDetails(SHeaderMethods.votesMethod, 10), 1766))), existingPropTest("votes", { (x: Header) => x.votes })) } @@ -4809,7 +4810,7 @@ class SigmaDslSpecification extends SigmaDslTesting val testTraceBase = traceBase ++ Array( FixedCostItem(PropertyCall), - FixedCostItem(SContext.dataInputsMethod, FixedCost(JitCost(15))), + FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), FixedCostItem(Constant), FixedCostItem(ByIndex) ) @@ -4827,7 +4828,7 @@ class SigmaDslSpecification extends SigmaDslTesting ByIndex( MethodCall.typed[Value[SCollection[SBox.type]]]( ValUse(1, SContext), - SContext.getMethodByName("dataInputs"), + SContextMethods.getMethodByName("dataInputs"), Vector(), Map() ), @@ -4852,7 +4853,7 @@ class SigmaDslSpecification extends SigmaDslTesting ByIndex( MethodCall.typed[Value[SCollection[SBox.type]]]( ValUse(1, SContext), - SContext.getMethodByName("dataInputs"), + SContextMethods.getMethodByName("dataInputs"), Vector(), Map() ), @@ -4933,7 +4934,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(Inputs), FixedCostItem(MethodCall), FixedCostItem(FuncValue), - SeqCostItem(MethodDesc(SCollection.MapMethod), PerItemCost(JitCost(20), JitCost(1), 10), 1), + SeqCostItem(MethodDesc(SCollectionMethods.MapMethod), PerItemCost(JitCost(20), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(ExtractAmount) @@ -4954,7 +4955,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((1, SContext)), MethodCall.typed[Value[SCollection[SLong.type]]]( Inputs, - SCollection.getMethodByName("map").withConcreteTypes( + SCollectionMethods.getMethodByName("map").withConcreteTypes( Map(STypeVar("IV") -> SBox, STypeVar("OV") -> SLong) ), Vector(FuncValue(Array((3, SBox)), ExtractAmount(ValUse(3, SBox)))), @@ -4988,7 +4989,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - SeqCostItem(MethodDesc(SCollection.MapMethod), PerItemCost(JitCost(20), JitCost(1), 10), 1), + SeqCostItem(MethodDesc(SCollectionMethods.MapMethod), PerItemCost(JitCost(20), JitCost(1), 10), 1), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), @@ -5025,7 +5026,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((1, SContext)), MethodCall.typed[Value[SCollection[STuple]]]( Inputs, - SCollection.getMethodByName("map").withConcreteTypes( + SCollectionMethods.getMethodByName("map").withConcreteTypes( Map(STypeVar("IV") -> SBox, STypeVar("OV") -> SPair(SLong, SLong)) ), Vector( @@ -5082,7 +5083,7 @@ class SigmaDslSpecification extends SigmaDslTesting val selfCostDetails = TracedCost( traceBase ++ Array( FixedCostItem(PropertyCall), - FixedCostItem(SContext.selfBoxIndexMethod, FixedCost(JitCost(20))) + FixedCostItem(SContextMethods.selfBoxIndexMethod, FixedCost(JitCost(20))) ) ) verifyCases( @@ -5103,7 +5104,7 @@ class SigmaDslSpecification extends SigmaDslTesting Vector((1, SContext)), MethodCall.typed[Value[SInt.type]]( ValUse(1, SContext), - SContext.getMethodByName("selfBoxIndex"), + SContextMethods.getMethodByName("selfBoxIndex"), Vector(), Map() ) @@ -5122,16 +5123,16 @@ class SigmaDslSpecification extends SigmaDslTesting } verifyCases( - Seq(ctx -> Expected(Success(ctx.LastBlockUtxoRootHash), cost = 1766, methodCostDetails(SContext.lastBlockUtxoRootHashMethod, 15), 1766)), + Seq(ctx -> Expected(Success(ctx.LastBlockUtxoRootHash), cost = 1766, methodCostDetails(SContextMethods.lastBlockUtxoRootHashMethod, 15), 1766)), existingPropTest("LastBlockUtxoRootHash", { (x: Context) => x.LastBlockUtxoRootHash }), preGeneratedSamples = Some(samples)) val isUpdateAllowedCostDetails = TracedCost( traceBase ++ Array( FixedCostItem(PropertyCall), - FixedCostItem(SContext.lastBlockUtxoRootHashMethod, FixedCost(JitCost(15))), + FixedCostItem(SContextMethods.lastBlockUtxoRootHashMethod, FixedCost(JitCost(15))), FixedCostItem(PropertyCall), - FixedCostItem(SAvlTree.isUpdateAllowedMethod, FixedCost(JitCost(15))) + FixedCostItem(SAvlTreeMethods.isUpdateAllowedMethod, FixedCost(JitCost(15))) ) ) verifyCases( @@ -5144,11 +5145,11 @@ class SigmaDslSpecification extends SigmaDslTesting MethodCall.typed[Value[SBoolean.type]]( MethodCall.typed[Value[SAvlTree.type]]( ValUse(1, SContext), - SContext.getMethodByName("LastBlockUtxoRootHash"), + SContextMethods.getMethodByName("LastBlockUtxoRootHash"), Vector(), Map() ), - SAvlTree.getMethodByName("isUpdateAllowed"), + SAvlTreeMethods.getMethodByName("isUpdateAllowed"), Vector(), Map() ) @@ -5156,7 +5157,7 @@ class SigmaDslSpecification extends SigmaDslTesting preGeneratedSamples = Some(samples)) verifyCases( - Seq(ctx -> Expected(Success(ctx.minerPubKey), cost = 1767, methodCostDetails(SContext.minerPubKeyMethod, 20), 1767)), + Seq(ctx -> Expected(Success(ctx.minerPubKey), cost = 1767, methodCostDetails(SContextMethods.minerPubKeyMethod, 20), 1767)), existingPropTest("minerPubKey", { (x: Context) => x.minerPubKey }), preGeneratedSamples = Some(samples)) @@ -5216,7 +5217,7 @@ class SigmaDslSpecification extends SigmaDslTesting SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SContext.dataInputsMethod, FixedCost(JitCost(15))), + FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), FixedCostItem(Constant), FixedCostItem(ByIndex), FixedCostItem(ExtractRegisterAs), @@ -5260,7 +5261,7 @@ class SigmaDslSpecification extends SigmaDslTesting ByIndex( MethodCall.typed[Value[SCollection[SBox.type]]]( ValUse(1, SContext), - SContext.getMethodByName("dataInputs"), + SContextMethods.getMethodByName("dataInputs"), Vector(), Map() ), @@ -5332,7 +5333,7 @@ class SigmaDslSpecification extends SigmaDslTesting ByIndex( MethodCall.typed[Value[SCollection[SBox.type]]]( ValUse(1, SContext), - SContext.getMethodByName("dataInputs"), + SContextMethods.getMethodByName("dataInputs"), Vector(), Map() ), @@ -5775,7 +5776,7 @@ class SigmaDslSpecification extends SigmaDslTesting SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SContext.dataInputsMethod, FixedCost(JitCost(15))), + FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), FixedCostItem(Constant), FixedCostItem(ByIndex), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -5812,7 +5813,7 @@ class SigmaDslSpecification extends SigmaDslTesting SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SContext.dataInputsMethod, FixedCost(JitCost(15))), + FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), FixedCostItem(Constant), FixedCostItem(ByIndex), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -5846,7 +5847,7 @@ class SigmaDslSpecification extends SigmaDslTesting SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SContext.dataInputsMethod, FixedCost(JitCost(15))), + FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), FixedCostItem(Constant), FixedCostItem(ByIndex), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -5881,7 +5882,7 @@ class SigmaDslSpecification extends SigmaDslTesting SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SContext.dataInputsMethod, FixedCost(JitCost(15))), + FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), FixedCostItem(Constant), FixedCostItem(ByIndex), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -5959,7 +5960,7 @@ class SigmaDslSpecification extends SigmaDslTesting ByIndex( MethodCall.typed[Value[SCollection[SBox.type]]]( ValUse(1, SContext), - SContext.getMethodByName("dataInputs"), + SContextMethods.getMethodByName("dataInputs"), Vector(), Map() ), @@ -6003,7 +6004,7 @@ class SigmaDslSpecification extends SigmaDslTesting SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SContext.dataInputsMethod, FixedCost(JitCost(15))), + FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), FixedCostItem(Constant), FixedCostItem(ByIndex), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -6043,7 +6044,7 @@ class SigmaDslSpecification extends SigmaDslTesting SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SContext.dataInputsMethod, FixedCost(JitCost(15))), + FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), FixedCostItem(Constant), FixedCostItem(ByIndex), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -6080,7 +6081,7 @@ class SigmaDslSpecification extends SigmaDslTesting SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SContext.dataInputsMethod, FixedCost(JitCost(15))), + FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), FixedCostItem(Constant), FixedCostItem(ByIndex), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -6115,7 +6116,7 @@ class SigmaDslSpecification extends SigmaDslTesting SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 2), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SContext.dataInputsMethod, FixedCost(JitCost(15))), + FixedCostItem(SContextMethods.dataInputsMethod, FixedCost(JitCost(15))), FixedCostItem(Constant), FixedCostItem(ByIndex), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), @@ -6192,7 +6193,7 @@ class SigmaDslSpecification extends SigmaDslTesting ByIndex( MethodCall.typed[Value[SCollection[SBox.type]]]( ValUse(1, SContext), - SContext.getMethodByName("dataInputs"), + SContextMethods.getMethodByName("dataInputs"), Vector(), Map() ), @@ -6395,7 +6396,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(Global), FixedCostItem(PropertyCall), - FixedCostItem(SGlobal.groupGeneratorMethod, FixedCost(JitCost(10))) + FixedCostItem(SGlobalMethods.groupGeneratorMethod, FixedCost(JitCost(10))) ) ) verifyCases( @@ -6411,7 +6412,7 @@ class SigmaDslSpecification extends SigmaDslTesting Vector((1, SInt)), MethodCall.typed[Value[SGroupElement.type]]( Global, - SGlobal.getMethodByName("groupGenerator"), + SGlobalMethods.getMethodByName("groupGenerator"), Vector(), Map() ) @@ -6430,7 +6431,7 @@ class SigmaDslSpecification extends SigmaDslTesting Vector((1, SInt)), MethodCall.typed[Value[SGroupElement.type]]( Global, - SGlobal.getMethodByName("groupGenerator"), + SGlobalMethods.getMethodByName("groupGenerator"), Vector(), Map() ) @@ -6468,7 +6469,7 @@ class SigmaDslSpecification extends SigmaDslTesting Exponentiate( MethodCall.typed[Value[SGroupElement.type]]( Global, - SGlobal.getMethodByName("groupGenerator"), + SGlobalMethods.getMethodByName("groupGenerator"), Vector(), Map() ), @@ -6554,7 +6555,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((1, SPair(SByteArray, SByteArray))), MethodCall.typed[Value[SCollection[SByte.type]]]( Global, - SGlobal.getMethodByName("xor"), + SGlobalMethods.getMethodByName("xor"), Vector( SelectField.typed[Value[SCollection[SByte.type]]]( ValUse(1, SPair(SByteArray, SByteArray)), @@ -6693,7 +6694,7 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - SeqCostItem(MethodDesc(SCollection.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 0) + SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 0) ) ) val costDetails2 = TracedCost( @@ -6703,7 +6704,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(ExtractScriptBytes), - SeqCostItem(MethodDesc(SCollection.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 135) + SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 135) ) ) val costDetails3 = TracedCost( @@ -6716,7 +6717,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(ExtractScriptBytes), - SeqCostItem(MethodDesc(SCollection.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 147) + SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 147) ) ) verifyCases( @@ -6737,7 +6738,7 @@ class SigmaDslSpecification extends SigmaDslTesting Vector((1, SCollectionType(SBox))), MethodCall.typed[Value[SCollection[SByte.type]]]( ValUse(1, SCollectionType(SBox)), - SCollection.getMethodByName("flatMap").withConcreteTypes( + SCollectionMethods.getMethodByName("flatMap").withConcreteTypes( Map(STypeVar("IV") -> SBox, STypeVar("OV") -> SByte) ), Vector(FuncValue(Vector((3, SBox)), ExtractScriptBytes(ValUse(3, SBox)))), @@ -6755,7 +6756,7 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(ValUse), - SeqCostItem(MethodDesc(SCollection.ZipMethod), PerItemCost(JitCost(10), JitCost(1), 10), zipElements) + SeqCostItem(MethodDesc(SCollectionMethods.ZipMethod), PerItemCost(JitCost(10), JitCost(1), 10), zipElements) ) ) @@ -6774,7 +6775,7 @@ class SigmaDslSpecification extends SigmaDslTesting Vector((1, SCollectionType(SBox))), MethodCall.typed[Value[SCollection[STuple]]]( ValUse(1, SCollectionType(SBox)), - SCollection.getMethodByName("zip").withConcreteTypes( + SCollectionMethods.getMethodByName("zip").withConcreteTypes( Map(STypeVar("IV") -> SBox, STypeVar("OV") -> SBox) ), Vector(ValUse(1, SCollectionType(SBox))), @@ -6811,7 +6812,7 @@ class SigmaDslSpecification extends SigmaDslTesting def costDetails(indicesCount: Int) = TracedCost( traceBase ++ Array( FixedCostItem(PropertyCall), - SeqCostItem(MethodDesc(SCollection.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), indicesCount) + SeqCostItem(MethodDesc(SCollectionMethods.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), indicesCount) ) ) verifyCases( @@ -6829,7 +6830,7 @@ class SigmaDslSpecification extends SigmaDslTesting Vector((1, SCollectionType(SBox))), MethodCall.typed[Value[SCollection[SInt.type]]]( ValUse(1, SCollectionType(SBox)), - SCollection.getMethodByName("indices").withConcreteTypes(Map(STypeVar("IV") -> SBox)), + SCollectionMethods.getMethodByName("indices").withConcreteTypes(Map(STypeVar("IV") -> SBox)), Vector(), Map() ) @@ -6900,7 +6901,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((1, SCollectionType(SBox))), MethodCall.typed[Value[SBoolean.type]]( ValUse(1, SCollectionType(SBox)), - SCollection.getMethodByName("forall").withConcreteTypes(Map(STypeVar("IV") -> SBox)), + SCollectionMethods.getMethodByName("forall").withConcreteTypes(Map(STypeVar("IV") -> SBox)), Vector(FuncValue(Array((3, SBox)), GT(ExtractAmount(ValUse(3, SBox)), LongConstant(1L)))), Map() ) @@ -6976,7 +6977,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((1, SCollectionType(SBox))), MethodCall.typed[Value[SBoolean.type]]( ValUse(1, SCollectionType(SBox)), - SCollection.getMethodByName("exists").withConcreteTypes(Map(STypeVar("IV") -> SBox)), + SCollectionMethods.getMethodByName("exists").withConcreteTypes(Map(STypeVar("IV") -> SBox)), Vector(FuncValue(Array((3, SBox)), GT(ExtractAmount(ValUse(3, SBox)), LongConstant(1L)))), Map() ) @@ -7082,7 +7083,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((1, SCollectionType(SBigInt))), MethodCall.typed[Value[SBoolean.type]]( ValUse(1, SCollectionType(SBigInt)), - SCollection.getMethodByName("exists").withConcreteTypes(Map(STypeVar("IV") -> SBigInt)), + SCollectionMethods.getMethodByName("exists").withConcreteTypes(Map(STypeVar("IV") -> SBigInt)), Vector( FuncValue( Array((3, SBigInt)), @@ -7197,7 +7198,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((1, SCollectionType(SBigInt))), MethodCall.typed[Value[SBoolean.type]]( ValUse(1, SCollectionType(SBigInt)), - SCollection.getMethodByName("forall").withConcreteTypes(Map(STypeVar("IV") -> SBigInt)), + SCollectionMethods.getMethodByName("forall").withConcreteTypes(Map(STypeVar("IV") -> SBigInt)), Vector( FuncValue( Array((3, SBigInt)), @@ -7225,7 +7226,7 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - SeqCostItem(MethodDesc(SCollection.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 0) + SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 0) ) ) val costDetails1 = TracedCost( @@ -7234,7 +7235,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(FuncValue), FixedCostItem(NamedDesc("MatchSingleArgMethodCall"), FixedCost(JitCost(30))), SeqCostItem(NamedDesc("CheckFlatmapBody"), PerItemCost(JitCost(20), JitCost(20), 1), 1), - SeqCostItem(MethodDesc(SCollection.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 0) + SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 0) ) ) val costDetails2 = TracedCost( @@ -7244,12 +7245,12 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SGroupElement.GetEncodedMethod, FixedCost(JitCost(250))), + FixedCostItem(SGroupElementMethods.GetEncodedMethod, FixedCost(JitCost(250))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SGroupElement.GetEncodedMethod, FixedCost(JitCost(250))), - SeqCostItem(MethodDesc(SCollection.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 66) + FixedCostItem(SGroupElementMethods.GetEncodedMethod, FixedCost(JitCost(250))), + SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 66) ) ) val costDetails3 = TracedCost( @@ -7259,16 +7260,16 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SGroupElement.GetEncodedMethod, FixedCost(JitCost(250))), + FixedCostItem(SGroupElementMethods.GetEncodedMethod, FixedCost(JitCost(250))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SGroupElement.GetEncodedMethod, FixedCost(JitCost(250))), + FixedCostItem(SGroupElementMethods.GetEncodedMethod, FixedCost(JitCost(250))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SGroupElement.GetEncodedMethod, FixedCost(JitCost(250))), - SeqCostItem(MethodDesc(SCollection.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 99) + FixedCostItem(SGroupElementMethods.GetEncodedMethod, FixedCost(JitCost(250))), + SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 99) ) ) val costDetails4 = TracedCost( @@ -7278,16 +7279,16 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SGroupElement.GetEncodedMethod, FixedCost(JitCost(250))), + FixedCostItem(SGroupElementMethods.GetEncodedMethod, FixedCost(JitCost(250))), FixedCostItem(PropertyCall), - SeqCostItem(MethodDesc(SCollection.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), 33), + SeqCostItem(MethodDesc(SCollectionMethods.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), 33), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SGroupElement.GetEncodedMethod, FixedCost(JitCost(250))), + FixedCostItem(SGroupElementMethods.GetEncodedMethod, FixedCost(JitCost(250))), FixedCostItem(PropertyCall), - SeqCostItem(MethodDesc(SCollection.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), 33), - SeqCostItem(MethodDesc(SCollection.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 66) + SeqCostItem(MethodDesc(SCollectionMethods.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), 33), + SeqCostItem(MethodDesc(SCollectionMethods.FlatMapMethod), PerItemCost(JitCost(60), JitCost(10), 8), 66) ) ) @@ -7324,7 +7325,7 @@ class SigmaDslSpecification extends SigmaDslTesting Vector((1, SCollectionType(SGroupElement))), MethodCall.typed[Value[SCollection[SByte.type]]]( ValUse(1, SCollectionType(SGroupElement)), - SCollection.getMethodByName("flatMap").withConcreteTypes( + SCollectionMethods.getMethodByName("flatMap").withConcreteTypes( Map(STypeVar("IV") -> SGroupElement, STypeVar("OV") -> SByte) ), Vector( @@ -7332,7 +7333,7 @@ class SigmaDslSpecification extends SigmaDslTesting Vector((3, SGroupElement)), MethodCall.typed[Value[SCollection[SByte.type]]]( ValUse(3, SGroupElement), - SGroupElement.getMethodByName("getEncoded"), + SGroupElementMethods.getMethodByName("getEncoded"), Vector(), Map() ) @@ -7366,7 +7367,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((1, SCollectionType(SGroupElement))), MethodCall.typed[Value[SCollection[SInt.type]]]( ValUse(1, SCollectionType(SGroupElement)), - SCollection.getMethodByName("flatMap").withConcreteTypes( + SCollectionMethods.getMethodByName("flatMap").withConcreteTypes( Map(STypeVar("IV") -> SGroupElement, STypeVar("OV") -> SInt) ), Vector( @@ -7375,11 +7376,11 @@ class SigmaDslSpecification extends SigmaDslTesting MethodCall.typed[Value[SCollection[SInt.type]]]( MethodCall.typed[Value[SCollection[SByte.type]]]( ValUse(3, SGroupElement), - SGroupElement.getMethodByName("getEncoded"), + SGroupElementMethods.getMethodByName("getEncoded"), Vector(), Map() ), - SCollection.getMethodByName("indices").withConcreteTypes(Map(STypeVar("IV") -> SByte)), + SCollectionMethods.getMethodByName("indices").withConcreteTypes(Map(STypeVar("IV") -> SByte)), Vector(), Map() ) @@ -7416,7 +7417,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(ValUse), FixedCostItem(ValUse), FixedCostItem(SelectField), - SeqCostItem(MethodDesc(SCollection.PatchMethod), PerItemCost(JitCost(30), JitCost(2), 10), i) + SeqCostItem(MethodDesc(SCollectionMethods.PatchMethod), PerItemCost(JitCost(30), JitCost(2), 10), i) ) ) @@ -7472,7 +7473,7 @@ class SigmaDslSpecification extends SigmaDslTesting ), MethodCall.typed[Value[SCollection[SInt.type]]]( ValUse(3, SCollectionType(SInt)), - SCollection.getMethodByName("patch").withConcreteTypes(Map(STypeVar("IV") -> SInt)), + SCollectionMethods.getMethodByName("patch").withConcreteTypes(Map(STypeVar("IV") -> SInt)), Vector( SelectField.typed[Value[SInt.type]](ValUse(4, SPair(SInt, SInt)), 1.toByte), ValUse(3, SCollectionType(SInt)), @@ -7505,7 +7506,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - SeqCostItem(MethodDesc(SCollection.UpdatedMethod), PerItemCost(JitCost(20), JitCost(1), 10), i) + SeqCostItem(MethodDesc(SCollectionMethods.UpdatedMethod), PerItemCost(JitCost(20), JitCost(1), 10), i) ) ) verifyCases( @@ -7544,7 +7545,7 @@ class SigmaDslSpecification extends SigmaDslTesting ValUse(1, SPair(SCollectionType(SInt), SPair(SInt, SInt))), 1.toByte ), - SCollection.getMethodByName("updated").withConcreteTypes(Map(STypeVar("IV") -> SInt)), + SCollectionMethods.getMethodByName("updated").withConcreteTypes(Map(STypeVar("IV") -> SInt)), Vector( SelectField.typed[Value[SInt.type]](ValUse(3, SPair(SInt, SInt)), 1.toByte), SelectField.typed[Value[SInt.type]](ValUse(3, SPair(SInt, SInt)), 2.toByte) @@ -7582,7 +7583,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - SeqCostItem(MethodDesc(SCollection.UpdateManyMethod), PerItemCost(JitCost(20), JitCost(2), 10), i) + SeqCostItem(MethodDesc(SCollectionMethods.UpdateManyMethod), PerItemCost(JitCost(20), JitCost(2), 10), i) ) ) verifyCases( @@ -7632,7 +7633,7 @@ class SigmaDslSpecification extends SigmaDslTesting ValUse(1, SPair(SCollectionType(SInt), SPair(SCollectionType(SInt), SCollectionType(SInt)))), 1.toByte ), - SCollection.getMethodByName("updateMany").withConcreteTypes(Map(STypeVar("IV") -> SInt)), + SCollectionMethods.getMethodByName("updateMany").withConcreteTypes(Map(STypeVar("IV") -> SInt)), Vector( SelectField.typed[Value[SCollection[SInt.type]]]( ValUse(3, SPair(SCollectionType(SInt), SCollectionType(SInt))), @@ -7805,7 +7806,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((1, SPair(SByteArray, SInt))), MethodCall.typed[Value[SInt.type]]( SelectField.typed[Value[SCollection[SByte.type]]](ValUse(1, SPair(SByteArray, SInt)), 1.toByte), - SCollection.getMethodByName("fold").withConcreteTypes(Map(STypeVar("IV") -> SByte, STypeVar("OV") -> SInt)), + SCollectionMethods.getMethodByName("fold").withConcreteTypes(Map(STypeVar("IV") -> SByte, STypeVar("OV") -> SInt)), Vector( SelectField.typed[Value[SInt.type]](ValUse(1, SPair(SByteArray, SInt)), 2.toByte), FuncValue( @@ -8083,7 +8084,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((1, SPair(SByteArray, SInt))), MethodCall.typed[Value[SInt.type]]( SelectField.typed[Value[SCollection[SByte.type]]](ValUse(1, SPair(SByteArray, SInt)), 1.toByte), - SCollection.getMethodByName("fold").withConcreteTypes(Map(STypeVar("IV") -> SByte, STypeVar("OV") -> SInt)), + SCollectionMethods.getMethodByName("fold").withConcreteTypes(Map(STypeVar("IV") -> SByte, STypeVar("OV") -> SInt)), Vector( SelectField.typed[Value[SInt.type]](ValUse(1, SPair(SByteArray, SInt)), 2.toByte), FuncValue( @@ -8140,7 +8141,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField) ) ++ Array.fill(i)(FixedCostItem(NamedDesc("EQ_Prim"), FixedCost(JitCost(3)))) - :+ SeqCostItem(MethodDesc(SCollection.IndexOfMethod), PerItemCost(JitCost(20), JitCost(10), 2), i) + :+ SeqCostItem(MethodDesc(SCollectionMethods.IndexOfMethod), PerItemCost(JitCost(20), JitCost(10), 2), i) ) verifyCases( // (coll, (elem: Byte, from: Int)) @@ -8189,7 +8190,7 @@ class SigmaDslSpecification extends SigmaDslTesting ValUse(1, SPair(SByteArray, SPair(SByte, SInt))), 1.toByte ), - SCollection.getMethodByName("indexOf").withConcreteTypes(Map(STypeVar("IV") -> SByte)), + SCollectionMethods.getMethodByName("indexOf").withConcreteTypes(Map(STypeVar("IV") -> SByte)), Vector( SelectField.typed[Value[SByte.type]](ValUse(3, SPair(SByte, SInt)), 1.toByte), SelectField.typed[Value[SInt.type]](ValUse(3, SPair(SByte, SInt)), 2.toByte) @@ -8268,7 +8269,7 @@ class SigmaDslSpecification extends SigmaDslTesting FixedCostItem(SelectField), FixedCostItem(ValUse), FixedCostItem(SelectField), - FixedCostItem(SCollection.GetOrElseMethod, FixedCost(JitCost(30))) + FixedCostItem(SCollectionMethods.GetOrElseMethod, FixedCost(JitCost(30))) ) ) ) @@ -8333,7 +8334,7 @@ class SigmaDslSpecification extends SigmaDslTesting ValUse(1, SPair(SCollectionType(SInt), SPair(SInt, SInt))), 1.toByte ), - SCollection.getMethodByName("getOrElse").withConcreteTypes(Map(STypeVar("IV") -> SInt)), + SCollectionMethods.getMethodByName("getOrElse").withConcreteTypes(Map(STypeVar("IV") -> SInt)), Vector( SelectField.typed[Value[SInt.type]](ValUse(3, SPair(SInt, SInt)), 1.toByte), SelectField.typed[Value[SInt.type]](ValUse(3, SPair(SInt, SInt)), 2.toByte) @@ -8413,7 +8414,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - SeqCostItem(MethodDesc(SCollection.MapMethod), PerItemCost(JitCost(20), JitCost(1), 10), i) + SeqCostItem(MethodDesc(SCollectionMethods.MapMethod), PerItemCost(JitCost(20), JitCost(1), 10), i) ) ) ++ repeatPlusChunk(i) @@ -8445,7 +8446,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((1, SCollectionType(SInt))), MethodCall.typed[Value[SCollection[SInt.type]]]( ValUse(1, SCollectionType(SInt)), - SCollection.getMethodByName("map").withConcreteTypes( + SCollectionMethods.getMethodByName("map").withConcreteTypes( Map(STypeVar("IV") -> SInt, STypeVar("OV") -> SInt) ), Vector( @@ -8762,7 +8763,7 @@ class SigmaDslSpecification extends SigmaDslTesting ValUse(1, SPair(SCollectionType(SInt), SPair(SInt, SInt))), 1.toByte ), - SCollection.getMethodByName("slice").withConcreteTypes(Map(STypeVar("IV") -> SInt)), + SCollectionMethods.getMethodByName("slice").withConcreteTypes(Map(STypeVar("IV") -> SInt)), Vector( SelectField.typed[Value[SInt.type]](ValUse(3, SPair(SInt, SInt)), 1.toByte), SelectField.typed[Value[SInt.type]](ValUse(3, SPair(SInt, SInt)), 2.toByte) @@ -8831,7 +8832,7 @@ class SigmaDslSpecification extends SigmaDslTesting ValUse(1, SPair(SCollectionType(SInt), SCollectionType(SInt))), 1.toByte ), - SCollection.getMethodByName("append").withConcreteTypes(Map(STypeVar("IV") -> SInt)), + SCollectionMethods.getMethodByName("append").withConcreteTypes(Map(STypeVar("IV") -> SInt)), Vector( SelectField.typed[Value[SCollection[SInt.type]]]( ValUse(1, SPair(SCollectionType(SInt), SCollectionType(SInt))), @@ -8857,14 +8858,14 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - FixedCostItem(SOption.FilterMethod, FixedCost(JitCost(20))) + FixedCostItem(SOptionMethods.FilterMethod, FixedCost(JitCost(20))) ) ) val costDetails5 = TracedCost( traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - FixedCostItem(SOption.FilterMethod, FixedCost(JitCost(20))), + FixedCostItem(SOptionMethods.FilterMethod, FixedCost(JitCost(20))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -8875,14 +8876,14 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - FixedCostItem(SOption.MapMethod, FixedCost(JitCost(20))) + FixedCostItem(SOptionMethods.MapMethod, FixedCost(JitCost(20))) ) ) val costDetails7 = TracedCost( traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - FixedCostItem(SOption.MapMethod, FixedCost(JitCost(20))), + FixedCostItem(SOptionMethods.MapMethod, FixedCost(JitCost(20))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -8925,7 +8926,7 @@ class SigmaDslSpecification extends SigmaDslTesting Vector((1, SOption(SLong))), MethodCall.typed[Value[SOption[SLong.type]]]( ValUse(1, SOption(SLong)), - SOption.getMethodByName("filter").withConcreteTypes(Map(STypeVar("T") -> SLong)), + SOptionMethods.getMethodByName("filter").withConcreteTypes(Map(STypeVar("T") -> SLong)), Vector(FuncValue(Vector((3, SLong)), EQ(ValUse(3, SLong), LongConstant(1L)))), Map() ) @@ -8943,7 +8944,7 @@ class SigmaDslSpecification extends SigmaDslTesting Vector((1, SOption(SLong))), MethodCall.typed[Value[SOption[SLong.type]]]( ValUse(1, SOption(SLong)), - SOption.getMethodByName("map").withConcreteTypes( + SOptionMethods.getMethodByName("map").withConcreteTypes( Map(STypeVar("T") -> SLong, STypeVar("R") -> SLong) ), Vector( @@ -8962,14 +8963,14 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - FixedCostItem(SOption.FilterMethod, FixedCost(JitCost(20))) + FixedCostItem(SOptionMethods.FilterMethod, FixedCost(JitCost(20))) ) ) val costDetails2 = TracedCost( traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - FixedCostItem(SOption.FilterMethod, FixedCost(JitCost(20))), + FixedCostItem(SOptionMethods.FilterMethod, FixedCost(JitCost(20))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -8982,7 +8983,7 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - FixedCostItem(SOption.FilterMethod, FixedCost(JitCost(20))), + FixedCostItem(SOptionMethods.FilterMethod, FixedCost(JitCost(20))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -9008,7 +9009,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((1, SOption(SLong))), MethodCall.typed[Value[SOption[SLong.type]]]( ValUse(1, SOption(SLong)), - SOption.getMethodByName("filter").withConcreteTypes(Map(STypeVar("T") -> SLong)), + SOptionMethods.getMethodByName("filter").withConcreteTypes(Map(STypeVar("T") -> SLong)), Vector( FuncValue( Array((3, SLong)), @@ -9027,14 +9028,14 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - FixedCostItem(SOption.MapMethod, FixedCost(JitCost(20))) + FixedCostItem(SOptionMethods.MapMethod, FixedCost(JitCost(20))) ) ) val costDetails5 = TracedCost( traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - FixedCostItem(SOption.MapMethod, FixedCost(JitCost(20))), + FixedCostItem(SOptionMethods.MapMethod, FixedCost(JitCost(20))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -9047,7 +9048,7 @@ class SigmaDslSpecification extends SigmaDslTesting traceBase ++ Array( FixedCostItem(MethodCall), FixedCostItem(FuncValue), - FixedCostItem(SOption.MapMethod, FixedCost(JitCost(20))), + FixedCostItem(SOptionMethods.MapMethod, FixedCost(JitCost(20))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(Constant), @@ -9073,7 +9074,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((1, SOption(SLong))), MethodCall.typed[Value[SOption[SLong.type]]]( ValUse(1, SOption(SLong)), - SOption.getMethodByName("map").withConcreteTypes( + SOptionMethods.getMethodByName("map").withConcreteTypes( Map(STypeVar("T") -> SLong, STypeVar("R") -> SLong) ), Vector( @@ -9748,11 +9749,11 @@ class SigmaDslSpecification extends SigmaDslTesting SeqCostItem(CompanionDesc(BlockValue), PerItemCost(JitCost(1), JitCost(1), 10), 1), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - FixedCostItem(SContext.headersMethod, FixedCost(JitCost(15))), + FixedCostItem(SContextMethods.headersMethod, FixedCost(JitCost(15))), FixedCostItem(FuncValue.AddToEnvironmentDesc, FixedCost(JitCost(5))), FixedCostItem(ValUse), FixedCostItem(PropertyCall), - SeqCostItem(MethodDesc(SCollection.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), 1), + SeqCostItem(MethodDesc(SCollectionMethods.IndicesMethod), PerItemCost(JitCost(20), JitCost(2), 16), 1), FixedCostItem(Constant), FixedCostItem(ValUse), FixedCostItem(SizeOf), @@ -9811,7 +9812,7 @@ class SigmaDslSpecification extends SigmaDslTesting List(), MethodCall.typed[Value[SCollection[SHeader.type]]]( ValUse(1, SContext), - SContext.getMethodByName("headers"), + SContextMethods.getMethodByName("headers"), Vector(), Map() ) @@ -9821,7 +9822,7 @@ class SigmaDslSpecification extends SigmaDslTesting Slice( MethodCall.typed[Value[SCollection[SInt.type]]]( ValUse(3, SCollectionType(SHeader)), - SCollection.getMethodByName("indices").withConcreteTypes(Map(STypeVar("IV") -> SHeader)), + SCollectionMethods.getMethodByName("indices").withConcreteTypes(Map(STypeVar("IV") -> SHeader)), Vector(), Map() ), @@ -9842,7 +9843,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((6, SHeader)), MethodCall.typed[Value[SCollection[SByte.type]]]( ValUse(6, SHeader), - SHeader.getMethodByName("parentId"), + SHeaderMethods.getMethodByName("parentId"), Vector(), Map() ) @@ -9858,7 +9859,7 @@ class SigmaDslSpecification extends SigmaDslTesting Array((6, SHeader)), MethodCall.typed[Value[SCollection[SByte.type]]]( ValUse(6, SHeader), - SHeader.getMethodByName("id"), + SHeaderMethods.getMethodByName("id"), Vector(), Map() ) @@ -9921,7 +9922,7 @@ class SigmaDslSpecification extends SigmaDslTesting ValUse(3, SPair(SByteArray, SByteArray)), 1.toByte ), - SCollection.getMethodByName("zip").withConcreteTypes( + SCollectionMethods.getMethodByName("zip").withConcreteTypes( Map(STypeVar("IV") -> SByte, STypeVar("OV") -> SByte) ), Vector( @@ -9961,7 +9962,7 @@ class SigmaDslSpecification extends SigmaDslTesting ValUse(1, SPair(SByteArray2, SByteArray)), 1.toByte ), - SCollection.getMethodByName("fold").withConcreteTypes(Map(STypeVar("IV") -> SCollection(SByte), STypeVar("OV") -> SCollection(SByte))), + SCollectionMethods.getMethodByName("fold").withConcreteTypes(Map(STypeVar("IV") -> SCollection(SByte), STypeVar("OV") -> SCollection(SByte))), Vector( SelectField.typed[Value[SCollection[SByte.type]]]( ValUse(1, SPair(SByteArray2, SByteArray)), @@ -9975,7 +9976,7 @@ class SigmaDslSpecification extends SigmaDslTesting ValUse(3, SPair(SByteArray, SByteArray)), 1.toByte ), - SCollection.getMethodByName("zip").withConcreteTypes( + SCollectionMethods.getMethodByName("zip").withConcreteTypes( Map(STypeVar("IV") -> SByte, STypeVar("OV") -> SByte) ), Vector( @@ -9986,7 +9987,7 @@ class SigmaDslSpecification extends SigmaDslTesting ), Map() ), - SCollection.getMethodByName("map").withConcreteTypes( + SCollectionMethods.getMethodByName("map").withConcreteTypes( Map(STypeVar("IV") -> SPair(SByte, SByte), STypeVar("OV") -> SByte) ), Vector( @@ -10031,7 +10032,7 @@ class SigmaDslSpecification extends SigmaDslTesting // TODO v6.0: Add support of SFunc in TypeSerializer (see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/847) assertExceptionThrown( f.verifyCase(Coll[Int](), Expected(Success(Coll[Int]()), 0)), - exceptionLike[MatchError]("(SInt$) => SInt$ (of class sigmastate.SFunc)") + exceptionLike[MatchError]("(SInt$) => SInt$ (of class sigma.ast.SFunc)") ) } diff --git a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala index 4aff49761e..f7f276727c 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala @@ -18,12 +18,12 @@ import sigma.util.BenchmarkUtil import sigma.util.CollectionUtil._ import sigma.util.Extensions._ import sigma.util.StringUtil.StringUtilExtensions -import sigmastate.SType.AnyOps +import sigma.ast.SType.AnyOps import sigmastate.Values.{ByteArrayConstant, Constant, ConstantNode, ErgoTree, IntConstant, SValue} import sigmastate.crypto.DLogProtocol.{DLogProverInput, ProveDlog} import sigmastate.crypto.SigmaProtocolPrivateInput import sigmastate.eval.Extensions._ -import sigmastate.eval.{CompiletimeIRContext, CostingBox, CostingDataContext, Evaluation, IRContext, SigmaDsl} +import sigmastate.eval.{CompiletimeIRContext, CostingBox, CostingDataContext, IRContext, SigmaDsl} import sigmastate.helpers.TestingHelpers._ import sigmastate.helpers.{CompilerTestingCommons, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaPPrint} import sigmastate.interpreter.Interpreter.{ScriptEnv, VerificationResult} @@ -33,8 +33,8 @@ import sigmastate.serialization.ValueSerializer import sigmastate.serialization.generators.ObjectGenerators import sigmastate.utils.Helpers._ import sigmastate.utxo.{DeserializeContext, DeserializeRegister, GetVar, OptionGet} -import sigmastate.{SOption, SSigmaProp, SType, SigmaLeaf, eval} - +import sigma.ast.{SOption, SSigmaProp, SType} +import sigmastate.{SigmaLeaf, eval} import scala.collection.mutable import scala.reflect.ClassTag import scala.util.{Failure, Success, Try} diff --git a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala index cd7e15b841..fd012b3493 100644 --- a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala +++ b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala @@ -1,10 +1,11 @@ package sigmastate import scala.util.DynamicVariable -import sigmastate.lang.{TransformingSigmaBuilder, CompilerResult, CompilerSettings, SigmaCompiler} +import sigmastate.lang.{CompilerResult, CompilerSettings, SigmaCompiler, TransformingSigmaBuilder} import sigmastate.interpreter.Interpreter.ScriptEnv -import sigmastate.Values.{SigmaPropValue, SValue, Value, ErgoTree} +import sigmastate.Values.{ErgoTree, SValue, SigmaPropValue, Value} import org.ergoplatform.ErgoAddressEncoder.TestnetNetworkPrefix +import sigma.ast.SType import sigmastate.serialization.ValueSerializer import sigmastate.eval.IRContext import sigmastate.lang.Terms.ValueOps diff --git a/sc/shared/src/test/scala/sigmastate/ErgoTreeSpecification.scala b/sc/shared/src/test/scala/sigmastate/ErgoTreeSpecification.scala index 23406d9cb4..61445216b1 100644 --- a/sc/shared/src/test/scala/sigmastate/ErgoTreeSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/ErgoTreeSpecification.scala @@ -5,11 +5,11 @@ import org.ergoplatform.validation.{ValidationException, ValidationRules} import org.ergoplatform.{ErgoAddressEncoder, ErgoBox, ErgoLikeContext, Self} import sigma.data.RType.asType import sigma.data.{Nullable, RType} -import sigma.VersionContext -import sigmastate.SCollection.{SByteArray, checkValidFlatmap} +import sigma.{Evaluation, VersionContext} +import sigma.ast.SCollection.SByteArray import sigmastate.Values._ import sigma.VersionContext._ -import sigmastate.eval.{CostingBox, Evaluation, Profiler} +import sigmastate.eval.{CostingBox, Profiler} import sigmastate.exceptions.{CostLimitException, InterpreterException} import sigmastate.helpers.{ErgoLikeContextTesting, SigmaPPrint} import sigmastate.interpreter.{ErgoTreeEvaluator, EvalSettings} @@ -20,7 +20,9 @@ import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer import sigmastate.utils.Helpers.TryOps import sigmastate.utxo._ import sigma._ +import sigma.ast._ import sigma.{ContractsTestkit, SigmaDslTesting} +import sigmastate.SCollectionMethods.checkValidFlatmap /** Regression tests with ErgoTree related test vectors. @@ -228,14 +230,14 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { { // SNumericType.typeId is erroneously shadowed by SGlobal.typeId // this should be preserved in v3.x and fixed in v4.0 (SNumericType.typeId, Seq( - MInfo(methodId = 1, SGlobal.groupGeneratorMethod), - MInfo(2, SGlobal.xorMethod) + MInfo(methodId = 1, SGlobalMethods.groupGeneratorMethod), + MInfo(2, SGlobalMethods.xorMethod) ), true) }, { // SBigInt inherit methods from SNumericType.methods // however they are not resolvable via SBigInt.typeId - import SNumericType._ + import SNumericTypeMethods._ (SBigInt.typeId, Seq( MInfo(methodId = 1, ToByteMethod, isResolvableFromIds = false), MInfo(2, ToShortMethod, isResolvableFromIds = false), @@ -246,7 +248,7 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { MInfo(7, ToBitsMethod, isResolvableFromIds = false) ), true) }, - { import SGroupElement._ + { import SGroupElementMethods._ (SGroupElement.typeId, Seq( MInfo(2, GetEncodedMethod), MInfo(3, ExponentiateMethod), @@ -254,13 +256,13 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { MInfo(5, NegateMethod) ), true) }, - { import SSigmaProp._ + { import SSigmaPropMethods._ (SSigmaProp.typeId, Seq( MInfo(1, PropBytesMethod), MInfo(2, IsProvenMethod) // TODO v5.x (3h): this method must be removed (see https://github.com/ScorexFoundation/sigmastate-interpreter/pull/800) ), true) }, - { import SBox._ + { import SBoxMethods._ (SBox.typeId, Seq( MInfo(1, ValueMethod), MInfo(2, PropositionBytesMethod), @@ -274,7 +276,7 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { .zipWithIndex .map { case (m,i) => MInfo((8 + i + 1).toByte, m) }, true) }, - { import SAvlTree._ + { import SAvlTreeMethods._ (SAvlTree.typeId, Seq( MInfo(1, digestMethod), MInfo(2, enabledOperationsMethod), @@ -293,7 +295,7 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { MInfo(15, updateDigestMethod) ), true) }, - { import SHeader._ + { import SHeaderMethods._ (SHeader.typeId, Seq( MInfo(1, idMethod), MInfo(2, versionMethod), MInfo(3, parentIdMethod), MInfo(4, ADProofsRootMethod), MInfo(5, stateRootMethod), MInfo(6, transactionsRootMethod), @@ -302,14 +304,14 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { MInfo(13, powNonceMethod), MInfo(14, powDistanceMethod), MInfo(15, votesMethod) ), true) }, - { import SPreHeader._ + { import SPreHeaderMethods._ (SPreHeader.typeId, Seq( MInfo(1, versionMethod), MInfo(2, parentIdMethod), MInfo(3, timestampMethod), MInfo(4, nBitsMethod), MInfo(5, heightMethod), MInfo(6, minerPkMethod), MInfo(7, votesMethod) ), true) }, - { import SContext._ + { import SContextMethods._ (SContext.typeId, Seq( MInfo(1, dataInputsMethod), MInfo(2, headersMethod), MInfo(3, preHeaderMethod), MInfo(4, inputsMethod), MInfo(5, outputsMethod), MInfo(6, heightMethod), @@ -317,12 +319,12 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { MInfo(10, minerPubKeyMethod), MInfo(11, getVarMethod) ), true) }, - { import SGlobal._ + { import SGlobalMethods._ (SGlobal.typeId, Seq( MInfo(1, groupGeneratorMethod), MInfo(2, xorMethod) ), true) }, - { import SCollection._ + { import SCollectionMethods._ (SCollection.typeId, Seq( MInfo(1, SizeMethod), MInfo(2, GetOrElseMethod), @@ -364,7 +366,7 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { */ ), true) }, - { import SOption._ + { import SOptionMethods._ (SOption.typeId, Seq( MInfo(2, IsDefinedMethod), MInfo(3, GetMethod), @@ -384,7 +386,8 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { case Some(tyDesc) => assert(canHaveMethods, s"Type $tyDesc should NOT have methods") - tyDesc.methods.length shouldBe methods.length + val mc = MethodsContainer(tyDesc.typeId) + mc.methods.length shouldBe methods.length for (expectedMethod <- methods) { if (expectedMethod.isResolvableFromIds) { @@ -612,7 +615,7 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { def mkLambda(t: SType, mkBody: SValue => SValue) = { MethodCall( ValUse(1, SCollectionType(t)), - SCollection.getMethodByName("flatMap").withConcreteTypes( + SCollectionMethods.getMethodByName("flatMap").withConcreteTypes( Map(STypeVar("IV") -> t, STypeVar("OV") -> SByte) ), Vector(FuncValue(Vector((3, t)), mkBody(ValUse(3, t)))), @@ -625,7 +628,7 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { (SBox, x => ExtractBytes(x.asBox)), (SBox, x => ExtractBytesWithNoRef(x.asBox)), (SSigmaProp, x => SigmaPropBytes(x.asSigmaProp)), - (SBox, x => MethodCall(x, SBox.getMethodByName("id"), Vector(), Map())) + (SBox, x => MethodCall(x, SBoxMethods.getMethodByName("id"), Vector(), Map())) ).map { case (t, f) => mkLambda(t, f) } validLambdas.foreach { l => @@ -643,7 +646,7 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { // invalid MC like `boxes.flatMap(b => b.id, 10)` MethodCall( ValUse(1, SBox), - SCollection.getMethodByName("flatMap").withConcreteTypes( + SCollectionMethods.getMethodByName("flatMap").withConcreteTypes( Map(STypeVar("IV") -> SBox, STypeVar("OV") -> SByte) ), Vector( @@ -655,7 +658,7 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { // invalid MC like `boxes.flatMap((b,_) => b.id)` MethodCall( ValUse(1, SBox), - SCollection.getMethodByName("flatMap").withConcreteTypes( + SCollectionMethods.getMethodByName("flatMap").withConcreteTypes( Map(STypeVar("IV") -> SBox, STypeVar("OV") -> SByte) ), Vector( diff --git a/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala b/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala index ad5af68649..77a18188c1 100644 --- a/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala @@ -6,6 +6,7 @@ import scorex.util.ModifierId import sigmastate.Values.ErgoTree.{DefaultHeader, updateVersionBits} import sigmastate.Values._ import sigma.VersionContext.MaxSupportedScriptVersion +import sigma.ast.{SBoolean, SBox, SCollection, SType} import sigmastate.eval._ import sigmastate.exceptions.InterpreterException import sigmastate.helpers.{ErgoLikeContextTesting, ErgoLikeTestInterpreter} diff --git a/sc/shared/src/test/scala/sigmastate/SoftForkabilitySpecification.scala b/sc/shared/src/test/scala/sigmastate/SoftForkabilitySpecification.scala index c46b5a3119..b5680ec507 100644 --- a/sc/shared/src/test/scala/sigmastate/SoftForkabilitySpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/SoftForkabilitySpecification.scala @@ -4,7 +4,8 @@ import org.ergoplatform._ import org.ergoplatform.validation.ValidationRules._ import org.ergoplatform.validation._ import org.scalatest.BeforeAndAfterAll -import sigmastate.SPrimType.MaxPrimTypeCode +import sigma.ast.{SBoolean, SCollection, SContext, SFunc, SGlobal, SInt} +import sigma.ast.SPrimType.MaxPrimTypeCode import sigmastate.Values.ErgoTree.EmptyConstants import sigmastate.Values.{ByteArrayConstant, ErgoTree, IntConstant, NotReadyValueInt, UnparsedErgoTree, ValueCompanion} import sigmastate.exceptions.{InterpreterException, SerializerException} @@ -14,12 +15,13 @@ import sigmastate.interpreter.ErgoTreeEvaluator.DataEnv import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} import sigmastate.interpreter.{ContextExtension, ErgoTreeEvaluator, ProverResult} import sigmastate.lang.Terms._ -import sigmastate.serialization.OpCodes.{LastConstantCode, OpCode} +import sigmastate.serialization.ValueCodes.LastConstantCode import sigmastate.serialization.SigmaSerializer.startReader import sigmastate.serialization._ import sigmastate.utils.Helpers._ import sigmastate.utxo.DeserializeContext import sigma.{Colls, SigmaTestingData} +import sigmastate.serialization.ValueCodes.OpCode class SoftForkabilitySpecification extends SigmaTestingData with CompilerTestingCommons diff --git a/sc/shared/src/test/scala/sigmastate/TypesSpecification.scala b/sc/shared/src/test/scala/sigmastate/TypesSpecification.scala index 3d5edf22f2..64a4d8a0d5 100644 --- a/sc/shared/src/test/scala/sigmastate/TypesSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/TypesSpecification.scala @@ -1,9 +1,10 @@ package sigmastate import sigma.Environment -import sigmastate.SType.isValueOfType +import sigma.ast.SType.isValueOfType import sigmastate.eval.{CSigmaProp, CostingSigmaDslBuilder} import sigma.SigmaTestingData +import sigma.ast._ class TypesSpecification extends SigmaTestingData { diff --git a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala index 5d949d65fc..7be159757c 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala @@ -5,6 +5,7 @@ import org.ergoplatform.validation.ValidationSpecification import org.ergoplatform.{Context => _, _} import scalan.BaseCtxTests import sigma.VersionContext +import sigma.ast.SType import sigmastate.Values.{BigIntArrayConstant, EvaluatedValue, SValue, SigmaPropConstant, Value} import sigmastate.helpers.TestingHelpers._ import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting} @@ -13,7 +14,7 @@ import sigmastate.interpreter.{ContextExtension, ErgoTreeEvaluator} import sigmastate.lang.Terms.ValueOps import sigmastate.lang.{CompilerResult, CompilerSettings, LangTests, SigmaCompiler} import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer -import sigmastate.{AvlTreeData, CompilerTestsBase, SType} +import sigmastate.{AvlTreeData, CompilerTestsBase} import sigma.{ContractsTestkit, Context => DContext} import scala.annotation.unused @@ -30,7 +31,7 @@ trait ErgoScriptTestkit extends ContractsTestkit with LangTests import Context._ import Liftables._ - override lazy val compiler = new SigmaCompiler(CompilerSettings( + override lazy val compiler = SigmaCompiler(CompilerSettings( TestnetNetworkPrefix, IR.builder, lowerMethodCalls = true diff --git a/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala b/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala index ed9733b57c..6d80e20734 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala @@ -1,13 +1,14 @@ package sigmastate.eval -import org.ergoplatform.{Height, Outputs, Self, Inputs} +import org.ergoplatform.{Height, Inputs, Outputs, Self} import sigmastate._ -import sigmastate.Values.{LongConstant, FuncValue, BlockValue, SigmaPropConstant, IntConstant, ValDef, ValUse} +import sigmastate.Values.{BlockValue, FuncValue, IntConstant, LongConstant, SigmaPropConstant, ValDef, ValUse} import sigmastate.helpers.ContextEnrichingTestProvingInterpreter import sigmastate.interpreter.Interpreter._ import scalan.BaseCtxTests +import sigma.ast.{SBox, SFunc, SInt, SLong, SSigmaProp, SType} import sigmastate.lang.LangTests -import sigmastate.lang.Terms.{ValueOps, Apply} +import sigmastate.lang.Terms.{Apply, ValueOps} import sigmastate.utxo._ class ErgoTreeBuildingTest extends BaseCtxTests diff --git a/sc/shared/src/test/scala/sigmastate/eval/EvaluationTest.scala b/sc/shared/src/test/scala/sigmastate/eval/EvaluationTest.scala index 9aefb272b6..c2d6143748 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/EvaluationTest.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/EvaluationTest.scala @@ -6,6 +6,7 @@ import sigmastate.helpers.ContextEnrichingTestProvingInterpreter import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter._ import scalan.BaseCtxTests +import sigma.ast.SSigmaProp import sigmastate.lang.LangTests import sigma.util.BenchmarkUtil._ import sigmastate._ diff --git a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala index ed86bb86ed..7ebc8f907b 100644 --- a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala +++ b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala @@ -8,7 +8,8 @@ import org.scalacheck.Gen import org.scalatest.Assertion import sigma.util.BenchmarkUtil import scalan.TestContexts -import sigma.{Colls, TestUtils} +import sigma.ast.{SOption, SType} +import sigma.{Colls, Evaluation, TestUtils} import sigma.data.RType import sigmastate.Values.{Constant, ErgoTree, SValue, SigmaBoolean, SigmaPropValue} import sigmastate.eval._ @@ -19,7 +20,7 @@ import sigmastate.interpreter.Interpreter.ScriptEnv import sigmastate.interpreter._ import sigmastate.lang.{CompilerSettings, SigmaCompiler, Terms} import sigmastate.serialization.SigmaSerializer -import sigmastate.{CompilerTestsBase, JitCost, SOption, SType} +import sigmastate.{CompilerTestsBase, JitCost} import scala.language.implicitConversions import scala.reflect.ClassTag diff --git a/sc/shared/src/test/scala/sigmastate/helpers/SigmaPPrint.scala b/sc/shared/src/test/scala/sigmastate/helpers/SigmaPPrint.scala index 690630d327..ef92f62d51 100644 --- a/sc/shared/src/test/scala/sigmastate/helpers/SigmaPPrint.scala +++ b/sc/shared/src/test/scala/sigmastate/helpers/SigmaPPrint.scala @@ -4,9 +4,10 @@ import org.ergoplatform.ErgoBox import org.ergoplatform.ErgoBox.RegisterId import org.ergoplatform.settings.ErgoAlgos import pprint.{PPrinter, Tree} +import sigma.ast.SCollection.{SBooleanArray, SByteArray, SByteArray2} +import sigma.ast._ import sigma.data.{CollType, PrimitiveType} import sigma.{Coll, GroupElement} -import sigmastate.SCollection._ import sigmastate.Values.{ConstantNode, ErgoTree, FuncValue, ValueCompanion} import sigmastate._ import sigmastate.crypto.CryptoConstants.EcPointType @@ -211,11 +212,11 @@ object SigmaPPrint extends PPrinter { Tree.Literal(s"FuncValue.AddToEnvironmentDesc") case MethodDesc(method) => Tree.Apply("MethodDesc", Seq(methodLiteral(method)).iterator) - case sigmastate.SGlobal => + case SGlobal => Tree.Literal(s"SGlobal") - case sigmastate.SCollection => + case SCollection => Tree.Literal(s"SCollection") - case sigmastate.SOption => + case SOption => Tree.Literal(s"SOption") case t: STypeCompanion if t.isInstanceOf[SType] => Tree.Literal(s"S${t.typeName}") diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaBinderTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaBinderTest.scala index 397c5c5e5d..94d3467598 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaBinderTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaBinderTest.scala @@ -5,6 +5,7 @@ import org.ergoplatform.ErgoAddressEncoder._ import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import sigma.ast.{NoType, SBoolean, SBox, SCollection, SFunc, SInt, SLong, STuple} import sigmastate.Values._ import sigmastate._ import sigmastate.interpreter.Interpreter.ScriptEnv @@ -167,7 +168,7 @@ class SigmaBinderTest extends AnyPropSpec with ScalaCheckPropertyChecks with Mat property("predefined primitives") { bind(env, "{ (box: Box) => box.value }") shouldBe Lambda(IndexedSeq("box" -> SBox), NoType, Select(Ident("box"), "value")) - bind(env, "{ (box: Box) => box.propositionBytes }") shouldBe Lambda(IndexedSeq("box" -> SBox), NoType, Select(Ident("box"), SBox.PropositionBytes)) + bind(env, "{ (box: Box) => box.propositionBytes }") shouldBe Lambda(IndexedSeq("box" -> SBox), NoType, Select(Ident("box"), SBoxMethods.PropositionBytes)) bind(env, "{ (box: Box) => box.bytes }") shouldBe Lambda(IndexedSeq("box" -> SBox), NoType, Select(Ident("box"), "bytes")) bind(env, "{ (box: Box) => box.id }") shouldBe Lambda(IndexedSeq("box" -> SBox), NoType, Select(Ident("box"), "id")) } diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala index 129f096d85..0f0d6c8688 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala @@ -3,6 +3,7 @@ package sigmastate.lang import org.ergoplatform.ErgoAddressEncoder.TestnetNetworkPrefix import org.ergoplatform._ import scorex.util.encode.Base58 +import sigma.ast.{SAvlTree, SBoolean, SBox, SByte, SCollection, SInt, SSigmaProp, SType} import sigmastate.Values._ import sigmastate._ import sigmastate.exceptions.{GraphBuildingException, InvalidArguments, TyperException} @@ -80,8 +81,8 @@ class SigmaCompilerTest extends CompilerTestingCommons with LangTests with Objec } property("global methods") { - comp(env, "{ groupGenerator }") shouldBe MethodCall(Global, SGlobal.groupGeneratorMethod, IndexedSeq(), Terms.EmptySubst) - comp(env, "{ Global.groupGenerator }") shouldBe MethodCall(Global, SGlobal.groupGeneratorMethod, IndexedSeq(), Terms.EmptySubst) + comp(env, "{ groupGenerator }") shouldBe MethodCall(Global, SGlobalMethods.groupGeneratorMethod, IndexedSeq(), Terms.EmptySubst) + comp(env, "{ Global.groupGenerator }") shouldBe MethodCall(Global, SGlobalMethods.groupGeneratorMethod, IndexedSeq(), Terms.EmptySubst) comp(env, "{ Global.xor(arr1, arr2) }") shouldBe Xor(ByteArrayConstant(arr1), ByteArrayConstant(arr2)) comp(env, "{ xor(arr1, arr2) }") shouldBe Xor(ByteArrayConstant(arr1), ByteArrayConstant(arr2)) } @@ -221,24 +222,24 @@ class SigmaCompilerTest extends CompilerTestingCommons with LangTests with Objec comp("Coll(true, false).indices") shouldBe mkMethodCall( ConcreteCollection.fromItems(TrueLeaf, FalseLeaf), - SCollection.IndicesMethod.withConcreteTypes(Map(SCollection.tIV -> SBoolean)), + SCollectionMethods.IndicesMethod.withConcreteTypes(Map(SCollection.tIV -> SBoolean)), Vector() ) } property("SBox.tokens") { comp("SELF.tokens") shouldBe - mkMethodCall(Self, SBox.tokensMethod, IndexedSeq()) + mkMethodCall(Self, SBoxMethods.tokensMethod, IndexedSeq()) } property("SContext.dataInputs") { comp("CONTEXT.dataInputs") shouldBe - mkMethodCall(Context, SContext.dataInputsMethod, IndexedSeq()) + mkMethodCall(Context, SContextMethods.dataInputsMethod, IndexedSeq()) } property("SAvlTree.digest") { comp("getVar[AvlTree](1).get.digest") shouldBe - mkMethodCall(GetVar(1.toByte, SAvlTree).get, SAvlTree.digestMethod, IndexedSeq()) + mkMethodCall(GetVar(1.toByte, SAvlTree).get, SAvlTreeMethods.digestMethod, IndexedSeq()) } property("SGroupElement.exp") { @@ -250,7 +251,7 @@ class SigmaCompilerTest extends CompilerTestingCommons with LangTests with Objec property("SOption.map") { comp("getVar[Int](1).map({(i: Int) => i + 1})") shouldBe mkMethodCall(GetVarInt(1), - SOption.MapMethod.withConcreteTypes(Map(SType.tT -> SInt, SType.tR -> SInt)), + SOptionMethods.MapMethod.withConcreteTypes(Map(SType.tT -> SInt, SType.tR -> SInt)), IndexedSeq(FuncValue( Vector((1, SInt)), Plus(ValUse(1, SInt), IntConstant(1)))), Map() @@ -260,7 +261,7 @@ class SigmaCompilerTest extends CompilerTestingCommons with LangTests with Objec property("SOption.filter") { comp("getVar[Int](1).filter({(i: Int) => i > 0})") shouldBe mkMethodCall(GetVarInt(1), - SOption.FilterMethod.withConcreteTypes(Map(SType.tT -> SInt)), + SOptionMethods.FilterMethod.withConcreteTypes(Map(SType.tT -> SInt)), IndexedSeq(FuncValue( Vector((1, SInt)), GT(ValUse(1, SInt), IntConstant(0)))), Map() @@ -271,7 +272,7 @@ class SigmaCompilerTest extends CompilerTestingCommons with LangTests with Objec comp("Coll(1, 2).patch(1, Coll(3), 1)") shouldBe mkMethodCall( ConcreteCollection.fromItems(IntConstant(1), IntConstant(2)), - SCollection.PatchMethod.withConcreteTypes(Map(SCollection.tIV -> SInt)), + SCollectionMethods.PatchMethod.withConcreteTypes(Map(SCollection.tIV -> SInt)), Vector(IntConstant(1), ConcreteCollection.fromItems(IntConstant(3)), IntConstant(1)), Map()) } @@ -280,7 +281,7 @@ class SigmaCompilerTest extends CompilerTestingCommons with LangTests with Objec comp("Coll(1, 2).updated(1, 1)") shouldBe mkMethodCall( ConcreteCollection.fromItems(IntConstant(1), IntConstant(2)), - SCollection.UpdatedMethod.withConcreteTypes(Map(SCollection.tIV -> SInt)), + SCollectionMethods.UpdatedMethod.withConcreteTypes(Map(SCollection.tIV -> SInt)), Vector(IntConstant(1), IntConstant(1)), Map()) } @@ -289,7 +290,7 @@ class SigmaCompilerTest extends CompilerTestingCommons with LangTests with Objec comp("Coll(1, 2).updateMany(Coll(1), Coll(3))") shouldBe mkMethodCall( ConcreteCollection.fromItems(IntConstant(1), IntConstant(2)), - SCollection.UpdateManyMethod.withConcreteTypes(Map(SCollection.tIV -> SInt)), + SCollectionMethods.UpdateManyMethod.withConcreteTypes(Map(SCollection.tIV -> SInt)), Vector(ConcreteCollection.fromItems(IntConstant(1)), ConcreteCollection.fromItems(IntConstant(3))), Map()) } @@ -298,7 +299,7 @@ class SigmaCompilerTest extends CompilerTestingCommons with LangTests with Objec comp("Coll(1, 2).indexOf(1, 0)") shouldBe mkMethodCall( ConcreteCollection.fromItems(IntConstant(1), IntConstant(2)), - SCollection.IndexOfMethod.withConcreteTypes(Map(SCollection.tIV -> SInt)), + SCollectionMethods.IndexOfMethod.withConcreteTypes(Map(SCollection.tIV -> SInt)), Vector(IntConstant(1), IntConstant(0)), Map()) } @@ -307,7 +308,7 @@ class SigmaCompilerTest extends CompilerTestingCommons with LangTests with Objec comp("Coll(1, 2).zip(Coll(1, 1))") shouldBe mkMethodCall( ConcreteCollection.fromItems(IntConstant(1), IntConstant(2)), - SCollection.ZipMethod.withConcreteTypes(Map(SCollection.tIV -> SInt, SCollection.tOV -> SInt)), + SCollectionMethods.ZipMethod.withConcreteTypes(Map(SCollection.tIV -> SInt, SCollection.tOV -> SInt)), Vector(ConcreteCollection.fromItems(IntConstant(1), IntConstant(1))) ) } diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala index b12938db03..90c54def15 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala @@ -6,9 +6,10 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import sigma.Colls -import sigmastate.SCollection._ +import sigma.ast.SCollection._ import sigmastate.Values._ import sigmastate._ +import sigma.ast._ import sigmastate.crypto.CryptoConstants import sigmastate.crypto.DLogProtocol.{DLogProverInput, ProveDlog} import sigmastate.exceptions.TyperException diff --git a/sc/shared/src/test/scala/sigmastate/serialization/DeserializationResilience.scala b/sc/shared/src/test/scala/sigmastate/serialization/DeserializationResilience.scala index 52ef46c642..a146dcd00e 100644 --- a/sc/shared/src/test/scala/sigmastate/serialization/DeserializationResilience.scala +++ b/sc/shared/src/test/scala/sigmastate/serialization/DeserializationResilience.scala @@ -9,6 +9,7 @@ import scorex.crypto.authds.avltree.batch.{BatchAVLProver, Insert} import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.util.serialization.{Reader, VLQByteBufferReader} +import sigma.ast.{SBoolean, SInt} import sigma.{Colls, Environment} import sigmastate.Values.{BlockValue, GetVarInt, IntConstant, SValue, SigmaBoolean, SigmaPropValue, Tuple, ValDef, ValUse} import sigmastate._ diff --git a/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala b/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala index c4d8ebf13d..2ccabd953a 100644 --- a/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala @@ -4,10 +4,12 @@ import java.math.BigInteger import org.ergoplatform.ErgoBox import org.ergoplatform.validation.ValidationException import org.ergoplatform.validation.ValidationRules.CheckDeserializedScriptIsSigmaProp +import sigma.ast.SInt +import sigma.data.CBigInt import sigmastate.Values.{BigIntConstant, ByteConstant, ConstantPlaceholder, ErgoTree, IntConstant, ShortConstant, SigmaPropValue, UnparsedErgoTree} import sigmastate._ -import sigmastate.eval.{CBigInt, IRContext} -import sigmastate.exceptions.{SerializerException, ReaderPositionLimitExceeded} +import sigmastate.eval.IRContext +import sigmastate.exceptions.{ReaderPositionLimitExceeded, SerializerException} import sigmastate.helpers.CompilerTestingCommons import sigmastate.serialization.ErgoTreeSerializer.DefaultSerializer import sigmastate.utxo.{DeserializeContext, DeserializeRegister} diff --git a/sc/shared/src/test/scala/sigmastate/utils/SpecGen.scala b/sc/shared/src/test/scala/sigmastate/utils/SpecGen.scala index 7eccb1dd00..09b45220e9 100644 --- a/sc/shared/src/test/scala/sigmastate/utils/SpecGen.scala +++ b/sc/shared/src/test/scala/sigmastate/utils/SpecGen.scala @@ -2,7 +2,8 @@ package sigmastate.utils import sigma.util.PrintExtensions.IterableExtensions import sigmastate._ -import sigmastate.eval.Evaluation._ +import sigma.Evaluation._ +import sigma.ast.{SBigInt, SBoolean, SCollection, SEmbeddable, SGlobal, SGroupElement, SNumericType, SOption, SPrimType, SString, SType, STypeCompanion} import sigma.util.Extensions.ByteOps import sigma.util.CollectionUtil import sigma.util.PrintExtensions._ @@ -10,8 +11,8 @@ import sigmastate.Values._ import sigmastate.lang.SigmaPredef.{PredefinedFunc, PredefinedFuncRegistry} import sigmastate.lang.StdSigmaBuilder import sigmastate.lang.Terms.{MethodCall, PropertyCall} -import sigmastate.serialization.OpCodes.OpCode -import sigmastate.serialization.{OpCodes, ValueSerializer} +import sigmastate.serialization.ValueCodes.OpCode +import sigmastate.serialization.{OpCodes, ValueCodes, ValueSerializer} import sigmastate.utxo.{SelectField, SigmaPropIsProven} object SpecGenUtils { @@ -30,7 +31,7 @@ trait SpecGen { args: Seq[ArgInfo], op: Either[PredefinedFunc, SMethod]) def collectSerializers(): Seq[ValueSerializer[_ <: Values.Value[SType]]] = { - ((OpCodes.LastConstantCode + 1) to 255).collect { + ((ValueCodes.LastConstantCode + 1) to 255).collect { case i if ValueSerializer.serializers(i.toByte) != null => val ser = ValueSerializer.serializers(i.toByte) assert(i == ser.opDesc.opCode.toUByte) @@ -39,7 +40,7 @@ trait SpecGen { } def collectFreeCodes(): Seq[Int] = { - ((OpCodes.LastConstantCode + 1) to 255).collect { + ((ValueCodes.LastConstantCode + 1) to 255).collect { case i if ValueSerializer.serializers(i.toByte) == null => i } } @@ -47,7 +48,8 @@ trait SpecGen { def collectMethods(): Seq[SMethod] = { for { tc <- typesWithMethods.sortBy(_.typeId) - m <- tc.methods.sortBy(_.methodId) + mc = MethodsContainer(tc.typeId) + m <- mc.methods.sortBy(_.methodId) } yield m } @@ -215,7 +217,8 @@ trait SpecGen { } def printMethods(tc: STypeCompanion) = { - val methodSubsections = for { m <- tc.methods.sortBy(_.methodId) } yield { + val mc = MethodsContainer(tc.typeId) + val methodSubsections = for { m <- mc.methods.sortBy(_.methodId) } yield { methodSubsection(tc.typeName, m) } val res = methodSubsections.mkString("\n\n") diff --git a/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala index 5133692685..769bf25423 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala @@ -5,19 +5,20 @@ import org.ergoplatform._ import org.ergoplatform.dsl.{ContractSpec, SigmaContractSyntax, TestContractSpec} import scorex.crypto.authds.avltree.batch._ import scorex.crypto.authds.{ADKey, ADValue, SerializedAdProof} -import scorex.crypto.hash.{Digest32, Blake2b256} -import sigmastate.SCollection.SByteArray +import scorex.crypto.hash.{Blake2b256, Digest32} +import sigma.ast.SCollection.SByteArray import sigmastate.Values._ import sigmastate._ import sigmastate.eval.{CSigmaProp, IRContext} import sigmastate.eval._ import sigmastate.eval.Extensions._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, CompilerTestingCommons} +import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter.ScriptNameProp import sigmastate.interpreter.ProverResult import sigmastate.lang.Terms._ import sigma.Coll +import sigma.ast.SAvlTree import sigma.{AvlTree, Context} @@ -204,7 +205,7 @@ class AVLTreeScriptsSpecification extends CompilerTestingCommons val propExp = IR.builder.mkMethodCall( ExtractRegisterAs[SAvlTree.type](Self, reg1).get, - SAvlTree.containsMethod, + SAvlTreeMethods.containsMethod, IndexedSeq(ByteArrayConstant(key), ByteArrayConstant(proof)) ).asBoolValue.toSigmaProp prop shouldBe propExp @@ -320,7 +321,7 @@ class AVLTreeScriptsSpecification extends CompilerTestingCommons val propExp = IR.builder.mkMethodCall( ExtractRegisterAs[SAvlTree.type](Self, reg1).get, - SAvlTree.containsMethod, + SAvlTreeMethods.containsMethod, IndexedSeq(ExtractRegisterAs[SByteArray](Self, reg2).get, GetVarByteArray(proofId).get) ).asBoolValue.toSigmaProp prop shouldBe propExp diff --git a/sc/shared/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala index eddd607178..a409e98fe1 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala @@ -4,7 +4,7 @@ import java.math.BigInteger import org.ergoplatform.ErgoBox.{AdditionalRegisters, R6, R8} import org.ergoplatform._ import sigma.data.RType -import sigmastate.SCollection.SByteArray +import sigma.ast.SCollection.SByteArray import sigmastate.Values._ import sigmastate._ import sigmastate.eval.Extensions._ @@ -12,7 +12,8 @@ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingIn import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter._ import sigmastate.lang.Terms._ -import SType.AnyOps +import sigma.ast.SType.AnyOps +import sigma.ast._ import sigmastate.crypto.CryptoConstants import sigmastate.eval.{CAnyValue, InvalidType} import sigmastate.interpreter.ContextExtension.VarBinding diff --git a/sc/shared/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala index 54f0d1dc04..5696163fc1 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala @@ -2,11 +2,13 @@ package sigmastate.utxo import sigmastate.Values._ import sigmastate._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, CompilerTestingCommons} +import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ import sigmastate.lang.Terms._ import org.ergoplatform._ -import sigmastate.SCollection._ +import sigma.ast.SCollection._ +import sigma.ast._ +import sigmastate.SCollectionMethods.{FlatMapMethod, IndexOfMethod, IndicesMethod, PatchMethod, UpdateManyMethod, UpdatedMethod} import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} import sigmastate.serialization.OpCodes._ import sigmastate.utils.Helpers._ @@ -531,7 +533,7 @@ class CollectionOperationsSpecification extends CompilerTestingCommons assertProof("OUTPUTS.zip(INPUTS).size == 2", EQ( SizeOf(MethodCall(Outputs, - SCollection.ZipMethod.withConcreteTypes(Map(SCollection.tIV -> SBox, SCollection.tOV -> SBox)), + SCollectionMethods.ZipMethod.withConcreteTypes(Map(SCollection.tIV -> SBox, SCollection.tOV -> SBox)), Vector(Inputs), Map()).asCollection[STuple]), IntConstant(2)), diff --git a/sc/shared/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala index 58bbb522c6..be105d3b8a 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala @@ -6,9 +6,10 @@ import org.ergoplatform._ import org.ergoplatform.validation.ValidationException import org.scalatest.TryValues._ import scorex.crypto.hash.Blake2b256 -import sigmastate.SCollection.SByteArray +import sigma.ast.SCollection.SByteArray import sigmastate.Values._ import sigmastate._ +import sigma.ast._ import sigmastate.eval._ import sigmastate.eval.Extensions._ import sigmastate.interpreter.Interpreter._ diff --git a/sc/shared/src/test/scala/sigmastate/utxo/SigmaCompilerSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/SigmaCompilerSpecification.scala index ffbb02dd98..07565bbff9 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/SigmaCompilerSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/SigmaCompilerSpecification.scala @@ -1,11 +1,12 @@ package sigmastate.utxo +import sigma.ast.SType import sigmastate.Values._ import sigmastate.eval.CAnyValue import sigmastate.helpers.CompilerTestingCommons import sigmastate.interpreter.Interpreter.ScriptEnv import sigmastate.lang.Terms._ -import sigmastate.{GE, ModQ, SType} +import sigmastate.{GE, ModQ} /** * Specification for compile function diff --git a/sc/shared/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala index 31536a76fd..ea1ed7dcc3 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala @@ -1,9 +1,10 @@ package sigmastate.utxo +import sigma.ast.SSigmaProp import sigmastate.crypto.DLogProtocol.{DLogProverInput, ProveDlog} import sigmastate.Values.{ConcreteCollection, FalseLeaf, IntConstant, SigmaPropConstant, SigmaPropValue, TrueLeaf} import sigmastate._ -import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTransactionTesting, CompilerTestingCommons} +import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTransactionTesting} import sigmastate.exceptions.GraphBuildingException class ThresholdSpecification extends CompilerTestingCommons diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala index b8fe0a8410..b80794c3f2 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala @@ -6,8 +6,9 @@ import sigmastate.helpers.CompilerTestingCommons import org.ergoplatform.dsl.ContractSyntax.Token import org.ergoplatform.dsl.TestContractSpec import scorex.crypto.hash.Blake2b256 -import sigmastate.SCollection.SByteArray +import sigma.ast.SCollection.SByteArray import sigmastate._ +import sigma.ast._ import sigmastate.Values.{BlockValue, ByteArrayConstant, LongConstant, ValDef, ValUse, Value} import sigmastate.eval.{CSigmaProp, Digest32Coll} import sigmastate.eval.Extensions._ diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala index ef004f602a..e5603342f3 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala @@ -3,6 +3,7 @@ package sigmastate.utxo.examples import org.ergoplatform.Height import scorex.crypto.hash.Blake2b256 import scorex.utils.Random +import sigma.ast.{SBoolean, SByte, SCollection} import sigmastate.Values._ import sigmastate._ import sigmastate.interpreter.Interpreter._ diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala index a6c612a037..a9db5642cc 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala @@ -3,6 +3,7 @@ package sigmastate.utxo.examples import org.ergoplatform._ import org.ergoplatform.settings.ErgoAlgos import sigma.Colls +import sigma.ast.{SBoolean, SBox, SInt, SLong, SOption} import sigmastate.Values.{BlockValue, ErgoTree, IntConstant, LongConstant, ValDef, ValUse} import sigmastate._ import sigmastate.eval._ diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala index 77918e453a..5f89ac5129 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala @@ -6,9 +6,10 @@ import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash import scorex.crypto.hash.{Blake2b256, Digest32} import sigma.Colls -import sigmastate.SCollection.SByteArray +import sigma.ast.SCollection.SByteArray import sigmastate.Values._ import sigmastate._ +import sigma.ast._ import sigmastate.eval._ import sigmastate.lang.Terms._ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} @@ -89,7 +90,7 @@ class FsmExampleSpecification extends CompilerTestingCommons val isMember = OptionIsDefined( IR.builder.mkMethodCall( OptionGet(ExtractRegisterAs[SAvlTree.type](Self, fsmDescRegister)), - SAvlTree.getMethod, + SAvlTreeMethods.getMethod, IndexedSeq(Append( ConcreteCollection.fromItems[SByte.type]( OptionGet(ExtractRegisterAs[SByte.type](Self, currentStateRegister)), diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala index 95899f0aa9..c36982d947 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala @@ -9,6 +9,7 @@ import scorex.crypto.authds.avltree.batch._ import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash.{Blake2b256, Digest32} import sigma.Colls +import sigma.ast.SByte import sigmastate.Values._ import sigmastate._ import sigmastate.crypto.CryptoConstants diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala index 54d2ec0241..15605481db 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala @@ -4,7 +4,8 @@ import org.ergoplatform._ import scorex.crypto.authds.avltree.batch.{BatchAVLProver, Insert, Lookup} import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash.{Blake2b256, Digest32} -import sigmastate.SCollection.SByteArray +import sigma.ast.{SAvlTree, SBoolean, SLong} +import sigma.ast.SCollection.SByteArray import sigmastate.Values._ import sigmastate._ import sigmastate.eval.Extensions.ArrayOps @@ -96,7 +97,7 @@ class MASTExampleSpecification extends CompilerTestingCommons val merklePathToScript = OptionIsDefined( IR.builder.mkMethodCall( ExtractRegisterAs[SAvlTree.type](Self, reg1).get, - SAvlTree.getMethod, + SAvlTreeMethods.getMethod, IndexedSeq( CalcBlake2b256(GetVarByteArray(scriptId).get), GetVarByteArray(proofId).get)).asOption[SByteArray] diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala index 8566ce437e..eb76496c82 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala @@ -5,9 +5,10 @@ import org.ergoplatform.ErgoBox.RegisterId import scorex.crypto.authds.avltree.batch.{BatchAVLProver, Insert, Lookup} import scorex.crypto.authds.{ADKey, ADValue} import scorex.crypto.hash.{Blake2b256, Digest32} -import sigmastate.SCollection.SByteArray +import sigma.ast.SCollection.SByteArray import sigmastate.Values._ import sigmastate._ +import sigma.ast._ import sigmastate.eval._ import sigmastate.lang.Terms._ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} @@ -135,7 +136,7 @@ class OracleExamplesSpecification extends CompilerTestingCommons val oracleProp = SigmaAnd( OptionIsDefined(IR.builder.mkMethodCall( - LastBlockUtxoRootHash, SAvlTree.getMethod, + LastBlockUtxoRootHash, SAvlTreeMethods.getMethod, IndexedSeq(ExtractId(GetVarBox(22: Byte).get), GetVarByteArray(23: Byte).get)).asOption[SByteArray]), EQ(extract[SByteArray](ErgoBox.ScriptRegId), ByteArrayConstant(ErgoTree.fromSigmaBoolean(oraclePubKey).bytes)), EQ(Exponentiate(GroupGenerator, extract[SBigInt.type](reg3)), diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala index 00b25ba8e1..51644ce34d 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala @@ -4,6 +4,7 @@ import org.ergoplatform._ import scorex.crypto.hash.Blake2b256 import scorex.util._ import sigma.Colls +import sigma.ast.{SBoolean, SByte, SInt, SLong} import sigmastate.Values._ import sigmastate._ import sigmastate.eval._ diff --git a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala index b2ffd664e8..4fac299405 100644 --- a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala +++ b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala @@ -2,27 +2,29 @@ package org.ergoplatform.sdk.js import org.ergoplatform.ErgoBox._ import org.ergoplatform.sdk.JavaHelpers.UniversalConverter -import org.ergoplatform.sdk.{Iso, ExtendedInputBox} +import org.ergoplatform.sdk.{ExtendedInputBox, Iso} import org.ergoplatform.sdk.wallet.protocol.context import org.ergoplatform._ -import sigma.data.RType +import org.ergoplatform.sdk.Iso.inverseIso +import sigma.data.{CBigInt, Iso, RType} import scorex.crypto.authds.ADKey import scorex.util.ModifierId import scorex.util.encode.Base16 import sigmastate.Values.{Constant, GroupElementConstant} import sigmastate.eval.Extensions.ArrayOps -import sigmastate.eval.{CBigInt, Digest32Coll, Evaluation, CAvlTree, CGroupElement, CPreHeader, CHeader} +import sigmastate.eval.{CAvlTree, CGroupElement, CHeader, CPreHeader, Digest32Coll} import sigmastate.fleetSdkCommon.distEsmTypesBoxesMod.Box import sigmastate.fleetSdkCommon.distEsmTypesCommonMod.HexString import sigmastate.fleetSdkCommon.distEsmTypesRegistersMod.NonMandatoryRegisters import sigmastate.fleetSdkCommon.distEsmTypesTokenMod.TokenAmount -import sigmastate.fleetSdkCommon.distEsmTypesTransactionsMod.{UnsignedTransaction, SignedTransaction} -import sigmastate.fleetSdkCommon.{distEsmTypesProverResultMod => proverResultMod, distEsmTypesContextExtensionMod => contextExtensionMod, distEsmTypesInputsMod => inputsMod, distEsmTypesBoxesMod => boxesMod, distEsmTypesCommonMod => commonMod, distEsmTypesRegistersMod => registersMod, distEsmTypesTokenMod => tokenMod} +import sigmastate.fleetSdkCommon.distEsmTypesTransactionsMod.{SignedTransaction, UnsignedTransaction} +import sigmastate.fleetSdkCommon.{distEsmTypesBoxesMod => boxesMod, distEsmTypesCommonMod => commonMod, distEsmTypesContextExtensionMod => contextExtensionMod, distEsmTypesInputsMod => inputsMod, distEsmTypesProverResultMod => proverResultMod, distEsmTypesRegistersMod => registersMod, distEsmTypesTokenMod => tokenMod} import sigmastate.interpreter.{ContextExtension, ProverResult} import sigmastate.serialization.{ErgoTreeSerializer, ValueSerializer} -import sigmastate.{AvlTreeData, AvlTreeFlags, SType} -import sigma.{Coll, Colls} +import sigmastate.{AvlTreeData, AvlTreeFlags} +import sigma.{Coll, Colls, Evaluation} import sigma.Extensions.CollBytesOps +import sigma.ast.SType import java.math.BigInteger import scala.collection.immutable.ListMap diff --git a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Value.scala b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Value.scala index e3a3d15b9a..e08e794fd6 100644 --- a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Value.scala +++ b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Value.scala @@ -5,15 +5,15 @@ import sigma.data.{CollType, RType} import sigma.data.PairType import scorex.util.Extensions.{IntOps, LongOps} import scorex.util.encode.Base16 -import sigmastate.SType +import sigma.ast.SType import sigmastate.crypto.Platform -import sigmastate.eval.{CAvlTree, CGroupElement, CSigmaProp, CostingBox, Evaluation, SigmaDsl} +import sigmastate.eval.{CAvlTree, CGroupElement, CSigmaProp, CostingBox, SigmaDsl} import sigmastate.fleetSdkCommon.distEsmTypesBoxesMod.Box import sigmastate.fleetSdkCommon.distEsmTypesCommonMod import sigmastate.fleetSdkCommon.distEsmTypesRegistersMod.NonMandatoryRegisters import sigmastate.lang.DeserializationSigmaBuilder import sigmastate.serialization.{ConstantSerializer, DataSerializer, SigmaSerializer} -import sigma.{Coll, Colls} +import sigma.{Coll, Colls, Evaluation} import java.math.BigInteger import scala.scalajs.js diff --git a/sdk/js/src/test/scala/org/ergoplatform/sdk/js/IsosSpec.scala b/sdk/js/src/test/scala/org/ergoplatform/sdk/js/IsosSpec.scala index 2164b9b339..97738fdf72 100644 --- a/sdk/js/src/test/scala/org/ergoplatform/sdk/js/IsosSpec.scala +++ b/sdk/js/src/test/scala/org/ergoplatform/sdk/js/IsosSpec.scala @@ -8,7 +8,8 @@ import org.scalacheck.{Arbitrary, Gen} import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -import sigmastate.SType +import sigma.ast.SType +import sigma.data.Iso import sigmastate.Values.Constant import sigmastate.interpreter.{ContextExtension, ProverResult} import sigmastate.serialization.generators.ObjectGenerators diff --git a/sdk/js/src/test/scala/org/ergoplatform/sdk/js/ValueSpec.scala b/sdk/js/src/test/scala/org/ergoplatform/sdk/js/ValueSpec.scala index be0997fcc6..7ef2476289 100644 --- a/sdk/js/src/test/scala/org/ergoplatform/sdk/js/ValueSpec.scala +++ b/sdk/js/src/test/scala/org/ergoplatform/sdk/js/ValueSpec.scala @@ -4,7 +4,7 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import scorex.util.encode.Base16 -import sigmastate.SType +import sigma.ast.SType import sigmastate.Values.{AvlTreeConstant, BigIntConstant, BooleanConstant, BoxConstant, ByteConstant, Constant, GroupElementConstant, IntConstant, LongConstant, ShortConstant, SigmaPropConstant, UnitConstant} import sigmastate.crypto.CryptoConstants.dlogGroup import sigmastate.crypto.DLogProtocol.ProveDlog diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/ContractTemplate.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/ContractTemplate.scala index 47d2a06d3e..ac8da8f398 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/ContractTemplate.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/ContractTemplate.scala @@ -1,11 +1,13 @@ package org.ergoplatform.sdk -import cats.syntax.either._ // required for Scala 2.11 +import cats.syntax.either._ import debox.cfor import io.circe._ import io.circe.syntax.EncoderOps import org.ergoplatform.sdk.utils.SerializationUtils.{parseString, serializeString} import org.ergoplatform.sdk.utils.Zero +import sigma.Evaluation +import sigma.ast.SType import sigma.util.safeNewArray import sigmastate.Values.ErgoTree.headerWithVersion import sigmastate.Values.{ErgoTree, _} diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/DataJsonEncoder.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/DataJsonEncoder.scala index a92eef9947..ac54f1d84f 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/DataJsonEncoder.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/DataJsonEncoder.scala @@ -9,15 +9,15 @@ import org.ergoplatform.settings.ErgoAlgos import sigma.data.RType import scorex.util._ import sigmastate.Values.{Constant, EvaluatedValue} -import sigmastate._ import sigmastate.lang.SigmaParser import sigmastate.eval._ import sigma._ import debox.cfor import sigmastate.exceptions.SerializerException + import scala.collection.compat.immutable.ArraySeq import scala.collection.mutable -import fastparse.{Parsed, parse} +import sigma.ast._ import sigmastate.serialization.SigmaSerializer import sigmastate.serialization.DataSerializer import sigmastate.serialization.ErgoTreeSerializer diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/InputBoxesValidator.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/InputBoxesValidator.scala index 7e3e24a8b7..98e4f45ac7 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/InputBoxesValidator.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/InputBoxesValidator.scala @@ -1,6 +1,6 @@ package org.ergoplatform.sdk -import org.ergoplatform.SigmaConstants.MaxBoxSize +import sigma.data.SigmaConstants.MaxBoxSize import org.ergoplatform.sdk.wallet.Constants.MaxAssetsPerBox import org.ergoplatform.sdk.wallet.{AssetUtils, TokensMap} import org.ergoplatform.{ErgoBoxAssets, ErgoBoxAssetsHolder} diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/JavaHelpers.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/JavaHelpers.scala index 75825defa3..789bb59b2a 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/JavaHelpers.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/JavaHelpers.scala @@ -9,19 +9,19 @@ import org.ergoplatform.sdk.wallet.secrets.{DerivationPath, ExtendedSecretKey} import org.ergoplatform.sdk.wallet.{Constants, TokensMap} import org.ergoplatform.settings.ErgoAlgos import scorex.crypto.authds.ADKey -import sigmastate.utils.Helpers._ // don't remove, required for Scala 2.11 +import sigmastate.utils.Helpers._ import scorex.util.encode.Base16 import scorex.util.{ModifierId, bytesToId, idToBytes} +import sigma.ast.SType import sigma.data.ExactIntegral.LongIsExactIntegral -import sigma.data.RType +import sigma.data.{InverseIso, Iso, RType, SigmaConstants} import sigma.util.StringUtil.StringUtilExtensions -import sigma.{AnyValue, AvlTree, Coll, Colls, GroupElement, Header} -import sigmastate.SType +import sigma.{AnyValue, AvlTree, Coll, Colls, Evaluation, GroupElement, Header} import sigmastate.Values.{Constant, ErgoTree, EvaluatedValue, SValue, SigmaBoolean, SigmaPropConstant} import sigmastate.crypto.CryptoConstants.EcPointType import sigmastate.crypto.DLogProtocol.ProveDlog import sigmastate.crypto.{CryptoFacade, DiffieHellmanTupleProverInput, ProveDHTuple} -import sigmastate.eval.{CostingSigmaDslBuilder, Digest32Coll, Evaluation} +import sigmastate.eval.{CostingSigmaDslBuilder, Digest32Coll} import sigmastate.serialization.{ErgoTreeSerializer, GroupElementSerializer, SigmaSerializer, ValueSerializer} import java.lang.{Boolean => JBoolean, Byte => JByte, Integer => JInt, Long => JLong, Short => JShort, String => JString} @@ -30,33 +30,6 @@ import java.util import java.util.{List => JList, Map => JMap} import scala.collection.{JavaConverters, mutable} -/** Type-class of isomorphisms between types. - * Isomorphism between two types `A` and `B` essentially say that both types - * represents the same information (entity) but in a different way. - *

- * The information is not lost so that both are true: - * 1) a == from(to(a)) - * 2) b == to(from(b)) - *

- * It is used to define type-full conversions: - * - different conversions between Java and Scala data types. - * - conversion between Ergo representations and generated API representations - */ -abstract class Iso[A, B] { - def to(a: A): B - def from(b: B): A - def andThen[C](iso: Iso[B,C]): Iso[A,C] = ComposeIso(iso, this) - def inverse: Iso[B, A] = InverseIso(this) -} -final case class InverseIso[A,B](iso: Iso[A,B]) extends Iso[B,A] { - override def to(a: B): A = iso.from(a) - override def from(b: A): B = iso.to(b) -} -final case class ComposeIso[A, B, C](iso2: Iso[B, C], iso1: Iso[A, B]) extends Iso[A, C] { - def from(c: C): A = iso1.from(iso2.from(c)) - def to(a: A): C = iso2.to(iso1.to(a)) -} - trait LowPriorityIsos { } diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/JsonCodecs.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/JsonCodecs.scala index c03411507e..9495f0d18a 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/JsonCodecs.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/JsonCodecs.scala @@ -12,14 +12,14 @@ import scorex.crypto.hash.Digest32 import scorex.util.ModifierId import sigmastate.Values.{ErgoTree, EvaluatedValue} import sigmastate.eval.Extensions._ -import sigmastate.eval.{CPreHeader, WrapperOf, _} +import sigmastate.eval._ import sigmastate.exceptions.SigmaException import sigmastate.interpreter.{ContextExtension, ProverResult} -import sigmastate.{AvlTreeData, AvlTreeFlags, SType} +import sigmastate.{AvlTreeData, AvlTreeFlags} import sigma.{AnyValue, Coll, Colls, Header, PreHeader} import scala.util.Try -import sigmastate.utils.Helpers._ // required for Scala 2.11 +import sigmastate.utils.Helpers._ import org.ergoplatform.ErgoBox import sigmastate.serialization.ValueSerializer import org.ergoplatform.DataInput @@ -31,7 +31,8 @@ import org.ergoplatform.UnsignedErgoLikeTransaction import org.ergoplatform.ErgoLikeTransactionTemplate import org.ergoplatform.ErgoBoxCandidate import org.ergoplatform.ErgoLikeContext - +import sigma.ast.SType +import sigma.data.{CBigInt, WrapperOf} import scala.collection.mutable trait JsonCodecs { diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/OutBoxBuilder.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/OutBoxBuilder.scala index 61a71fcfa2..50afb74e5b 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/OutBoxBuilder.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/OutBoxBuilder.scala @@ -2,10 +2,10 @@ package org.ergoplatform.sdk import org.ergoplatform.ErgoBox.TokenId import org.ergoplatform.sdk.JavaHelpers.collRType -import org.ergoplatform.{ErgoBox, ErgoBoxCandidate, SigmaConstants} +import org.ergoplatform.{ErgoBox, ErgoBoxCandidate} import sigma.Colls -import sigma.data.RType -import sigmastate.SType +import sigma.ast.SType +import sigma.data.{RType, SigmaConstants} import sigmastate.Values.{Constant, ErgoTree, EvaluatedValue} import scala.collection.mutable.ArrayBuffer diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/ReducingInterpreter.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/ReducingInterpreter.scala index 1e73c49640..64b4d72efb 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/ReducingInterpreter.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/ReducingInterpreter.scala @@ -9,7 +9,7 @@ import org.ergoplatform.{ErgoLikeContext, ErgoLikeInterpreter} import sigma.util.Extensions.LongOps import sigmastate.AvlTreeData import sigmastate.Values.ErgoTree -import sigmastate.eval.Evaluation.addCostChecked +import sigmastate.eval.addCostChecked import sigmastate.exceptions.CostLimitException import sigmastate.interpreter.Interpreter import sigmastate.interpreter.Interpreter.ScriptEnv diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/Zero.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/Zero.scala index 6cc7e6718c..7b31553038 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/Zero.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/Zero.scala @@ -1,7 +1,7 @@ package org.ergoplatform.sdk.utils import org.ergoplatform.ErgoBox -import sigma.data.{CollType, FuncType, OptionType, PairType, RType, TupleType} +import sigma.data.{CBigInt, CollType, FuncType, OptionType, PairType, RType, TupleType} import sigma.data.RType._ import scorex.crypto.authds.avltree.batch.BatchAVLProver import scorex.crypto.hash.{Blake2b256, Digest32} diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/ContractTemplateSpecification.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/ContractTemplateSpecification.scala index 268012ac3c..4bf866740a 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/ContractTemplateSpecification.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/ContractTemplateSpecification.scala @@ -5,10 +5,11 @@ import org.scalatest.compatible.Assertion import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import sigmastate.Values._ import sigmastate._ -import sigmastate.eval.CBigInt import sigmastate.helpers.NegativeTesting import sigmastate.serialization.{SerializationSpecification, SigmaSerializer} import sigma.ContractsTestkit +import sigma.ast.{SByte, SInt, SType} +import sigma.data.CBigInt import java.math.BigInteger @@ -66,15 +67,15 @@ class ContractTemplateSpecification extends SerializationSpecification property("unequal length of constTypes and constValues") { assertExceptionThrown( createContractTemplate( - IndexedSeq(SType.typeByte, SType.typeByte, SType.typeByte).asInstanceOf[IndexedSeq[SType]], + IndexedSeq(SByte, SByte, SByte).asInstanceOf[IndexedSeq[SType]], Some(IndexedSeq(Some(10.toByte), Some(20.toByte)).asInstanceOf[IndexedSeq[Option[SType#WrappedType]]]), IndexedSeq( createParameter("p1", 0), createParameter("p2", 1), createParameter("p3", 2)), - EQ(Plus(ConstantPlaceholder(0, SType.typeByte), - ConstantPlaceholder(1, SType.typeByte)), - ConstantPlaceholder(2, SType.typeByte)).toSigmaProp + EQ(Plus(ConstantPlaceholder(0, SByte), + ConstantPlaceholder(1, SByte)), + ConstantPlaceholder(2, SByte)).toSigmaProp ), exceptionLike[IllegalArgumentException]("constValues must be empty or of same length as constTypes. Got 2, expected 3") ) @@ -83,16 +84,16 @@ class ContractTemplateSpecification extends SerializationSpecification property("more parameters than constants") { assertExceptionThrown( createContractTemplate( - IndexedSeq(SType.typeByte, SType.typeByte, SType.typeByte).asInstanceOf[IndexedSeq[SType]], + IndexedSeq(SByte, SByte, SByte).asInstanceOf[IndexedSeq[SType]], Some(IndexedSeq(Some(10.toByte), Some(20.toByte), Some(30.toByte)).asInstanceOf[IndexedSeq[Option[SType#WrappedType]]]), IndexedSeq( createParameter("p1", 0), createParameter("p2", 1), createParameter("p3", 2), createParameter("p4", 3)), - EQ(Plus(ConstantPlaceholder(0, SType.typeByte), - ConstantPlaceholder(1, SType.typeByte)), - ConstantPlaceholder(2, SType.typeByte)).toSigmaProp + EQ(Plus(ConstantPlaceholder(0, SByte), + ConstantPlaceholder(1, SByte)), + ConstantPlaceholder(2, SByte)).toSigmaProp ), exceptionLike[IllegalArgumentException]("number of parameters must be <= number of constants") ) @@ -101,15 +102,15 @@ class ContractTemplateSpecification extends SerializationSpecification property("invalid parameter constantIndex") { assertExceptionThrown( createContractTemplate( - IndexedSeq(SType.typeByte, SType.typeByte, SType.typeByte).asInstanceOf[IndexedSeq[SType]], + IndexedSeq(SByte, SByte, SByte).asInstanceOf[IndexedSeq[SType]], Some(IndexedSeq(Some(10.toByte), Some(20.toByte), Some(30.toByte)).asInstanceOf[IndexedSeq[Option[SType#WrappedType]]]), IndexedSeq( createParameter("p1", 0), createParameter("p2", 1), createParameter("p3", 100)), - EQ(Plus(ConstantPlaceholder(0, SType.typeByte), - ConstantPlaceholder(1, SType.typeByte)), - ConstantPlaceholder(2, SType.typeByte)).toSigmaProp + EQ(Plus(ConstantPlaceholder(0, SByte), + ConstantPlaceholder(1, SByte)), + ConstantPlaceholder(2, SByte)).toSigmaProp ), exceptionLike[IllegalArgumentException]("parameter constantIndex must be in range [0, 3)") ) @@ -118,15 +119,15 @@ class ContractTemplateSpecification extends SerializationSpecification property("duplicate parameter constantIndex") { assertExceptionThrown( createContractTemplate( - IndexedSeq(SType.typeByte, SType.typeByte, SType.typeByte).asInstanceOf[IndexedSeq[SType]], + IndexedSeq(SByte, SByte, SByte).asInstanceOf[IndexedSeq[SType]], Some(IndexedSeq(Some(10.toByte), Some(20.toByte), Some(30.toByte)).asInstanceOf[IndexedSeq[Option[SType#WrappedType]]]), IndexedSeq( createParameter("p1", 0), createParameter("p2", 1), createParameter("p3", 1)), - EQ(Plus(ConstantPlaceholder(0, SType.typeByte), - ConstantPlaceholder(1, SType.typeByte)), - ConstantPlaceholder(2, SType.typeByte)).toSigmaProp + EQ(Plus(ConstantPlaceholder(0, SByte), + ConstantPlaceholder(1, SByte)), + ConstantPlaceholder(2, SByte)).toSigmaProp ), exceptionLike[IllegalArgumentException]("multiple parameters point to the same constantIndex") ) @@ -135,15 +136,15 @@ class ContractTemplateSpecification extends SerializationSpecification property("duplicate parameter names") { assertExceptionThrown( createContractTemplate( - IndexedSeq(SType.typeByte, SType.typeByte, SType.typeByte).asInstanceOf[IndexedSeq[SType]], + IndexedSeq(SByte, SByte, SByte).asInstanceOf[IndexedSeq[SType]], Some(IndexedSeq(Some(10.toByte), Some(20.toByte), Some(30.toByte)).asInstanceOf[IndexedSeq[Option[SType#WrappedType]]]), IndexedSeq( createParameter("duplicate_name", 0), createParameter("p2", 1), createParameter("duplicate_name", 2)), - EQ(Plus(ConstantPlaceholder(0, SType.typeByte), - ConstantPlaceholder(1, SType.typeByte)), - ConstantPlaceholder(2, SType.typeByte)).toSigmaProp + EQ(Plus(ConstantPlaceholder(0, SByte), + ConstantPlaceholder(1, SByte)), + ConstantPlaceholder(2, SByte)).toSigmaProp ), exceptionLike[IllegalArgumentException]("parameter names must be unique. Found duplicate parameters with name duplicate_name") ) @@ -152,14 +153,14 @@ class ContractTemplateSpecification extends SerializationSpecification property("constantIndex without default value and parameter") { assertExceptionThrown( createContractTemplate( - IndexedSeq(SType.typeByte, SType.typeByte, SType.typeByte).asInstanceOf[IndexedSeq[SType]], + IndexedSeq(SByte, SByte, SByte).asInstanceOf[IndexedSeq[SType]], Some(IndexedSeq(None, Some(20.toByte), Some(30.toByte)).asInstanceOf[IndexedSeq[Option[SType#WrappedType]]]), IndexedSeq( createParameter("p2", 1), createParameter("p3", 2)), - EQ(Plus(ConstantPlaceholder(0, SType.typeByte), - ConstantPlaceholder(1, SType.typeByte)), - ConstantPlaceholder(2, SType.typeByte)).toSigmaProp + EQ(Plus(ConstantPlaceholder(0, SByte), + ConstantPlaceholder(1, SByte)), + ConstantPlaceholder(2, SByte)).toSigmaProp ), exceptionLike[IllegalArgumentException]("constantIndex 0 does not have a default value and absent from parameter as well") ) @@ -171,23 +172,23 @@ class ContractTemplateSpecification extends SerializationSpecification createParameter("p2", 1), createParameter("p3", 2)) val expressionTrees = IndexedSeq( - EQ(Plus(ConstantPlaceholder(0, SType.typeByte), - ConstantPlaceholder(1, SType.typeByte)), - ConstantPlaceholder(2, SType.typeByte)).toSigmaProp, - EQ(Plus(ConstantPlaceholder(0, SType.typeInt), - ConstantPlaceholder(1, SType.typeInt)), - ConstantPlaceholder(2, SType.typeInt)).toSigmaProp, + EQ(Plus(ConstantPlaceholder(0, SByte), + ConstantPlaceholder(1, SByte)), + ConstantPlaceholder(2, SByte)).toSigmaProp, + EQ(Plus(ConstantPlaceholder(0, SInt), + ConstantPlaceholder(1, SInt)), + ConstantPlaceholder(2, SInt)).toSigmaProp, EQ(Plus(CBigInt(BigInteger.valueOf(10L)), BigIntConstant(20L)), BigIntConstant(30L)).toSigmaProp ) val templates = Seq( createContractTemplate( - IndexedSeq(SType.typeByte, SType.typeByte, SType.typeByte).asInstanceOf[IndexedSeq[SType]], + IndexedSeq(SByte, SByte, SByte).asInstanceOf[IndexedSeq[SType]], Some(IndexedSeq(Some(10.toByte), Some(20.toByte), Some(30.toByte)).asInstanceOf[IndexedSeq[Option[SType#WrappedType]]]), parameters, expressionTrees(0) ), createContractTemplate( - IndexedSeq(SType.typeInt, SType.typeInt, SType.typeInt).asInstanceOf[IndexedSeq[SType]], + IndexedSeq(SInt, SInt, SInt).asInstanceOf[IndexedSeq[SType]], Some(IndexedSeq(Some(10), None, Some(30)).asInstanceOf[IndexedSeq[Option[SType#WrappedType]]]), parameters, expressionTrees(1) @@ -244,11 +245,11 @@ class ContractTemplateSpecification extends SerializationSpecification createParameter("p1", 0), createParameter("p2", 2)) val expressionTree = - EQ(Plus(ConstantPlaceholder(0, SType.typeInt), - ConstantPlaceholder(1, SType.typeInt)), - ConstantPlaceholder(2, SType.typeInt)).toSigmaProp + EQ(Plus(ConstantPlaceholder(0, SInt), + ConstantPlaceholder(1, SInt)), + ConstantPlaceholder(2, SInt)).toSigmaProp val template = createContractTemplate( - IndexedSeq(SType.typeInt, SType.typeInt, SType.typeInt).asInstanceOf[IndexedSeq[SType]], + IndexedSeq(SInt, SInt, SInt).asInstanceOf[IndexedSeq[SType]], Some(IndexedSeq(None, Some(20), None).asInstanceOf[IndexedSeq[Option[SType#WrappedType]]]), parameters, expressionTree diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/DataJsonEncoderSpecification.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/DataJsonEncoderSpecification.scala index 89330bc759..d6d90b9edf 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/DataJsonEncoderSpecification.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/DataJsonEncoderSpecification.scala @@ -4,16 +4,16 @@ package org.ergoplatform.sdk import java.math.BigInteger import org.scalacheck.Arbitrary._ import org.scalacheck.Gen -import sigma.data.RType -import sigmastate.SCollection.SByteArray -import sigmastate.SType.AnyOps +import sigma.data.{RType, TupleColl} +import sigma.ast._ +import sigma.ast.SCollection.SByteArray +import sigma.ast.SType.AnyOps import sigmastate.Values.SigmaBoolean -import sigmastate._ import sigmastate.eval.Extensions._ -import sigmastate.eval.{Evaluation, _} +import sigmastate.eval._ import sigmastate.crypto.CryptoConstants.EcPointType import sigmastate.exceptions.SerializerException -import sigma.{AvlTree, Box, Colls} +import sigma.{AvlTree, Box, Colls, Evaluation} import sigmastate.serialization.SerializationSpecification import scala.annotation.nowarn @@ -51,8 +51,9 @@ class DataJsonEncoderSpecification extends SerializationSpecification { def testTuples[T <: SType](tpe: T) = { implicit val wWrapped: Gen[T#WrappedType] = wrappedTypeGen(tpe) - implicit val tag : ClassTag[T#WrappedType] = tpe.classTag[T#WrappedType] - implicit val tAny : RType[Any] = sigma.AnyType + val tT = Evaluation.stypeToRType(tpe) + @nowarn implicit val tag : ClassTag[T#WrappedType] = tT.classTag + @nowarn implicit val tAny : RType[Any] = sigma.AnyType forAll { in: (T#WrappedType, T#WrappedType) => val (x,y) = (in._1, in._2) roundtrip[SType]((x, y).asWrappedType, STuple(tpe, tpe)) @@ -63,8 +64,8 @@ class DataJsonEncoderSpecification extends SerializationSpecification { @nowarn def testAnyValue[T <: SType](tpe: T) = { implicit val wWrapped = wrappedTypeGen(tpe) - implicit val tag = tpe.classTag[T#WrappedType] implicit val tT = Evaluation.stypeToRType(tpe) + implicit val tag = tT.classTag implicit val tAny = sigma.AnyType forAll { in: T#WrappedType => val x = CAnyValue(in) @@ -183,8 +184,9 @@ class DataJsonEncoderSpecification extends SerializationSpecification { def testEncodeError[T <: SType](tpe: T) = { implicit val wWrapped = wrappedTypeGen(tpe) - implicit val tag = tpe.classTag[T#WrappedType] - implicit val tAny = sigma.AnyType + val tT = Evaluation.stypeToRType(tpe) + @nowarn implicit val tag = tT.classTag + @nowarn implicit val tAny = sigma.AnyType forAll { x: T#WrappedType => an[SerializerException] should be thrownBy { DataJsonEncoder.encode(TupleColl(x, x, x).asWrappedType, STuple(tpe, tpe, tpe)) diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/JsonSerializationSpec.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/JsonSerializationSpec.scala index 70615d6796..e94d1293a5 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/JsonSerializationSpec.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/JsonSerializationSpec.scala @@ -9,7 +9,7 @@ import org.scalacheck.Arbitrary.arbitrary import scorex.crypto.authds.{ADDigest, ADKey} import scorex.util.ModifierId import scorex.util.encode.Base16 -import sigmastate.{AvlTreeData, SType} +import sigmastate.AvlTreeData import sigmastate.Values.{ByteArrayConstant, ByteConstant, ErgoTree, EvaluatedValue, IntConstant, LongArrayConstant, SigmaPropConstant} import sigmastate.crypto.CryptoConstants import sigmastate.crypto.DLogProtocol.ProveDlog @@ -19,8 +19,8 @@ import sigmastate.serialization.SerializationSpecification import sigmastate.utils.Helpers.DecoderResultOps // required for Scala 2.11 (extension method toTry) import sigma.Coll import sigma.{Header, PreHeader} -import org.ergoplatform.{DataInput, ErgoBox, ErgoBoxCandidate, ErgoLikeContext, ErgoLikeTransaction, ErgoLikeTransactionTemplate, Input, UnsignedErgoLikeTransaction, UnsignedInput} - +import org.ergoplatform.{DataInput, ErgoBox, ErgoLikeContext, ErgoLikeTransaction, ErgoLikeTransactionTemplate, Input, UnsignedErgoLikeTransaction, UnsignedInput} +import sigma.ast.SType import scala.collection.mutable class JsonSerializationSpec extends SerializationSpecification with JsonCodecs { diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/generators/ObjectGenerators.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/generators/ObjectGenerators.scala index 3908760e59..cab8d1df1a 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/generators/ObjectGenerators.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/generators/ObjectGenerators.scala @@ -3,9 +3,10 @@ package org.ergoplatform.sdk.generators import org.ergoplatform.sdk.{ContractTemplate, Parameter} import org.ergoplatform.validation.ValidationSpecification import org.scalacheck.Gen -import sigmastate.Values.{ErgoTree, SigmaPropValue} +import sigma.ast.SType +import sigmastate.TestsBase +import sigmastate.Values.ErgoTree import sigmastate.serialization.generators.{ConcreteCollectionGenerators, TypeGenerators, ObjectGenerators => InterpreterObjectGenerators} -import sigmastate.{SType, TestsBase} import scala.util.Random diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/wallet/utils/Generators.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/wallet/utils/Generators.scala index 80164f5f23..3df10bf2ce 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/wallet/utils/Generators.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/wallet/utils/Generators.scala @@ -10,7 +10,7 @@ import org.scalacheck.{Arbitrary, Gen} import scorex.crypto.authds.ADKey import sigmastate.Values.{ByteArrayConstant, CollectionConstant, ErgoTree, EvaluatedValue, FalseLeaf, TrueLeaf} import sigmastate.crypto.DLogProtocol.ProveDlog -import sigmastate.{SByte, SType} +import sigma.ast.{SByte, SType} import scorex.util._ import org.ergoplatform.{ErgoBox, ErgoBoxCandidate, ErgoTreePredef, UnsignedErgoLikeTransaction, UnsignedInput} import sigmastate.eval.Extensions._