diff --git a/README.md b/README.md index 7d02e9cf0e..6ecc4ac99b 100644 --- a/README.md +++ b/README.md @@ -93,23 +93,19 @@ This library is on Maven repository and can be added to the SBT configuration of Scala project. ```scala -libraryDependencies += "org.scorexfoundation" %% "sigma-state" % "4.0.3" +libraryDependencies += "org.scorexfoundation" %% "sigma-state" % "5.0.6" ``` ## Repository Organization -| sub-module | description | -|---|-----| -| common | Used in all other submodules and contain basic utility classes | -| core | Implementation of graph-based intermediate representation of ErgoTree, which is used in cost estimation and interpretation | -| docs | Collection of documents | -| library | Implementation of graph IR nodes for Coll, Size and other types | -| library-api | Declarations of interfaces | -| library-impl | Implementation of interfaces | -| sigma-api | Declarations of runtime interfaces which are used in ErgoTree interpreter | -| sigma-impl | Implementation of sigma-api interfaces | -| sigma-library | Implementation of graph IR nodes for Sigma types | -| sigmastate | Implementation ErgoTree, Interpreter and cost estimation | +| sub-module | description | +|-------------|-------------------------------------------------------------------------------------------| +| common | Used in all other submodules and contain basic utility classes | +| core-lib | Contains core classes such as Coll, BigInt used by interpreter | +| docs | Collection of documents | +| graph-ir | Implementation of graph-based intermediate representation of ErgoTree, which is used in by ErgoScript compiler | +| interpreter | Implementation of ErgoTree Interpreter | +| sc | Implementation of ErgoScript compiler | ## Contributing diff --git a/build.sbt b/build.sbt index 6c06c611fe..cc1faf43cd 100644 --- a/build.sbt +++ b/build.sbt @@ -70,13 +70,27 @@ dynverSonatypeSnapshots in ThisBuild := true dynverSeparator in ThisBuild := "-" val bouncycastleBcprov = "org.bouncycastle" % "bcprov-jdk15on" % "1.66" -val scrypto = "org.scorexfoundation" %% "scrypto" % "2.3.0-RC1" +val scrypto = "org.scorexfoundation" %% "scrypto" % "2.3.0" val scorexUtil = "org.scorexfoundation" %% "scorex-util" % "0.2.0" val debox = "org.scorexfoundation" %% "debox" % "0.10.0" val spireMacros = "org.typelevel" %% "spire-macros" % "0.17.0-M1" val fastparse = "com.lihaoyi" %% "fastparse" % "2.3.3" val scalaCompat = "org.scala-lang.modules" %% "scala-collection-compat" % "2.7.0" +lazy val circeCore211 = "io.circe" %% "circe-core" % "0.10.0" +lazy val circeGeneric211 = "io.circe" %% "circe-generic" % "0.10.0" +lazy val circeParser211 = "io.circe" %% "circe-parser" % "0.10.0" + +lazy val circeCore = "io.circe" %% "circe-core" % "0.13.0" +lazy val circeGeneric = "io.circe" %% "circe-generic" % "0.13.0" +lazy val circeParser = "io.circe" %% "circe-parser" % "0.13.0" + +def circeDeps(scalaVersion: String) = if (scalaVersion == scala211) + Seq(circeCore211, circeGeneric211, circeParser211) +else + Seq(circeCore, circeGeneric, circeParser) + + val testingDependencies = Seq( "org.scalatest" %% "scalatest" % "3.2.14" % Test, "org.scalactic" %% "scalactic" % "3.2.14" % Test, @@ -101,19 +115,7 @@ libraryDependencies ++= Seq( scorexUtil, "org.bouncycastle" % "bcprov-jdk15on" % "1.+", fastparse, debox, spireMacros, scalaCompat -) ++ testingDependencies ++ - (if (scalaVersion.value == scala211) - Seq(circeCore211, circeGeneric211, circeParser211) - else - Seq(circeCore, circeGeneric, circeParser)) - -lazy val circeCore211 = "io.circe" %% "circe-core" % "0.10.0" -lazy val circeGeneric211 = "io.circe" %% "circe-generic" % "0.10.0" -lazy val circeParser211 = "io.circe" %% "circe-parser" % "0.10.0" - -lazy val circeCore = "io.circe" %% "circe-core" % "0.13.0" -lazy val circeGeneric = "io.circe" %% "circe-generic" % "0.13.0" -lazy val circeParser = "io.circe" %% "circe-parser" % "0.13.0" +) ++ testingDependencies ++ circeDeps(scalaVersion.value) scalacOptions ++= Seq("-feature", "-deprecation") @@ -152,76 +154,43 @@ lazy val common = Project("common", file("common")) )) .settings(publish / skip := true) -lazy val libraryapi = Project("library-api", file("library-api")) +lazy val corelib = Project("core-lib", file("core-lib")) .dependsOn(common % allConfigDependency) - .settings(libraryDefSettings, - libraryDependencies ++= Seq()) - .settings(publish / skip := true) - -lazy val libraryimpl = Project("library-impl", file("library-impl")) - .dependsOn(libraryapi % allConfigDependency) .settings(libraryDefSettings, - libraryDependencies ++= Seq( debox )) + libraryDependencies ++= Seq( debox, scrypto )) .settings(publish / skip := true) -lazy val core = Project("core", file("core")) - .dependsOn(common % allConfigDependency, libraryapi % allConfigDependency) - .settings(libraryDefSettings, - libraryDependencies ++= Seq( debox )) - .settings(publish / skip := true) - -lazy val library = Project("library", file("library")) - .dependsOn(common % allConfigDependency, core % allConfigDependency, libraryapi, libraryimpl) +lazy val graphir = Project("graph-ir", file("graph-ir")) + .dependsOn(common % allConfigDependency, corelib) .settings( libraryDefSettings, - libraryDependencies ++= Seq( debox )) + libraryDependencies ++= Seq( debox, scrypto, bouncycastleBcprov )) .settings(publish / skip := true) -lazy val sigmaapi = Project("sigma-api", file("sigma-api")) - .dependsOn(common, libraryapi) - .settings(libraryDefSettings, - libraryDependencies ++= Seq( - scrypto, bouncycastleBcprov - )) - .settings(publish / skip := true) - -lazy val sigmalibrary = Project("sigma-library", file("sigma-library")) - .dependsOn( - common % allConfigDependency, - core % allConfigDependency, - libraryapi % allConfigDependency, - libraryimpl % allConfigDependency, - library % allConfigDependency, - sigmaapi % allConfigDependency) - .settings(libraryDefSettings, - libraryDependencies ++= Seq( - scrypto, - bouncycastleBcprov - )) +lazy val interpreter = (project in file("interpreter")) + .dependsOn(graphir % allConfigDependency) + .settings(libraryDefSettings) + .settings(libraryDependencies ++= + Seq(scorexUtil, fastparse) ++ circeDeps(scalaVersion.value) + ) .settings(publish / skip := true) -lazy val sigmastate = (project in file("sigmastate")) - .dependsOn(sigmalibrary % allConfigDependency) +lazy val sc = (project in file("sc")) + .dependsOn(graphir % allConfigDependency, interpreter % allConfigDependency) .settings(libraryDefSettings) - .settings(libraryDependencies ++= Seq( - scorexUtil, fastparse, - if (scalaVersion.value == scala211) circeCore211 else circeCore, - if (scalaVersion.value == scala211) circeGeneric211 else circeGeneric, - if (scalaVersion.value == scala211) circeParser211 else circeParser - )) + .settings(libraryDependencies ++= + Seq(scorexUtil, fastparse) ++ circeDeps(scalaVersion.value) + ) .settings(publish / skip := true) lazy val sigma = (project in file(".")) - .aggregate( - sigmastate, common, core, libraryapi, libraryimpl, library, - sigmaapi, sigmalibrary) + .aggregate(common, corelib, graphir, interpreter, sc) .settings(libraryDefSettings, rootSettings) .settings(publish / aggregate := false) .settings(publishLocal / aggregate := false) lazy val aggregateCompile = ScopeFilter( - inProjects(common, core, libraryapi, libraryimpl, library, sigmaapi, - sigmalibrary, sigmastate), + inProjects(common, corelib, graphir, interpreter, sc), inConfigurations(Compile)) lazy val rootSettings = Seq( diff --git a/common/src/main/scala/scalan/Typeclass.scala b/common/src/main/scala/scalan/Typeclass.scala deleted file mode 100644 index 9c94a3a181..0000000000 --- a/common/src/main/scala/scalan/Typeclass.scala +++ /dev/null @@ -1,3 +0,0 @@ -package scalan - -class Typeclass extends scala.annotation.StaticAnnotation diff --git a/common/src/main/scala/scalan/package.scala b/common/src/main/scala/scalan/package.scala index be0281b8b3..87845d14c5 100644 --- a/common/src/main/scala/scalan/package.scala +++ b/common/src/main/scala/scalan/package.scala @@ -1,5 +1,4 @@ -import scala.language.experimental.macros import scala.reflect.ClassTag package object scalan { diff --git a/common/src/main/scala/scalan/reflection/CommonReflection.scala b/common/src/main/scala/scalan/reflection/CommonReflection.scala new file mode 100644 index 0000000000..b839d668be --- /dev/null +++ b/common/src/main/scala/scalan/reflection/CommonReflection.scala @@ -0,0 +1,74 @@ +package scalan.reflection + +import scala.collection.compat.immutable.ArraySeq +import scala.collection.mutable +import scala.collection.immutable + +/** Reflection metadata and global dictionaries to access it. + * For each class of this module that needs reflection metadata, + * we register a class entry with the necessary information. + * Only information that is needed at runtime is registered. + */ +object CommonReflection { + /** Descriptors of classes. */ + val classes = mutable.HashMap.empty[Class[_], SRClass[_]] + + /** Registers a class entry in the map of classes. + * + * @tparam T the type of the class to be registered + * @param clazz the class to be registered + * @param constructors the constructors of the class + * @param fields the fields of the class + * @param methods the methods of the class (represented as a map of method names and argument types to the corresponding RMethod instances) + */ + def registerClassEntry[T](clazz: Class[T], + constructors: Seq[SRConstructor[_]] = ArraySeq.empty, + fields: Map[String, SRField] = Map.empty, + methods: Map[(String, Seq[Class[_]]), RMethod] = Map.empty): Unit = classes.synchronized { + classes.put(clazz, new SRClass(clazz, constructors, fields, methods)) + } + + registerClassEntry(classOf[Boolean]) + + registerClassEntry(classOf[Byte]) + + registerClassEntry(classOf[Short]) + + registerClassEntry(classOf[Int]) + + registerClassEntry(classOf[Long]) + + registerClassEntry(classOf[Product2[_, _]]) + + registerClassEntry(classOf[immutable.$colon$colon[_]], + constructors = Array( + mkConstructor(Array(classOf[java.lang.Object], classOf[immutable.List[_]])) { args => + new immutable.$colon$colon(args(0).asInstanceOf[java.lang.Object], args(1).asInstanceOf[immutable.List[_]]) + } + ) + ) + + { val clazz = classOf[scala.Option[_]] + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "filter", Array(classOf[scala.Function1[_,_]])) { (obj, args) => + obj.asInstanceOf[Option[Any]].filter(args(0).asInstanceOf[Any => Boolean]) + }, + mkMethod(clazz, "map", Array(classOf[scala.Function1[_,_]])) { (obj, args) => + obj.asInstanceOf[Option[Any]].map(args(0).asInstanceOf[Any => Any]) + } + ) + ) + } + + { val clazz = classOf[scala.Some[_]] + registerClassEntry(clazz, + constructors = Array( + mkConstructor(Array(classOf[java.lang.Object])) { args => + new scala.Some(args(0).asInstanceOf[java.lang.Object]) + } + ) + ) + } + +} diff --git a/common/src/main/scala/scalan/reflection/JavaImpl.scala b/common/src/main/scala/scalan/reflection/JavaImpl.scala new file mode 100644 index 0000000000..bf8033c070 --- /dev/null +++ b/common/src/main/scala/scalan/reflection/JavaImpl.scala @@ -0,0 +1,160 @@ +package scalan.reflection + +import debox.cfor + +import java.lang.reflect.{Field, Constructor, Method} +import scala.collection.concurrent.TrieMap +import scala.collection.mutable + +/** + * A class that represents a Java class of type `T`. + * + * @constructor creates a new instance of `JRClass` with the given value. + * @param value the Java class of type `T`. + */ +class JRClass[T](val value: Class[T]) extends RClass[T] { + + /** A mutable map that stores the fields of this class. */ + val fields = TrieMap.empty[String, RField] + + override def getField(name: String): RField = + memoize(fields)(name, JRField(value.getField(name))) + + /** A mutable map that stores the methods of this class. */ + val methods = TrieMap.empty[(String, Seq[Class[_]]), RMethod] + + override def getMethod(name: String, parameterTypes: Class[_]*): RMethod = { + memoize(methods)((name, parameterTypes), JRMethod(this, value.getMethod(name, parameterTypes:_*))) + } + + override def getSimpleName: String = value.getSimpleName + override def getName: String = value.getName + + /** The constructors of this class. */ + var constructors: Seq[RConstructor[_]] = _ + + override def getConstructors(): Seq[RConstructor[_]] = { + if (constructors == null) { + synchronized { + if (constructors == null) { + val cs = value.getConstructors.asInstanceOf[Array[Constructor[Any]]] + val buf = mutable.ArrayBuilder.make[RConstructor[Any]] + cfor(0)(_ < cs.length, _ + 1) { i => + val c = cs(i) + buf += JRConstructor[Any](i, c) + } + constructors = buf.result().asInstanceOf[Array[RConstructor[_]]] + } + } + } + constructors + } + + /** Helper method that returns [[JRConstructor]] instances that were at least once used + * at runtime. + */ + def getUsedConstructors(): Seq[JRConstructor[_]] = + getConstructors().collect { case c: JRConstructor[_] if c.wasUsed => c } + + override def isPrimitive(): Boolean = value.isPrimitive + + override def getSuperclass(): RClass[_ >: T] = RClass(value.getSuperclass) + + override def isAssignableFrom(cls: Class[_]): Boolean = value.isAssignableFrom(cls) + + override def getDeclaredMethods(): Array[RMethod] = value.getDeclaredMethods.map(JRMethod(this, _)) + + override def equals(other: Any): Boolean = (this eq other.asInstanceOf[AnyRef]) || (other match { + case that: JRClass[_] => + val eq = value == that.value + // Uncomment the following line when debugging + // if (!eq) + // assert(this.getName != that.getName) // sanity check + eq + case _ => false + }) + + override def hashCode(): Int = value.hashCode() + + override def toString: String = s"JRClass($value)" +} + + +/** Implements [[RField]] using Java reflection. + * + * @param value The [[java.lang.reflect.Field]] object to wrap. + */ +class JRField private (val value: Field) extends RField { + override def getType: Class[_] = value.getType + + override def equals(other: Any): Boolean = (this eq other.asInstanceOf[AnyRef]) || (other match { + case that: JRField => value == that.value + case _ => false + }) + override def hashCode(): Int = value.hashCode() + override def toString: String = s"JRField($value)" +} +object JRField { + private[reflection] def apply(field: Field): RField = new JRField(field) +} + +/** Implements [[RConstructor]] using Java reflection. + * + * @tparam T The type of the class that declares this constructor. + * @param index The index of the constructor in the sequence of all constructors of the class. + * @param value The [[java.lang.reflect.Constructor]] to be wrapped. + */ +class JRConstructor[T] private (val index: Int, val value: Constructor[T]) extends RConstructor[T] { + @volatile var wasUsed: Boolean = false + override def newInstance(initargs: AnyRef*): T = { + wasUsed = true + value.newInstance(initargs:_*) + } + override def getParameterTypes(): Array[Class[_]] = { + wasUsed = true + value.getParameterTypes + } + + override def equals(other: Any): Boolean = (this eq other.asInstanceOf[AnyRef]) || (other match { + case that: JRConstructor[_] => value == that.value + case _ => false + }) + override def hashCode(): Int = value.hashCode() + override def toString: String = s"JRConstructor($index, $value)" +} +object JRConstructor { + private[reflection] def apply[T](index: Int, value: Constructor[T]): RConstructor[T] = + new JRConstructor[T](index, value) +} + +/** + * Implements [[RMethod]] using Java reflection. + * + * @param declaringClass The JRClass that declares this method. + * @param value The [[java.lang.reflect.Method]] instance that this JRMethod represents. + */ +class JRMethod private (declaringClass: JRClass[_], val value: Method) extends RMethod { + override def invoke(obj: Any, args: AnyRef*): AnyRef = { +// val name = value.getName +// val parameterTypes: Seq[Class[_]] = value.getParameterTypes +// memoize(declaringClass.methods)((name, parameterTypes), this) + value.invoke(obj, args:_*) + } + + override def getName: String = value.getName + + override def getDeclaringClass(): Class[_] = value.getDeclaringClass + + override def getParameterTypes(): Seq[Class[_]] = value.getParameterTypes + + override def equals(other: Any): Boolean = (this eq other.asInstanceOf[AnyRef]) || (other match { + case that: JRMethod => value == that.value + case _ => false + }) + + override def hashCode(): Int = value.hashCode() + override def toString: String = s"JRMethod($value)" +} +object JRMethod { + private[reflection] def apply(clazz: JRClass[_], value: Method): RMethod = new JRMethod(clazz, value) +} diff --git a/common/src/main/scala/scalan/reflection/Platform.scala b/common/src/main/scala/scalan/reflection/Platform.scala new file mode 100644 index 0000000000..bf2ee9c6cc --- /dev/null +++ b/common/src/main/scala/scalan/reflection/Platform.scala @@ -0,0 +1,46 @@ +package scalan.reflection + +import scala.collection.concurrent.TrieMap + +/** Platform dependent implementation of reflection methods. */ +object Platform { + /** Stores all classes which were accessed during runtime and whose metadata was not + * registered. + * This should be used only for debugging and never in production. + */ + val unknownClasses = TrieMap.empty[Class[_], JRClass[_]] + + /** Thread-safe storage of class information. */ + private val classes = TrieMap.empty[Class[_], JRClass[_]] + + /** Check class registration. Should be used only for debugging. */ + private def checkRegisteredClass[T](clazz: Class[T]): Unit = { + CommonReflection.classes.get(clazz) match { + case Some(c) => + assert(c.clazz == clazz) + case _ => + sys.error(s"Cannot find RClass data for $clazz") + } + } + + /** Returns an RClass instance for the given class. + * + * @param clazz The class for which to retrieve an RClass instance. + * @tparam T The type of the class. + * @return An RClass instance for the given class. + * @throws java.lang.RuntimeException if RClass metadata for the given class cannot be + * found. + */ + def resolveClass[T](clazz: Class[T]): RClass[T] = { + val cls = memoize(classes)(clazz, new JRClass[T](clazz)).asInstanceOf[JRClass[T]] + // Uncomment the following lines to collect missing reflection data and generate Scala code for it + // Should be used only for debugging and never in production. +// try { +// checkRegisteredClass(clazz) +// } catch { +// case e: RuntimeException => +// memoize(unknownClasses)(clazz, cls) +// } + cls + } +} diff --git a/common/src/main/scala/scalan/reflection/RClass.scala b/common/src/main/scala/scalan/reflection/RClass.scala new file mode 100644 index 0000000000..32e8aeb2e3 --- /dev/null +++ b/common/src/main/scala/scalan/reflection/RClass.scala @@ -0,0 +1,115 @@ +package scalan.reflection + +/** A representation of a field of a class, providing reflective access to the field's type. */ +abstract class RField { + /** @return the type of this field. */ + def getType: Class[_] +} + +/** A representation of a constructor of a class, providing reflective access to the constructor's parameters and ability to create new instances. + * @tparam T the type of the class + */ +trait RConstructor[T] { + + /** Creates a new instance of the class using the specified arguments. + * @param args the arguments to pass to the constructor + * @return a new instance of the class T + */ + def newInstance(args: AnyRef*): T + + /** Returns the types of the parameters of this constructor. + * @return an array of Class objects representing the types of the parameters of this constructor + */ + def getParameterTypes(): Array[Class[_]] +} + +/** Represents a method that can be invoked on an object with arguments. */ +abstract class RMethod { + /** Invokes this method on the given object with the given arguments. + * + * @param obj The object on which to invoke this method. + * @param args The arguments to pass to this method. + * @return The result of invoking this method on the given object with the given arguments. + */ + def invoke(obj: Any, args: AnyRef*): Any + + /** Returns the name of this method. */ + def getName: String + + /** Returns the class in which this method is declared. */ + def getDeclaringClass(): Class[_] + + /** Returns an array of `Class` objects representing the parameter types of this method + * in declaration order. + */ + def getParameterTypes(): Seq[Class[_]] +} + +/** Represents a class that can be reflected upon to obtain information about its fields, + * methods, constructors and superclass. + * + * @tparam T The type represented by this `RClass`. + */ +abstract class RClass[T] { + /** Returns an `RField` object representing a field with the specified name within this `RClass`. + * + * @param name The name of the field to retrieve + * @return An `RField` object representing a field with the specified name within this `RClass`. + */ + def getField(name: String): RField + + /** Returns an `RMethod` object representing a method with the specified name and + * parameter types within this `RClass`. + * + * @param name The name of the method to retrieve + * @param parameterTypes A list of classes representing each parameter type + * @return An `RMethod` object representing a method with the specified name and + * parameter types within this `RClass`. + */ + def getMethod(name: String, parameterTypes: Class[_]*): RMethod + + /** Returns the simple name (i.e. without package) of this class. */ + def getSimpleName: String + + /** Returns the fully qualified name of this class. */ + def getName: String + + /** Returns an array containing `RConstructor` objects reflecting all public constructors + * of this `RClass` + */ + def getConstructors(): Seq[RConstructor[_]] + + /** Returns a boolean indicating whether or not this `RClass` represents a primitive type. */ + def isPrimitive(): Boolean + + /** Returns an `RClass` object representing the superclass of this `RClass`. */ + def getSuperclass(): RClass[_ >: T] + + /** Returns a boolean indicating whether or not instances of the specified class can be assigned to + * variables of this `RClass`. + * + * @param cls The class to check + * @return A boolean indicating whether or not instances of the specified class can be assigned to + * variables of this `RClass` + */ + def isAssignableFrom(cls: Class[_]): Boolean + + /** Returns an array containing `RMethod` objects reflecting all declared methods + * of this `RClass` + */ + def getDeclaredMethods(): Array[RMethod] +} + +object RClass { + + /** Returns an RClass instance for the given class. + * + * @param clazz The class for which to retrieve an RClass instance. + * @tparam T The type of the class. + * @return An RClass instance for the given class. + * @throws java.lang.RuntimeException if RClass metadata for the given class cannot be + * found. + */ + def apply[T](clazz: Class[T]): RClass[T] = Platform.resolveClass(clazz) + +} \ No newline at end of file diff --git a/common/src/main/scala/scalan/reflection/StaticImpl.scala b/common/src/main/scala/scalan/reflection/StaticImpl.scala new file mode 100644 index 0000000000..ff6a39348e --- /dev/null +++ b/common/src/main/scala/scalan/reflection/StaticImpl.scala @@ -0,0 +1,99 @@ +package scalan.reflection + +/** + * Represents a field in an Sigma Reflection metadata. + * Extends [[RField]] by providing a concrete implementation without relying on Java reflection. + * The instances of this class are used as parameters of `registerClassEntry` method. + * + * @param name the name of the field + * @param tpe the type of the field as runtime [[java.lang.Class]] + */ +class SRField(val name: String, tpe: Class[_]) extends RField { + override def getType: Class[_] = tpe + + override def equals(other: Any): Boolean = (this eq other.asInstanceOf[AnyRef]) || (other match { + case that: SRField => name == that.name + case _ => false + }) + override def hashCode(): Int = name.hashCode() +} + +/** Represents a constructor in an Sigma Reflection metadata. + * Extends [[RConstructor]] by providing a concrete implementation without relying on Java reflection. + * + * @param parameterTypes the types of the constructor's parameters + */ +abstract class SRConstructor[T](parameterTypes: Array[Class[_]]) extends RConstructor[T] { + override def getParameterTypes(): Array[Class[_]] = parameterTypes +} + +/** Represents a method in an Sigma Reflection metadata. + * Extends [[RMethod]] by providing a concrete implementation without relying on Java reflection. + * + * @param declaringClass the class that declares the method + * @param name the name of the method + * @param parameterTypes the types of the method's parameters + */ +abstract class SRMethod(declaringClass: Class[_], name: String, parameterTypes: Seq[Class[_]]) extends RMethod { + override def getName: String = name + override def getDeclaringClass(): Class[_] = declaringClass + override def getParameterTypes(): Seq[Class[_]] = parameterTypes + + override def equals(other: Any): Boolean = (this eq other.asInstanceOf[AnyRef]) || (other match { + case that: SRMethod + if getDeclaringClass == that.getDeclaringClass && getName == that.getName => + parameterTypes == that.getParameterTypes() + case _ => false + }) + + override def toString: String = s"SRMethod(${declaringClass.getName}.$name(${parameterTypes.mkString(", ")}))" +} + +/** + * Represents a class in an Sigma Reflection metadata. + * Extends [[RClass]] by providing a concrete implementation without relying on Java reflection. + * + * @param clazz the [[java.lang.Class]] being represented + * @param constructors the constructors of the class + * @param fields the fields of the class (name -> field) + * @param methods the methods of the class ((name, parameterTypes) -> method) + */ +class SRClass[T](val clazz: Class[T], + constructors: Seq[SRConstructor[_]], + fields: Map[String, SRField], + methods: Map[(String, Seq[Class[_]]), RMethod]) extends RClass[T] { + + override def getField(fieldName: String): RField = fields.get(fieldName) match { + case Some(f) => f + case _ => throw new NoSuchFieldException(s"${clazz.getName}.$fieldName") + } + + override def getMethod(name: String, + parameterTypes: Class[_]*): RMethod = { + methods.get((name, parameterTypes)) match { + case Some(m) => m + case _ => throw new NoSuchMethodException(s"${clazz.getName}.$name(${parameterTypes.map(_.getName).mkString(",")})") + } + } + + override def getSimpleName: String = clazz.getSimpleName + + override def getName: String = clazz.getName + + override def isPrimitive(): Boolean = clazz.isPrimitive + + override def getConstructors(): Seq[RConstructor[_]] = constructors + + override def getSuperclass(): RClass[_ >: T] = clazz.getSuperclass.asInstanceOf[RClass[_ >: T]] + + override def isAssignableFrom(cls: Class[_]): Boolean = clazz.isAssignableFrom(cls) + + override def getDeclaredMethods(): Array[RMethod] = methods.values.toArray + + override def equals(other: Any): Boolean = (this eq other.asInstanceOf[AnyRef]) || (other match { + case that: SRClass[_] => clazz == that.clazz + case _ => false + }) + override def hashCode(): Int = clazz.hashCode() +} + diff --git a/common/src/main/scala/scalan/reflection/package.scala b/common/src/main/scala/scalan/reflection/package.scala new file mode 100644 index 0000000000..96a9556628 --- /dev/null +++ b/common/src/main/scala/scalan/reflection/package.scala @@ -0,0 +1,69 @@ +package scalan + +import scala.collection.mutable + +/** Contains the Sigma Reflection API. + * Sigma reflection is a mechanism for obtaining metadata about classes, methods, fields, etc. + * at runtime. It is used by kiama to rewrite ErgoTree expressions. It is also used by the + * ErgoTree interpreter to implement MethodCall nodes. + * + * The Sigma Reflection API has two implementations: + * 1) based on the Java Reflection API + * 2) based on Sigma Reflection metadata declared in the StaticImpl.scala file + */ +package object reflection { + + /** Memoizes a value in a mutable HashMap. + * + * @param map The mutable HashMap to store the key-value pair. + * @param key The key to store in the map. + * @param value The value to be evaluated and stored in the map if the key is not present. + * @return The value associated with the given key in the map. If the key is not present in the map, + * evaluates the `value` parameter and stores it in the map before returning it. + */ + def memoize[K, V](map: mutable.Map[K, V]) + (key: K, value: => V): V = { + map.get(key) match { + case Some(v) => v + case None => + val v = value + map.put(key, v) + v + } + } + + /** Creates a new SRMethod instance with the given parameters and handler function. + * This is analogous to the Java Reflection API's [[java.lang.reflect.Method]] class. + * + * @param clazz the [[java.lang.Class]] that declares the method + * @param name the name of the method + * @param paramTypes the types of the method's parameters + * @param handler a function that handles invoking the method, when RMethod.invoke + * is called then this `handler` is called + * @return a tuple containing the method's name and parameter types as its first element, + * and an SRMethod instance as its second element + * @see [[SRMethod]] + */ + def mkMethod(clazz: Class[_], name: String, paramTypes: Seq[Class[_]]) + (handler: (Any, Array[AnyRef]) => Any): ((String, Seq[Class[_]]), RMethod) = { + (name, paramTypes) -> + new SRMethod(clazz, name, paramTypes) { + override def invoke( + obj: Any, + args: AnyRef*): Any = handler(obj, args.toArray) + } + } + + /** Creates a new [[SRConstructor]] instance with the given parameter types and handler function. + * + * @param parameterTypes the types of the constructor's parameters + * @param handler a function that handles creating a new instance using this constructor + * @return an SRConstructor instance + */ + def mkConstructor(parameterTypes: Array[Class[_]])(handler: Array[AnyRef] => Any) = { + new SRConstructor[Any](parameterTypes) { + override def newInstance(args: AnyRef*): Any = handler(args.toArray) + } + } + +} diff --git a/common/src/main/scala/scalan/util/ClassLoaderUtil.scala b/common/src/main/scala/scalan/util/ClassLoaderUtil.scala deleted file mode 100644 index 332b34466f..0000000000 --- a/common/src/main/scala/scalan/util/ClassLoaderUtil.scala +++ /dev/null @@ -1,16 +0,0 @@ -package scalan.util - -import java.io.File -import java.net.URLClassLoader - -object ClassLoaderUtil { - def classPath(loader: ClassLoader): Seq[File] = loader match { - case loader: URLClassLoader => - loader.getURLs.map(FileUtil.urlToFile) ++ classPath(loader.getParent) - case _ => - Nil - } - - def URLClassLoader(files: TraversableOnce[File], parent: ClassLoader): URLClassLoader = - new URLClassLoader(files.map(_.toURI.toURL).toArray, parent) -} diff --git a/common/src/main/scala/scalan/util/CollectionUtil.scala b/common/src/main/scala/scalan/util/CollectionUtil.scala index 3f4613c5b7..414d3b9cea 100644 --- a/common/src/main/scala/scalan/util/CollectionUtil.scala +++ b/common/src/main/scala/scalan/util/CollectionUtil.scala @@ -3,7 +3,6 @@ package scalan.util import scala.language.higherKinds import java.util import java.util.Objects -import java.util.function.BiConsumer import scala.collection.{Seq, mutable, GenIterable} import scala.collection.mutable.{HashMap, ArrayBuffer} @@ -58,14 +57,6 @@ object CollectionUtil { case arr: Array[Boolean] => util.Arrays.hashCode(arr) } - def foldRight[A,B](xs: Seq[A])(proj: A => B)(f: (A,B) => B): B = - xs.foldRight[B](null.asInstanceOf[B]) { case (a, b) => - b match { - case null => proj(a) - case _ => f(a, b) - } - } - /** Group the given sequence of pairs by first values as keys. * @param kvs sequence of values which is traversed once * @return a multimap with ArrayBuffer of values for each key. diff --git a/common/src/main/scala/scalan/util/PrintExtensions.scala b/common/src/main/scala/scalan/util/PrintExtensions.scala deleted file mode 100644 index d9639560cb..0000000000 --- a/common/src/main/scala/scalan/util/PrintExtensions.scala +++ /dev/null @@ -1,38 +0,0 @@ -package scalan.util - -/** Helper methods for pretty printing of collections and optional values. */ -object PrintExtensions { - implicit class AnyExtension[A](x: A) { - def when(p: A => Boolean, show: A => String, default: String = "") = if (p(x)) show(x) else default - } - implicit class IterableExtensions[A](val it: Iterable[A]) extends AnyVal - { - def opt(show: Iterable[A] => String = _.mkString, default: String = ""): String = - if (it.isEmpty) default else show(it) - - def rep(show: A => String = _.toString, sep: String = ", "): String = it.map(show).mkString(sep) - - def asTypeParams(show: A => String = _.toString) = - if (it.nonEmpty) it.map(show).mkString("[", ", ", "]") else "" - - def optList(start: String, end: String, sep: String = ", ", show: A => String = _.toString) = - if (it.nonEmpty) it.map(show).mkString(start, sep, end) else "" - } - - implicit class OptionExtensions[A](val opt: Option[A]) extends AnyVal { - def opt(show: A => String = _.toString, default: String = ""): String = opt match { - case None => default - case Some(a) => show(a) - } - def ifDefined(value: String): String = if (opt.isDefined) value else "" - } - - implicit class BooleanExtensions(val opt: Boolean) extends AnyVal { - def opt(show: => String, default: => String = ""): String = if(opt) show else default - } - - def join(xs: Any*) = xs.map { - case x: Iterable[_] => x.rep() - case x => x.toString - }.filter(_.nonEmpty).rep() -} diff --git a/common/src/main/scala/scalan/util/StringUtil.scala b/common/src/main/scala/scalan/util/StringUtil.scala index b9be964fb0..d62c728e19 100644 --- a/common/src/main/scala/scalan/util/StringUtil.scala +++ b/common/src/main/scala/scalan/util/StringUtil.scala @@ -38,8 +38,6 @@ object StringUtil { implicit class StringUtilExtensions(val str: String) extends AnyVal { def isNullOrEmpty = str == null || str.isEmpty - def stripAndTrim = str.stripMargin.stripPrefix("\n").stripPrefix("\r\n").stripLineEnd - def lastComponent(sep: Char): String = { str.substring(str.lastIndexOf(sep) + 1) } diff --git a/common/src/main/scala/sigmastate/kiama/rewriting/Rewriter.scala b/common/src/main/scala/sigmastate/kiama/rewriting/Rewriter.scala index 6a2b8635c9..922a1368d6 100644 --- a/common/src/main/scala/sigmastate/kiama/rewriting/Rewriter.scala +++ b/common/src/main/scala/sigmastate/kiama/rewriting/Rewriter.scala @@ -11,7 +11,9 @@ package sigmastate.kiama package rewriting -import scala.collection.mutable +import scalan.reflection.{RClass, RConstructor} + +import scala.collection.concurrent.TrieMap /** * Strategy-based term rewriting in the style of Stratego (http://strategoxt.org/). @@ -218,13 +220,22 @@ trait Rewriter { */ object Duplicator { - import java.lang.reflect.Constructor - + /** + * The type of a duplicator. A duplicator takes a product `t` and + * an array of new children and returns a new product with the + * same constructor as `t` but with the new children. + */ type Duper = (Any, Array[AnyRef]) => Any - object MakeDuper extends (Class[_] => Duper) { + /** + * This duper always returns the same product that it is given for singleton Scala objects. + * It uses the `MODULE$` field to determine if a class is a singleton object. + * Otherwise, it uses the first constructor it finds to make a new product. + */ + object MakeDuper extends (RClass[_] => Duper) { - def apply(clazz : Class[_]) : Duper = + /** Make a duper for the given class. */ + def apply(clazz : RClass[_]) : Duper = try { // See if this class has a MODULE$ field. This field is used by Scala // to hold a singleton instance and is only present in singleton classes @@ -246,7 +257,8 @@ trait Rewriter { makeInstance(ctors(0), children) } - def makeInstance(ctor : Constructor[_], children : Array[AnyRef]) : Any = + /** Make an instance using the given constructor with the given children as arguments. */ + def makeInstance(ctor : RConstructor[_], children : Array[AnyRef]) : Any = try { ctor.newInstance(unboxPrimitives(ctor, children) : _*) } catch { @@ -255,9 +267,11 @@ trait Rewriter { |Common cause: term classes are nested in another class, move them to the top level""".stripMargin) } - def unboxPrimitives(ctor : Constructor[_], children : Array[AnyRef]) : Array[AnyRef] = { - val numChildren = ctor.getParameterTypes().length + /** Unbox primitive values in the given array of children using type information of + * the given constructor. */ + def unboxPrimitives(ctor : RConstructor[_], children : Array[AnyRef]) : Array[AnyRef] = { val childrenTypes = ctor.getParameterTypes() + val numChildren = childrenTypes.length val newChildren = new Array[AnyRef](numChildren) var i = 0 while (i < numChildren) { @@ -270,6 +284,7 @@ trait Rewriter { newChildren } + /** Unbox a primitive value. */ def unboxAnyVal(s : AnyRef) : AnyRef = s match { case p : Product if p.productArity == 1 => @@ -280,24 +295,26 @@ trait Rewriter { } - private val cache = mutable.HashMap.empty[Class[_], Duper] + /** All memoized duppers. */ + private val dupers = TrieMap.empty[RClass[_], Duper] /** Obtains a duper for the given class lazily. and memoize it in the `cache` map. * This is the simplest solution, but not the most efficient for concurrent access. */ - def getDuper(clazz: Class[_]): Duper = synchronized { // TODO optimize: avoid global sync - val duper = cache.get(clazz) match { + def getDuper(clazz: RClass[_]): Duper = synchronized { // TODO optimize: avoid global sync (if this really is a bottleneck) + val duper = dupers.get(clazz) match { case Some(d) => d case None => val d = MakeDuper(clazz) - cache.put(clazz, d) + dupers.put(clazz, d) d } duper } - + + /** Apply the duplicator to the given product and children. */ def apply[T <: Product](t : T, children : Array[AnyRef]) : T = { - val clazz = t.getClass + val clazz = RClass(t.getClass) val duper = getDuper(clazz) duper(t, children).asInstanceOf[T] } diff --git a/common/src/main/scala/scalan/util/BenchmarkUtil.scala b/common/src/test/scala/scalan/util/BenchmarkUtil.scala similarity index 84% rename from common/src/main/scala/scalan/util/BenchmarkUtil.scala rename to common/src/test/scala/scalan/util/BenchmarkUtil.scala index ffaed0b16b..59cc68a37f 100644 --- a/common/src/main/scala/scalan/util/BenchmarkUtil.scala +++ b/common/src/test/scala/scalan/util/BenchmarkUtil.scala @@ -1,17 +1,19 @@ package scalan.util -import scala.concurrent.duration.Duration +import debox.cfor + import scala.concurrent.{Future, Await} +import scala.concurrent.duration.Duration import scala.concurrent.ExecutionContext.Implicits.global /** Helper classes for measuring time and printing timings. */ object BenchmarkUtil { - /** Execute `action` given number of iterations printing time for each iteration * and the total time. */ - def measure[T](nIters: Int, okShowIterTime: Boolean = true)(action: Int => Unit): Unit = { + def measure[T](nIters: Int, okShowIterTime: Boolean = true, okShowTotalTime: Boolean = true) + (action: Int => Unit): Unit = { var sum = 0L - for (i <- 0 until nIters) { + cfor(0)(_ < nIters, _ + 1) { i => val start = System.currentTimeMillis() val res = action(i) val end = System.currentTimeMillis() @@ -20,7 +22,7 @@ object BenchmarkUtil { println(s"Iter $i: $iterTime ms") sum += iterTime } - println(s"Total time: $sum ms") + if (okShowTotalTime) println(s"Total time: $sum ms") } /** Execute block and measure the time of its execution. */ @@ -39,7 +41,6 @@ object BenchmarkUtil { (res, end - start) } - def runTasks(nTasks: Int)(block: Int => Unit) = { val (_, total) = measureTime { val tasks = (1 to nTasks).map(iTask => Future(block(iTask))) @@ -47,5 +48,4 @@ object BenchmarkUtil { } println(s"Completed $nTasks tasks in $total msec") } - } diff --git a/common/src/main/scala/scalan/util/FileUtil.scala b/common/src/test/scala/scalan/util/FileUtil.scala similarity index 100% rename from common/src/main/scala/scalan/util/FileUtil.scala rename to common/src/test/scala/scalan/util/FileUtil.scala diff --git a/common/src/test/scala/scalan/util/PrintExtensions.scala b/common/src/test/scala/scalan/util/PrintExtensions.scala new file mode 100644 index 0000000000..d3b87441dd --- /dev/null +++ b/common/src/test/scala/scalan/util/PrintExtensions.scala @@ -0,0 +1,66 @@ +package scalan.util + +/** Helper methods for pretty printing of collections and optional values. */ +object PrintExtensions { + implicit class AnyExtension[A](x: A) { + /** Prints `x` if `p(x)` is true, otherwise prints `default`. */ + def when( + p: A => Boolean, + show: A => String, + default: String = "") = if (p(x)) show(x) else default + } + + implicit class IterableExtensions[A](val it: Iterable[A]) extends AnyVal { + /** Prints `show(it)` if `it` is not empty, otherwise prints `default`. */ + def opt(show: Iterable[A] => String = _.mkString, default: String = ""): String = + if (it.isEmpty) default else show(it) + + /** Prints `show(x)` for each `x` in `it` and `sep` between elements. */ + def rep( + show: A => String = _.toString, + sep: String = ", "): String = it.map(show).mkString(sep) + + def asTypeParams(show: A => String = _.toString) = + if (it.nonEmpty) it.map(show).mkString("[", ", ", "]") else "" + + /** Prints `start` and `end` around content, where + * content = `show(x)` for each `x` in `it` and `sep` between elements. */ + def optList( + start: String, + end: String, + sep: String = ", ", + show: A => String = _.toString) = + if (it.nonEmpty) it.map(show).mkString(start, sep, end) else "" + } + + implicit class OptionExtensions[A](val opt: Option[A]) extends AnyVal { + /** Prints `show(a)` if `opt = Some(a)`, otherwise prints `default`. */ + def opt(show: A => String = _.toString, default: String = ""): String = opt match { + case None => default + case Some(a) => show(a) + } + + /** Returns the given value if the `opt` is defined, otherwise an empty string. */ + def ifDefined(value: String): String = if (opt.isDefined) value else "" + } + + implicit class BooleanExtensions(val opt: Boolean) extends AnyVal { + /** Prints `show` if `opt` is true, otherwise prints `default`. */ + def opt(show: => String, default: => String = ""): String = if (opt) show else default + } + + /** Joins the string representations of the given elements. + * + * This function takes a variable number of arguments and returns a string that is the + * concatenation of their string representations. If an argument is an Iterable, its + * elements are recursively joined using this function. Empty strings are filtered out + * before joining. + * + * @param xs The elements to join + * @return The joined string + */ + def join(xs: Any*) = xs.map { + case x: Iterable[_] => x.rep() + case x => x.toString + }.filter(_.nonEmpty).rep() +} diff --git a/common/src/main/scala/scalan/util/ProcessUtil.scala b/common/src/test/scala/scalan/util/ProcessUtil.scala similarity index 99% rename from common/src/main/scala/scalan/util/ProcessUtil.scala rename to common/src/test/scala/scalan/util/ProcessUtil.scala index 32f278b5e4..f30d1fc2e0 100644 --- a/common/src/main/scala/scalan/util/ProcessUtil.scala +++ b/common/src/test/scala/scalan/util/ProcessUtil.scala @@ -1,7 +1,6 @@ package scalan.util import java.io.File - import scala.collection.mutable import scala.sys.process.ProcessLogger diff --git a/core-lib/src/main/scala/special/CoreLibReflection.scala b/core-lib/src/main/scala/special/CoreLibReflection.scala new file mode 100644 index 0000000000..7e52e53d37 --- /dev/null +++ b/core-lib/src/main/scala/special/CoreLibReflection.scala @@ -0,0 +1,443 @@ +package special + +import scalan.RType +import scalan.reflection.CommonReflection.registerClassEntry +import scalan.reflection._ +import special.collection.{CollBuilder, Coll} +import special.sigma._ +import special.wrappers.{OptionWrapSpec, RTypeWrapSpec} + +/** Registrations of reflection metadata for core-lib module. + * For each class of this module that needs reflection metadata, + * we register a class entry with the necessary information. + * Only information that is needed at runtime is registered. + */ +object CoreLibReflection { + val reflection = CommonReflection + + { val clazz = classOf[SigmaProp] + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "$bar$bar", Array[Class[_]](classOf[SigmaProp])) { (obj, args) => + obj.asInstanceOf[SigmaProp].$bar$bar(args(0).asInstanceOf[SigmaProp]) + }, + mkMethod(clazz, "isValid", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[SigmaProp].isValid + }, + mkMethod(clazz, "propBytes", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[SigmaProp].propBytes + }, + mkMethod(clazz, "$amp$amp", Array[Class[_]](classOf[SigmaProp])) { (obj, args) => + obj.asInstanceOf[SigmaProp].$amp$amp(args(0).asInstanceOf[SigmaProp]) + } + ) + ) + } + + { val clazz = classOf[special.sigma.BigInt] + val paramTypes = Array[Class[_]](clazz) + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "add", paramTypes) { (obj, args) => + obj.asInstanceOf[BigInt].add(args(0).asInstanceOf[BigInt]) + }, + mkMethod(clazz, "max", paramTypes) { (obj, args) => + obj.asInstanceOf[BigInt].max(args(0).asInstanceOf[BigInt]) + }, + mkMethod(clazz, "min", paramTypes) { (obj, args) => + obj.asInstanceOf[BigInt].min(args(0).asInstanceOf[BigInt]) + }, + mkMethod(clazz, "subtract", paramTypes) { (obj, args) => + obj.asInstanceOf[BigInt].subtract(args(0).asInstanceOf[BigInt]) + }, + mkMethod(clazz, "multiply", paramTypes) { (obj, args) => + obj.asInstanceOf[BigInt].multiply(args(0).asInstanceOf[BigInt]) + }, + mkMethod(clazz, "mod", paramTypes) { (obj, args) => + obj.asInstanceOf[BigInt].mod(args(0).asInstanceOf[BigInt]) + }, + mkMethod(clazz, "divide", paramTypes) { (obj, args) => + obj.asInstanceOf[BigInt].divide(args(0).asInstanceOf[BigInt]) + } + ) + ) + } + + { val clazz = classOf[CollBuilder] + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "xor", Array[Class[_]](classOf[Coll[_]], classOf[Coll[_]])) { (obj, args) => + obj.asInstanceOf[CollBuilder].xor( + args(0).asInstanceOf[Coll[Byte]], + args(1).asInstanceOf[Coll[Byte]]) + }, + mkMethod(clazz, "fromItems", Array[Class[_]](classOf[Seq[_]], classOf[RType[_]])) { (obj, args) => + obj.asInstanceOf[CollBuilder].fromItems[Any]( + args(0).asInstanceOf[Seq[Any]]: _*)(args(1).asInstanceOf[RType[Any]]) + }, + mkMethod(clazz, "replicate", Array[Class[_]](classOf[Int], classOf[Object], classOf[RType[_]])) { (obj, args) => + obj.asInstanceOf[CollBuilder].replicate(args(0).asInstanceOf[Int], + args(1).asInstanceOf[Any])(args(2).asInstanceOf[RType[Any]]) + } + ) + ) + } + + { val clazz = classOf[OptionWrapSpec] + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "getOrElse", Array[Class[_]](classOf[Option[_]], classOf[Function0[_]])) { (obj, args) => + val opt = args(0).asInstanceOf[Option[Any]] + val defaultFunc = args(1).asInstanceOf[Function0[Any]] + obj.asInstanceOf[OptionWrapSpec].getOrElse(opt, defaultFunc()) + }, + mkMethod(clazz, "isDefined", Array[Class[_]](classOf[Option[_]])) { (obj, args) => + obj.asInstanceOf[OptionWrapSpec].isDefined(args(0).asInstanceOf[Option[_]]) + }, + mkMethod(clazz, "filter", Array[Class[_]](classOf[Option[_]], classOf[Function1[_,_]])) { (obj, args) => + obj.asInstanceOf[OptionWrapSpec].filter( + args(0).asInstanceOf[Option[Any]], args(1).asInstanceOf[Any => Boolean]) + }, + mkMethod(clazz, "map", Array[Class[_]](classOf[Option[_]], classOf[Function1[_,_]])) { (obj, args) => + obj.asInstanceOf[OptionWrapSpec].map( + args(0).asInstanceOf[Option[Any]], args(1).asInstanceOf[Any => Any]) + }, + mkMethod(clazz, "get", Array[Class[_]](classOf[Option[_]])) { (obj, args) => + obj.asInstanceOf[OptionWrapSpec].get(args(0).asInstanceOf[Option[_]]) + } + ) + ) + } + + { val clazz = classOf[Coll[_]] + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "updated", Array[Class[_]](classOf[Int], classOf[java.lang.Object])) { (obj, args) => + obj.asInstanceOf[Coll[Any]].updated(args(0).asInstanceOf[Int], args(1).asInstanceOf[Any]) + }, + mkMethod(clazz, "flatMap", Array[Class[_]](classOf[Function1[_, _]], classOf[RType[_]])) { (obj, args) => + obj.asInstanceOf[Coll[Any]].flatMap( + args(0).asInstanceOf[Any => Coll[Any]])(args(1).asInstanceOf[RType[Any]]) + }, + mkMethod(clazz, "apply", Array[Class[_]](classOf[Int])) { (obj, args) => + obj.asInstanceOf[Coll[_]].apply(args(0).asInstanceOf[Int]) + }, + mkMethod(clazz, "append", Array[Class[_]](classOf[Coll[_]])) { (obj, args) => + obj.asInstanceOf[Coll[Any]].append(args(0).asInstanceOf[Coll[Any]]) + }, + mkMethod(clazz, "indexOf", Array[Class[_]](classOf[java.lang.Object], classOf[Int])) { (obj, args) => + obj.asInstanceOf[Coll[Any]].indexOf(args(0).asInstanceOf[Any], args(1).asInstanceOf[Int]) + }, + mkMethod(clazz, "map", Array[Class[_]](classOf[Function1[_, _]], classOf[RType[_]])) { (obj, args) => + obj.asInstanceOf[Coll[Any]].map(args(0).asInstanceOf[Any => Any])(args(1).asInstanceOf[RType[Any]]) + } + ) + ) + } + + { val clazz = classOf[AvlTree] + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "updateOperations", Array[Class[_]](classOf[Byte])) { (obj, args) => + obj.asInstanceOf[AvlTree].updateOperations(args(0).asInstanceOf[Byte]) + }, + mkMethod(clazz, "getMany", Array[Class[_]](classOf[Coll[_]], classOf[Coll[_]])) { (obj, args) => + obj.asInstanceOf[AvlTree].getMany(args(0).asInstanceOf[Coll[Coll[Byte]]], + args(1).asInstanceOf[Coll[Byte]]) + }, + mkMethod(clazz, "update", Array[Class[_]](classOf[Coll[_]], classOf[Coll[_]])) { (obj, args) => + obj.asInstanceOf[AvlTree].update(args(0).asInstanceOf[Coll[(Coll[Byte], Coll[Byte])]], + args(1).asInstanceOf[Coll[Byte]]) + }, + mkMethod(clazz, "keyLength", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[AvlTree].keyLength + }, + mkMethod(clazz, "enabledOperations", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[AvlTree].enabledOperations + }, + mkMethod(clazz, "updateDigest", Array[Class[_]](classOf[Coll[_]])) { (obj, args) => + obj.asInstanceOf[AvlTree].updateDigest(args(0).asInstanceOf[Coll[Byte]]) + }, + mkMethod(clazz, "digest", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[AvlTree].digest + }, + mkMethod(clazz, "insert", Array[Class[_]](classOf[Coll[_]], classOf[Coll[_]])) { (obj, args) => + obj.asInstanceOf[AvlTree].insert(args(0).asInstanceOf[Coll[(Coll[Byte], Coll[Byte])]], + args(1).asInstanceOf[Coll[Byte]]) + }, + mkMethod(clazz, "isRemoveAllowed", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[AvlTree].isRemoveAllowed + }, + mkMethod(clazz, "valueLengthOpt", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[AvlTree].valueLengthOpt + }, + mkMethod(clazz, "get", Array[Class[_]](classOf[Coll[_]], classOf[Coll[_]])) { (obj, args) => + obj.asInstanceOf[AvlTree].get(args(0).asInstanceOf[Coll[Byte]], + args(1).asInstanceOf[Coll[Byte]]) + }, + mkMethod(clazz, "remove", Array[Class[_]](classOf[Coll[_]], classOf[Coll[_]])) { (obj, args) => + obj.asInstanceOf[AvlTree].remove(args(0).asInstanceOf[Coll[Coll[Byte]]], args(1).asInstanceOf[Coll[Byte]]) + }, + mkMethod(clazz, "contains", Array[Class[_]](classOf[Coll[_]], classOf[Coll[_]])) { (obj, args) => + obj.asInstanceOf[AvlTree].contains(args(0).asInstanceOf[Coll[Byte]], + args(1).asInstanceOf[Coll[Byte]]) + }, + mkMethod(clazz, "isUpdateAllowed", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[AvlTree].isUpdateAllowed + }, + mkMethod(clazz, "isInsertAllowed", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[AvlTree].isInsertAllowed + } + ) + ) + } + + { val clazz = classOf[Box] + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "value", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Box].value + }, + mkMethod(clazz, "id", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Box].id + }, + mkMethod(clazz, "creationInfo", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Box].creationInfo + }, + mkMethod(clazz, "bytes", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Box].bytes + }, + mkMethod(clazz, "tokens", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Box].tokens + }, + mkMethod(clazz, "getReg", Array[Class[_]](classOf[Int], classOf[RType[_]])) { (obj, args) => + obj.asInstanceOf[Box].getReg(args(0).asInstanceOf[Int])(args(1).asInstanceOf[RType[_]]) + }, + mkMethod (clazz, "bytesWithoutRef", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Box].bytesWithoutRef + }, + mkMethod(clazz, "propositionBytes", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Box].propositionBytes + } + ) + ) + } + + { val clazz = classOf[Context] + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "LastBlockUtxoRootHash", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Context].LastBlockUtxoRootHash + }, + mkMethod(clazz, "dataInputs", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Context].dataInputs + }, + mkMethod(clazz, "selfBoxIndex", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Context].selfBoxIndex + }, + mkMethod(clazz, "INPUTS", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Context].INPUTS + }, + mkMethod(clazz, "minerPubKey", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Context].minerPubKey + }, + mkMethod(clazz, "HEIGHT", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Context].HEIGHT + }, + mkMethod(clazz, "OUTPUTS", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Context].OUTPUTS + }, + mkMethod(clazz, "SELF", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Context].SELF + }, + mkMethod(clazz, "preHeader", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Context].preHeader + }, + mkMethod(clazz, "getVar", Array[Class[_]](classOf[Byte], classOf[RType[_]])) { (obj, args) => + obj.asInstanceOf[Context].getVar(args(0).asInstanceOf[Byte])(args(1).asInstanceOf[RType[_]]) + }, + mkMethod(clazz, "headers", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Context].headers + } + ) + ) + } + + { val clazz = classOf[GroupElement] + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "exp", Array[Class[_]](classOf[BigInt])) { (obj, args) => + obj.asInstanceOf[GroupElement].exp(args(0).asInstanceOf[BigInt]) + }, + mkMethod(clazz, "multiply", Array[Class[_]](classOf[GroupElement])) { (obj, args) => + obj.asInstanceOf[GroupElement].multiply(args(0).asInstanceOf[GroupElement]) + }, + mkMethod(clazz, "getEncoded", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[GroupElement].getEncoded + }, + mkMethod(clazz, "negate", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[GroupElement].negate + } + ) + ) + } + + { val clazz = classOf[Header] + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "minerPk", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].minerPk + }, + mkMethod(clazz, "powNonce", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].powNonce + }, + mkMethod(clazz, "transactionsRoot", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].transactionsRoot + }, + mkMethod(clazz, "powOnetimePk", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].powOnetimePk + }, + mkMethod(clazz, "nBits", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].nBits + }, + mkMethod(clazz, "votes", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].votes + }, + mkMethod(clazz, "id", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].id + }, + mkMethod(clazz, "version", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].version + }, + mkMethod(clazz, "parentId", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].parentId + }, + mkMethod(clazz, "timestamp", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].timestamp + }, + mkMethod(clazz, "height", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].height + }, + mkMethod(clazz, "extensionRoot", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].extensionRoot + }, + mkMethod(clazz, "ADProofsRoot", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].ADProofsRoot + }, + mkMethod(clazz, "stateRoot", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].stateRoot + }, + mkMethod(clazz, "powDistance", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[Header].powDistance + } + ) + ) + } + + { val clazz = classOf[PreHeader] + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "minerPk", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[PreHeader].minerPk + }, + mkMethod(clazz, "votes", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[PreHeader].votes + }, + mkMethod(clazz, "nBits", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[PreHeader].nBits + }, + mkMethod(clazz, "version", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[PreHeader].version + }, + mkMethod(clazz, "timestamp", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[PreHeader].timestamp + }, + mkMethod(clazz, "parentId", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[PreHeader].parentId + }, + mkMethod(clazz, "height", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[PreHeader].height + } + ) + ) + } + + { val clazz = classOf[SigmaDslBuilder] + val cColl = classOf[Coll[_]] + val cGroupElement = classOf[GroupElement] + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "byteArrayToLong", Array[Class[_]](cColl)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].byteArrayToLong(args(0).asInstanceOf[Coll[Byte]]) + }, + mkMethod(clazz, "anyOf", Array[Class[_]](cColl)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].anyOf(args(0).asInstanceOf[Coll[Boolean]]) + }, + mkMethod(clazz, "allZK", Array[Class[_]](cColl)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].allZK(args(0).asInstanceOf[Coll[SigmaProp]]) + }, + mkMethod(clazz, "xorOf", Array[Class[_]](cColl)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].xorOf(args(0).asInstanceOf[Coll[Boolean]]) + }, + mkMethod(clazz, "substConstants", Array[Class[_]](cColl, cColl, cColl)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].substConstants(args(0).asInstanceOf[Coll[Byte]], + args(1).asInstanceOf[Coll[Int]], args(2).asInstanceOf[Coll[Any]]) + }, + mkMethod(clazz, "groupGenerator", Array[Class[_]]()) { (obj, _) => + obj.asInstanceOf[SigmaDslBuilder].groupGenerator + }, + mkMethod(clazz, "sigmaProp", Array[Class[_]](classOf[Boolean])) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].sigmaProp(args(0).asInstanceOf[Boolean]) + }, + mkMethod(clazz, "proveDlog", Array[Class[_]](cGroupElement)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].proveDlog(args(0).asInstanceOf[GroupElement]) + }, + mkMethod(clazz, "blake2b256", Array[Class[_]](cColl)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].blake2b256(args(0).asInstanceOf[Coll[Byte]]) + }, + mkMethod(clazz, "longToByteArray", Array[Class[_]](classOf[Long])) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].longToByteArray(args(0).asInstanceOf[Long]) + }, + mkMethod(clazz, "xor", Array[Class[_]](cColl, cColl)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].xor(args(0).asInstanceOf[Coll[Byte]], + args(1).asInstanceOf[Coll[Byte]]) + }, + mkMethod(clazz, "atLeast", Array[Class[_]](classOf[Int], cColl)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].atLeast(args(0).asInstanceOf[Int], + args(1).asInstanceOf[Coll[SigmaProp]]) + }, + mkMethod(clazz, "byteArrayToBigInt", Array[Class[_]](cColl)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].byteArrayToBigInt(args(0).asInstanceOf[Coll[Byte]]) + }, + mkMethod(clazz, "allOf", Array[Class[_]](cColl)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].allOf(args(0).asInstanceOf[Coll[Boolean]]) + }, + mkMethod(clazz, "proveDHTuple", Array[Class[_]](cGroupElement, cGroupElement, cGroupElement, cGroupElement)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].proveDHTuple(args(0).asInstanceOf[GroupElement], + args(1).asInstanceOf[GroupElement], + args(2).asInstanceOf[GroupElement], + args(3).asInstanceOf[GroupElement]) + }, + mkMethod(clazz, "anyZK", Array[Class[_]](cColl)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].anyZK(args(0).asInstanceOf[Coll[SigmaProp]]) + }, + mkMethod(clazz, "sha256", Array[Class[_]](cColl)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].sha256(args(0).asInstanceOf[Coll[Byte]]) + }, + mkMethod(clazz, "decodePoint", Array[Class[_]](cColl)) { (obj, args) => + obj.asInstanceOf[SigmaDslBuilder].decodePoint(args(0).asInstanceOf[Coll[Byte]]) + } + ) + ) + } + + { val clazz = classOf[RTypeWrapSpec] + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "name", Array[Class[_]](classOf[RType[_]])) { (obj, args) => + obj.asInstanceOf[RTypeWrapSpec].name(args(0).asInstanceOf[RType[_]]) + } + ) + ) + } +} diff --git a/library-api/src/main/scala/special/Types.scala b/core-lib/src/main/scala/special/Types.scala similarity index 61% rename from library-api/src/main/scala/special/Types.scala rename to core-lib/src/main/scala/special/Types.scala index 954a1baee7..5b37d57d4e 100644 --- a/library-api/src/main/scala/special/Types.scala +++ b/core-lib/src/main/scala/special/Types.scala @@ -1,26 +1,34 @@ package special -import scalan.RType import scalan.util.CollectionUtil - +import scalan.RType import scala.reflect.ClassTag -import scalan.RType.SomeType import special.collection.Coll +import scalan.RType.SomeType object Types { + /** Generic representation of tuples values. */ type TupleData = Coll[Any] + /** Returns an RType object representing a tuple type with the given SomeType array types. + * @param types An array of SomeType representing the types of each item in the tuple. + * @return An RType object for the tuple type. + */ def tupleRType(types: Array[SomeType]): RType[TupleData] = TupleType(types) + /** Descriptor (in RType family) of tuple types. + * @param items types of tuple items + */ case class TupleType(items: Array[SomeType]) extends RType[TupleData] { - val classTag: ClassTag[TupleData] = scala.reflect.classTag[TupleData] + override val classTag: ClassTag[TupleData] = scala.reflect.classTag[TupleData] + override def name: String = items.map(_.name).mkString("(", ", ", ")") + override def hashCode(): Int = CollectionUtil.deepHashCode(items) + override def equals(obj: Any): Boolean = (this eq obj.asInstanceOf[AnyRef]) || (obj match { case that: TupleType => java.util.Arrays.equals(items.asInstanceOf[Array[AnyRef]], that.items.asInstanceOf[Array[AnyRef]]) case _ => false }) } - } - diff --git a/library-api/src/main/scala/special/collection/Colls.scala b/core-lib/src/main/scala/special/collection/Colls.scala similarity index 100% rename from library-api/src/main/scala/special/collection/Colls.scala rename to core-lib/src/main/scala/special/collection/Colls.scala diff --git a/library-impl/src/main/scala/special/collection/CollsOverArrays.scala b/core-lib/src/main/scala/special/collection/CollsOverArrays.scala similarity index 100% rename from library-impl/src/main/scala/special/collection/CollsOverArrays.scala rename to core-lib/src/main/scala/special/collection/CollsOverArrays.scala diff --git a/library-impl/src/main/scala/special/collection/ExtensionMethods.scala b/core-lib/src/main/scala/special/collection/ExtensionMethods.scala similarity index 100% rename from library-impl/src/main/scala/special/collection/ExtensionMethods.scala rename to core-lib/src/main/scala/special/collection/ExtensionMethods.scala diff --git a/library-impl/src/main/scala/special/collection/Helpers.scala b/core-lib/src/main/scala/special/collection/Helpers.scala similarity index 100% rename from library-impl/src/main/scala/special/collection/Helpers.scala rename to core-lib/src/main/scala/special/collection/Helpers.scala diff --git a/library-api/src/main/scala/special/collection/package.scala b/core-lib/src/main/scala/special/collection/package.scala similarity index 73% rename from library-api/src/main/scala/special/collection/package.scala rename to core-lib/src/main/scala/special/collection/package.scala index 7eaa511965..6a69271223 100644 --- a/library-api/src/main/scala/special/collection/package.scala +++ b/core-lib/src/main/scala/special/collection/package.scala @@ -2,7 +2,10 @@ package special import scala.language.implicitConversions import scalan.RType -import scala.reflect.{ClassTag, classTag} +import scalan.reflection.CommonReflection.registerClassEntry +import scalan.reflection.SRMethod + +import scala.reflect.{classTag, ClassTag} package collection { case class CollType[A](tItem: RType[A]) extends RType[Coll[A]] { @@ -12,6 +15,9 @@ package collection { } package object collection { + /** Forces reflection data initialization */ + val reflection = CoreLibReflection + implicit def collRType[A](implicit tA: RType[A]): RType[Coll[A]] = CollType[A](tA) implicit def extendCollType[A](ct: RType[Coll[A]]): CollType[A] = ct.asInstanceOf[CollType[A]] implicit val collBuilderRType: RType[CollBuilder] = RType.fromClassTag(classTag[CollBuilder]) diff --git a/sigma-api/src/main/scala/special/sigma/SigmaDsl.scala b/core-lib/src/main/scala/special/sigma/SigmaDsl.scala similarity index 100% rename from sigma-api/src/main/scala/special/sigma/SigmaDsl.scala rename to core-lib/src/main/scala/special/sigma/SigmaDsl.scala diff --git a/sigma-api/src/main/scala/special/sigma/package.scala b/core-lib/src/main/scala/special/sigma/package.scala similarity index 94% rename from sigma-api/src/main/scala/special/sigma/package.scala rename to core-lib/src/main/scala/special/sigma/package.scala index dcbb71ef64..a81b27a45b 100644 --- a/sigma-api/src/main/scala/special/sigma/package.scala +++ b/core-lib/src/main/scala/special/sigma/package.scala @@ -1,7 +1,6 @@ package special import java.math.BigInteger - import scalan.RType import scalan.RType.GeneralType @@ -11,6 +10,8 @@ import scala.reflect.classTag * @see [[RType]] class */ package object sigma { + /** Forces reflection data initialization */ + val reflection = CoreLibReflection implicit val BigIntRType: RType[BigInt] = GeneralType(classTag[BigInt]) implicit val GroupElementRType: RType[GroupElement] = GeneralType(classTag[GroupElement]) @@ -29,4 +30,5 @@ package object sigma { implicit val SigmaDslBuilderRType: RType[SigmaDslBuilder] = RType.fromClassTag(classTag[SigmaDslBuilder]) implicit val BigIntegerRType: RType[BigInteger] = GeneralType(classTag[BigInteger]) + } \ No newline at end of file diff --git a/core-lib/src/main/scala/special/wrappers/WrappersSpec.scala b/core-lib/src/main/scala/special/wrappers/WrappersSpec.scala new file mode 100644 index 0000000000..e539d299d4 --- /dev/null +++ b/core-lib/src/main/scala/special/wrappers/WrappersSpec.scala @@ -0,0 +1,23 @@ +package special.wrappers + +import scalan.{WrapSpec, RType} + +/** Base class for wrappers of such types as WOption, WRType etc. + * Used in graph IR to implement method invocation. + */ +trait WrapSpecBase extends WrapSpec { +} + +/** Wrappers spec for Option */ +class OptionWrapSpec extends WrapSpecBase { + def get[A](xs: Option[A]): A = xs.get + def getOrElse[A](xs: Option[A], default: => A): A = xs.getOrElse(default) + def map[A,B](xs: Option[A], f: A => B): Option[B] = xs.map(f) + def filter[A](xs: Option[A], f: A => Boolean): Option[A] = xs.filter(f) + def isDefined[A](xs: Option[A]): Boolean = xs.isDefined +}; + +/** Wrappers spec for RType */ +class RTypeWrapSpec extends WrapSpecBase { + def name[T](d: RType[T]): String = d.name +} diff --git a/library-api/src/test/scala/special/TypesTests.scala b/core-lib/src/test/scala/special/TypesTests.scala similarity index 100% rename from library-api/src/test/scala/special/TypesTests.scala rename to core-lib/src/test/scala/special/TypesTests.scala diff --git a/core/src/main/resources/reference.conf b/graph-ir/src/main/resources/reference.conf similarity index 100% rename from core/src/main/resources/reference.conf rename to graph-ir/src/main/resources/reference.conf diff --git a/core/src/main/scala/scalan/Base.scala b/graph-ir/src/main/scala/scalan/Base.scala similarity index 96% rename from core/src/main/scala/scalan/Base.scala rename to graph-ir/src/main/scala/scalan/Base.scala index c8a9ea52fd..3674e32372 100644 --- a/core/src/main/scala/scalan/Base.scala +++ b/graph-ir/src/main/scala/scalan/Base.scala @@ -1,15 +1,14 @@ package scalan -import java.lang.reflect.{Constructor => Constr} import java.util.Arrays import scalan.OverloadHack.Overloaded1 import scala.language.implicitConversions import scala.annotation.implicitNotFound import scala.annotation.unchecked.uncheckedVariance -import scalan.compilation.GraphVizConfig import scalan.util.StringUtil import debox.{cfor, Buffer => DBuffer} +import scalan.reflection.{RClass, RConstructor} import scala.collection.compat.immutable.ArraySeq import scala.collection.mutable @@ -254,14 +253,6 @@ abstract class Base { scalan: Scalan => /** Method to embedd source type instance into graph IR. */ def lift(x: ST): Ref[T] - /** Extract lifted value from graph node. - * @return constValue from LiftedConst if `w` refers to such a node. - * @throws StagingException if `w` is not refering to the appropritate LiftedConst node. */ - def unlift(w: Ref[T]): ST - - protected def unliftError(w: Ref[T]) = - !!!(s"Cannot unlift simbol $w using $this") - /** We assume only single Liftable[ST, T] implementation for every IR type `T`. * And all instances of it are equal. */ override def hashCode(): Int = eW.hashCode() + 1 // to make Elem and Liftable differ @@ -287,7 +278,6 @@ abstract class Base { scalan: Scalan => /** Liftable evidence for primitive (base) types (used in BaseElemLiftable). */ class BaseLiftable[T](implicit val eW: Elem[T], override val sourceType: RType[T]) extends Liftable[T, T] { def lift(x: T) = toRep(x) - def unlift(w: Ref[T]) = valueFromRep(w) } /** Liftable evidence between `(SA, SB)` and `(A, B)` types. */ @@ -296,7 +286,6 @@ abstract class Base { scalan: Scalan => override val sourceType: RType[(SA, SB)] = RType.pairRType(lA.sourceType, lB.sourceType) def lift(x: (SA, SB)): Ref[(A, B)] = Pair(lA.lift(x._1), lB.lift(x._2)) - def unlift(w: Ref[(A, B)]): (SA, SB) = { val Pair(wa, wb) = w; (lA.unlift(wa), lB.unlift(wb)) } } /** Every function can be lifted to the graph IR. */ @@ -310,10 +299,6 @@ abstract class Base { scalan: Scalan => val eW: Elem[A => B] = funcElement(lA.eW, lB.eW) override val sourceType = RType.funcRType(lA.sourceType, lB.sourceType) def lift(srcF: SA => SB): Ref[A => B] = FuncConst[SA,SB,A,B](srcF) - def unlift(f: Ref[A => B]): SA => SB = f.node match { - case FuncConst(srcF) => srcF.asInstanceOf[SA => SB] - case _ => unliftError(f) - } } implicit lazy val BooleanIsLiftable = asLiftable[Boolean,Boolean](BooleanElement.liftable) @@ -401,11 +386,6 @@ abstract class Base { scalan: Scalan => def toStringWithDefinition: String def varNameWithType = varName + ":" + elem.name - /** Build graph of nodes starting from this node, generate dot file, - * and open it using system default viewer for dot extension. */ - def show(): Unit = show(defaultGraphVizConfig) - def show(emitMetadata: Boolean): Unit = show(defaultGraphVizConfig.copy(emitMetadata = emitMetadata)) - def show(config: GraphVizConfig): Unit = showGraphs(this)(config) } /** Untyped shortcut sinonim of Ref, which is used as untyped reference to graph nodes (definitions). @@ -514,16 +494,16 @@ abstract class Base { scalan: Scalan => case class EntityObjectOwner(obj: EntityObject) extends OwnerKind /** Returns OwnerKind for the given constructor, using its first parameter. */ - protected def getOwnerKind(constructor: Constr[_]): OwnerKind = { + protected def getOwnerKind(constructor: RConstructor[_]): OwnerKind = { val paramTypes = constructor.getParameterTypes val ownerParam = if (paramTypes.length == 0) NoOwner else { val firstParamClazz = paramTypes(0) - if (firstParamClazz.getSuperclass == classOf[EntityObject]) { + if (classOf[EntityObject].isAssignableFrom(firstParamClazz)) { val className = firstParamClazz.getSimpleName - val entityName = className.substring(0, className.length - 1) + val entityName = className.stripSuffix("$").stripSuffix("Cls") getEntityObject(entityName) match { case Nullable(obj) => EntityObjectOwner(obj) diff --git a/core/src/main/scala/scalan/DefRewriting.scala b/graph-ir/src/main/scala/scalan/DefRewriting.scala similarity index 100% rename from core/src/main/scala/scalan/DefRewriting.scala rename to graph-ir/src/main/scala/scalan/DefRewriting.scala diff --git a/core/src/main/scala/scalan/Entities.scala b/graph-ir/src/main/scala/scalan/Entities.scala similarity index 100% rename from core/src/main/scala/scalan/Entities.scala rename to graph-ir/src/main/scala/scalan/Entities.scala diff --git a/common/src/main/scala/scalan/Exceptions.scala b/graph-ir/src/main/scala/scalan/Exceptions.scala similarity index 100% rename from common/src/main/scala/scalan/Exceptions.scala rename to graph-ir/src/main/scala/scalan/Exceptions.scala diff --git a/graph-ir/src/main/scala/scalan/GraphIRReflection.scala b/graph-ir/src/main/scala/scalan/GraphIRReflection.scala new file mode 100644 index 0000000000..4be98bdf10 --- /dev/null +++ b/graph-ir/src/main/scala/scalan/GraphIRReflection.scala @@ -0,0 +1,566 @@ +package scalan + +import scalan.primitives.Thunks +import scalan.reflection.CommonReflection.registerClassEntry +import scalan.reflection.{mkConstructor, mkMethod, CommonReflection} +import special.CoreLibReflection +import special.collection.Colls +import special.sigma.SigmaDsl +import wrappers.scalan.WRTypes + +/** Registrations of reflection metadata for graph-ir module (see README.md). + * For each class of this module that needs reflection metadata, + * we register a class entry with the necessary information. + * Only information that is needed at runtime is registered. + */ +object GraphIRReflection { + /** Forces initialization of reflection data. */ + val reflection = (CommonReflection, CoreLibReflection) + + { val clazz = classOf[wrappers.scala.WOptions#WOption[_]] + val ctx = null.asInstanceOf[scalan.Library] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "filter", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.WOption[Any]].filter(args(0).asInstanceOf[ctx.Ref[Any => Boolean]]) + }, + mkMethod(clazz, "get", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.WOption[_]].get + }, + mkMethod(clazz, "isDefined", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.WOption[_]].isDefined + }, + mkMethod(clazz, "getOrElse", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.WOption[Any]].getOrElse(args(0).asInstanceOf[ctx.Ref[ctx.Thunk[Any]]]) + }, + mkMethod(clazz, "map", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.WOption[Any]].map(args(0).asInstanceOf[ctx.Ref[Any => Any]]) + } + ) + ) + } + + registerClassEntry(classOf[TypeDescs#FuncElem[_,_]], + constructors = Array( + mkConstructor(Array(classOf[Scalan], classOf[TypeDescs#Elem[_]], classOf[TypeDescs#Elem[_]])) { args => + val ctx = args(0).asInstanceOf[Scalan] + new ctx.FuncElem(args(1).asInstanceOf[ctx.Elem[_]], args(2).asInstanceOf[ctx.Elem[_]]) + } + ) + ) + + registerClassEntry(classOf[TypeDescs#PairElem[_,_]], + constructors = Array( + mkConstructor(Array(classOf[Scalan], classOf[TypeDescs#Elem[_]], classOf[TypeDescs#Elem[_]])) { args => + val ctx = args(0).asInstanceOf[Scalan] + new ctx.PairElem(args(1).asInstanceOf[ctx.Elem[_]], args(2).asInstanceOf[ctx.Elem[_]]) + } + ) + ) + + registerClassEntry(classOf[Thunks#ThunkElem[_]], + constructors = Array( + mkConstructor(Array(classOf[Scalan], classOf[TypeDescs#Elem[_]])) { args => + val ctx = args(0).asInstanceOf[Scalan] + new ctx.ThunkElem(args(1).asInstanceOf[ctx.Elem[_]]) + } + ) + ) + + { val clazz = classOf[special.sigma.SigmaDsl#SigmaProp] + val ctx = null.asInstanceOf[SigmaDsl] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "$bar$bar", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaProp].$bar$bar(args(0).asInstanceOf[ctx.Ref[ctx.SigmaProp]]) + }, + mkMethod(clazz, "isValid", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.SigmaProp].isValid + }, + mkMethod(clazz, "propBytes", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.SigmaProp].propBytes + }, + mkMethod(clazz, "$amp$amp", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaProp].$amp$amp(args(0).asInstanceOf[ctx.Ref[ctx.SigmaProp]]) + } + ) + ) + } + + { val clazz = classOf[SigmaDsl#BigInt] + val ctx = null.asInstanceOf[SigmaDsl] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "add", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.BigInt].add(args(0).asInstanceOf[ctx.Ref[ctx.BigInt]]) + }, + mkMethod(clazz, "max", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.BigInt].max(args(0).asInstanceOf[ctx.Ref[ctx.BigInt]]) + }, + mkMethod(clazz, "min", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.BigInt].min(args(0).asInstanceOf[ctx.Ref[ctx.BigInt]]) + }, + mkMethod(clazz, "subtract", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.BigInt].subtract(args(0).asInstanceOf[ctx.Ref[ctx.BigInt]]) + }, + mkMethod(clazz, "multiply", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.BigInt].multiply(args(0).asInstanceOf[ctx.Ref[ctx.BigInt]]) + }, + mkMethod(clazz, "mod", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.BigInt].mod(args(0).asInstanceOf[ctx.Ref[ctx.BigInt]]) + }, + mkMethod(clazz, "divide", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.BigInt].divide(args(0).asInstanceOf[ctx.Ref[ctx.BigInt]]) + } + ) + ) + } + + { val clazz = classOf[Colls#CollBuilder] + val ctx = null.asInstanceOf[Library] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "xor", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.CollBuilder].xor( + args(0).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]], + args(1).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + }, + mkMethod(clazz, "fromItems", Array[Class[_]](classOf[Seq[_]], classOf[TypeDescs#Elem[_]])) { (obj, args) => + obj.asInstanceOf[ctx.CollBuilder].fromItems[Any]( + args(0).asInstanceOf[Seq[ctx.Ref[Any]]]:_*)(args(1).asInstanceOf[ctx.Elem[Any]]) + }, + mkMethod(clazz, "replicate", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.CollBuilder].replicate(args(0).asInstanceOf[ctx.Ref[Int]], + args(1).asInstanceOf[ctx.Ref[Any]]) + } + ) + ) + } + + { + val clazz = classOf[Colls#Coll[_]] + val ctx = null.asInstanceOf[Library] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "append", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].append(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Any]]]) + }, + mkMethod(clazz, "forall", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].forall(args(0).asInstanceOf[ctx.Ref[Any => Boolean]]) + }, + mkMethod(clazz, "length", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Coll[_]].length + }, + mkMethod(clazz, "updateMany", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].updateMany( + args(0).asInstanceOf[ctx.Ref[ctx.Coll[Int]]], + args(1).asInstanceOf[ctx.Ref[ctx.Coll[Any]]]) + }, + mkMethod(clazz, "updated", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].updated( + args(0).asInstanceOf[ctx.Ref[Int]], args(1).asInstanceOf[ctx.Ref[Any]]) + }, + mkMethod(clazz, "patch", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].patch(args(0).asInstanceOf[ctx.Ref[Int]], + args(1).asInstanceOf[ctx.Ref[ctx.Coll[Any]]], + args(2).asInstanceOf[ctx.Ref[Int]]) + }, + mkMethod(clazz, "foldLeft", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].foldLeft(args(0).asInstanceOf[ctx.Ref[Any]], + args(1).asInstanceOf[ctx.Ref[((Any, Any)) => Any]]) + }, + mkMethod(clazz, "flatMap", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].flatMap(args(0).asInstanceOf[ctx.Ref[Any => ctx.Coll[Any]]]) + }, + mkMethod(clazz, "filter", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].filter(args(0).asInstanceOf[ctx.Ref[Any => Boolean]]) + }, + mkMethod(clazz, "slice", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].slice(args(0).asInstanceOf[ctx.Ref[Int]], + args(1).asInstanceOf[ctx.Ref[Int]]) + }, + mkMethod(clazz, "indices", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Coll[_]].indices + }, + mkMethod(clazz, "zip", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].zip(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Any]]]) + }, + mkMethod(clazz, "map", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].map(args(0).asInstanceOf[ctx.Ref[Any => Any]]) + }, + mkMethod(clazz, "getOrElse", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].getOrElse(args(0).asInstanceOf[ctx.Ref[Int]], args(1).asInstanceOf[ctx.Ref[Any]]) + }, + mkMethod(clazz, "indexOf", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].indexOf(args(0).asInstanceOf[ctx.Ref[Any]], args(1).asInstanceOf[ctx.Ref[Int]]) + }, + mkMethod(clazz, "apply", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[_]].apply(args(0).asInstanceOf[ctx.Ref[Int]]) + }, + mkMethod(clazz, "exists", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Coll[Any]].exists(args(0).asInstanceOf[ctx.Ref[Any => Boolean]]) + } + ) + ) + } + { + val clazz = classOf[SigmaDsl#AvlTree] + val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "updateOperations", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].updateOperations(args(0).asInstanceOf[ctx.Ref[Byte]]) + }, + mkMethod(clazz, "getMany", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].getMany(args(0).asInstanceOf[ctx.Ref[ctx.Coll[ctx.Coll[Byte]]]], + args(1).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + }, + mkMethod(clazz, "update", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].update(args(0).asInstanceOf[ctx.Ref[ctx.Coll[(ctx.Coll[Byte], ctx.Coll[Byte])]]], + args(1).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + }, + mkMethod(clazz, "keyLength", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].keyLength + }, + mkMethod(clazz, "enabledOperations", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].enabledOperations + }, + mkMethod(clazz, "updateDigest", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].updateDigest(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + }, + mkMethod(clazz, "digest", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].digest + }, + mkMethod(clazz, "insert", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].insert(args(0).asInstanceOf[ctx.Ref[ctx.Coll[(ctx.Coll[Byte], ctx.Coll[Byte])]]], + args(1).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + }, + mkMethod(clazz, "isRemoveAllowed", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].isRemoveAllowed + }, + mkMethod(clazz, "valueLengthOpt", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].valueLengthOpt + }, + mkMethod(clazz, "get", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].get(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]], + args(1).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + }, + mkMethod(clazz, "remove", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].remove(args(0).asInstanceOf[ctx.Ref[ctx.Coll[ctx.Coll[Byte]]]], args(1).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + }, + mkMethod(clazz, "contains", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].contains(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]], + args(1).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + }, + mkMethod(clazz, "isUpdateAllowed", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].isUpdateAllowed + }, + mkMethod(clazz, "isInsertAllowed", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.AvlTree].isInsertAllowed + } + ) + ) + } + + { val clazz = classOf[SigmaDsl#Box] + val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "value", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Box].value + }, + mkMethod(clazz, "id", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Box].id + }, + mkMethod(clazz, "creationInfo", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Box].creationInfo + }, + mkMethod(clazz, "bytes", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Box].bytes + }, + mkMethod(clazz, "getReg", Array[Class[_]](classOf[Base#Ref[_]], classOf[TypeDescs#Elem[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Box].getReg(args(0).asInstanceOf[ctx.Ref[Int]])(args(1).asInstanceOf[ctx.Elem[_]]) + }, + mkMethod(clazz, "tokens", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Box].tokens + }, + mkMethod(clazz, "bytesWithoutRef", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Box].bytesWithoutRef + }, + mkMethod(clazz, "propositionBytes", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Box].propositionBytes + } + ) + ) + } + + { + val clazz = classOf[SigmaDsl#Context] + val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "LastBlockUtxoRootHash", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Context].LastBlockUtxoRootHash + }, + mkMethod(clazz, "dataInputs", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Context].dataInputs + }, + mkMethod(clazz, "selfBoxIndex", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Context].selfBoxIndex + }, + mkMethod(clazz, "INPUTS", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Context].INPUTS + }, + mkMethod(clazz, "minerPubKey", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Context].minerPubKey + }, + mkMethod(clazz, "HEIGHT", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Context].HEIGHT + }, + mkMethod(clazz, "OUTPUTS", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Context].OUTPUTS + }, + mkMethod(clazz, "SELF", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Context].SELF + }, + mkMethod(clazz, "preHeader", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Context].preHeader + }, + mkMethod(clazz, "getVar", Array[Class[_]](classOf[Base#Ref[_]], classOf[TypeDescs#Elem[_]])) { (obj, args) => + obj.asInstanceOf[ctx.Context].getVar(args(0).asInstanceOf[ctx.Ref[Byte]])(args(1).asInstanceOf[ctx.Elem[_]]) + }, + mkMethod(clazz, "headers", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Context].headers + } + ) + ) + } + + { val clazz = classOf[SigmaDsl#GroupElement] + val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "exp", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.GroupElement].exp(args(0).asInstanceOf[ctx.Ref[ctx.BigInt]]) + }, + mkMethod(clazz, "multiply", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.GroupElement].multiply(args(0).asInstanceOf[ctx.Ref[ctx.GroupElement]]) + }, + mkMethod(clazz, "getEncoded", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.GroupElement].getEncoded + }, + mkMethod(clazz, "negate", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.GroupElement].negate + } + ) + ) + } + + { val clazz = classOf[SigmaDsl#Header] + val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "minerPk", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].minerPk + }, + mkMethod(clazz, "powNonce", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].powNonce + }, + mkMethod(clazz, "transactionsRoot", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].transactionsRoot + }, + mkMethod(clazz, "powOnetimePk", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].powOnetimePk + }, + mkMethod(clazz, "nBits", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].nBits + }, + mkMethod(clazz, "votes", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].votes + }, + mkMethod(clazz, "id", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].id + }, + mkMethod(clazz, "version", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].version + }, + mkMethod(clazz, "parentId", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].parentId + }, + mkMethod(clazz, "timestamp", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].timestamp + }, + mkMethod(clazz, "height", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].height + }, + mkMethod(clazz, "extensionRoot", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].extensionRoot + }, + mkMethod(clazz, "ADProofsRoot", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].ADProofsRoot + }, + mkMethod(clazz, "stateRoot", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].stateRoot + }, + mkMethod(clazz, "powDistance", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.Header].powDistance + } + ) + ) + } + + { val clazz = classOf[SigmaDsl#PreHeader] + val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "minerPk", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.PreHeader].minerPk + }, + mkMethod(clazz, "votes", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.PreHeader].votes + }, + mkMethod(clazz, "nBits", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.PreHeader].nBits + }, + mkMethod(clazz, "version", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.PreHeader].version + }, + mkMethod(clazz, "timestamp", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.PreHeader].timestamp + }, + mkMethod(clazz, "parentId", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.PreHeader].parentId + }, + mkMethod(clazz, "height", Array[Class[_]]()) { (obj, args) => + obj.asInstanceOf[ctx.PreHeader].height + } + ) + ) + } + + { val clazz = classOf[SigmaDsl#SigmaDslBuilder] + val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "byteArrayToLong", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].byteArrayToLong(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + }, + mkMethod(clazz, "anyOf", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].anyOf(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Boolean]]]) + }, + mkMethod(clazz, "allZK", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].allZK(args(0).asInstanceOf[ctx.Ref[ctx.Coll[ctx.SigmaProp]]]) + }, + mkMethod(clazz, "xorOf", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].xorOf(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Boolean]]]) + }, + mkMethod(clazz, "substConstants", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].substConstants(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]], + args(1).asInstanceOf[ctx.Ref[ctx.Coll[Int]]], args(2).asInstanceOf[ctx.Ref[ctx.Coll[Any]]]) + }, + mkMethod(clazz, "sigmaProp", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].sigmaProp(args(0).asInstanceOf[ctx.Ref[Boolean]]) + }, + mkMethod(clazz, "groupGenerator", Array[Class[_]]()) { (obj, _) => + obj.asInstanceOf[ctx.SigmaDslBuilder].groupGenerator + }, + mkMethod(clazz, "proveDlog", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].proveDlog(args(0).asInstanceOf[ctx.Ref[ctx.GroupElement]]) + }, + mkMethod(clazz, "blake2b256", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].blake2b256(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + }, + mkMethod(clazz, "longToByteArray", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].longToByteArray(args(0).asInstanceOf[ctx.Ref[Long]]) + }, + mkMethod(clazz, "xor", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].xor(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]], + args(1).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + }, + mkMethod(clazz, "atLeast", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].atLeast(args(0).asInstanceOf[ctx.Ref[Int]], + args(1).asInstanceOf[ctx.Ref[ctx.Coll[ctx.SigmaProp]]]) + }, + mkMethod(clazz, "byteArrayToBigInt", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].byteArrayToBigInt(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + }, + mkMethod(clazz, "allOf", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].allOf(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Boolean]]]) + }, + mkMethod(clazz, "proveDHTuple", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]], classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].proveDHTuple(args(0).asInstanceOf[ctx.Ref[ctx.GroupElement]], + args(1).asInstanceOf[ctx.Ref[ctx.GroupElement]], + args(2).asInstanceOf[ctx.Ref[ctx.GroupElement]], + args(3).asInstanceOf[ctx.Ref[ctx.GroupElement]]) + }, + mkMethod(clazz, "anyZK", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].anyZK(args(0).asInstanceOf[ctx.Ref[ctx.Coll[ctx.SigmaProp]]]) + }, + mkMethod(clazz, "sha256", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].sha256(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + }, + mkMethod(clazz, "decodePoint", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.SigmaDslBuilder].decodePoint(args(0).asInstanceOf[ctx.Ref[ctx.Coll[Byte]]]) + } + ) + ) + } + + { val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + val clazz = classOf[ctx.WOption.WOptionElem[_, _]] + registerClassEntry(clazz, + constructors = Array( + mkConstructor(Array(classOf[ctx.WOptionCls], classOf[TypeDescs#Elem[_]])) { args => + val entityObj = args(0).asInstanceOf[ctx.WOptionCls] + new entityObj.WOptionElem()(args(1).asInstanceOf[ctx.Elem[_]]) + } + ) + ) + } + + { val clazz = classOf[WRTypes#WRType[_]] + val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "name", Array[Class[_]]()) { (obj, _) => + obj.asInstanceOf[ctx.WRType[_]].name + } + ) + ) + } + + { val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + val clazz = classOf[ctx.WRType.WRTypeElem[_, _]] + registerClassEntry(clazz, + constructors = Array( + mkConstructor(Array(classOf[ctx.WRTypeCls], classOf[TypeDescs#Elem[_]])) { args => + val entityObj = args(0).asInstanceOf[ctx.WRTypeCls] + new entityObj.WRTypeElem()(args(1).asInstanceOf[ctx.Elem[_]]) + } + ) + ) + } + + { val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + val clazz = classOf[ctx.Coll.CollElem[_, _]] + registerClassEntry(clazz, + constructors = Array( + mkConstructor(Array(classOf[ctx.CollCls], classOf[TypeDescs#Elem[_]])) { args => + val entityObj = args(0).asInstanceOf[ctx.CollCls] + new entityObj.CollElem()(args(1).asInstanceOf[ctx.Elem[_]]) + } + ) + ) + } + + { val clazz = classOf[wrappers.special.WSpecialPredefs#WSpecialPredefCompanion] + val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + registerClassEntry(clazz, + methods = Map( + mkMethod(clazz, "some", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => + obj.asInstanceOf[ctx.WSpecialPredefCompanion].some(args(0).asInstanceOf[ctx.Ref[Any]]) + } + ) + ) + } +} diff --git a/library/src/main/scala/scalan/Library.scala b/graph-ir/src/main/scala/scalan/Library.scala similarity index 95% rename from library/src/main/scala/scalan/Library.scala rename to graph-ir/src/main/scala/scalan/Library.scala index c61338d4dd..ac8c5564a6 100644 --- a/library/src/main/scala/scalan/Library.scala +++ b/graph-ir/src/main/scala/scalan/Library.scala @@ -95,9 +95,6 @@ trait Library extends Scalan } } - // Rule: opt.fold(None, x => Some(x)) ==> opt - case WOptionM.fold(opt, Def(ThunkDef(SPCM.none(_), _)), Def(Lambda(_, _, x, SPCM.some(y)))) if x == y => opt - case WOptionM.getOrElse(opt, _) => opt.node match { // Rule: Some(x).getOrElse(_) ==> x case SPCM.some(x) => x @@ -108,7 +105,7 @@ trait Library extends Scalan case _ => super.rewriteDef(d) } - override def invokeUnlifted(e: Elem[_], mc: MethodCall, dataEnv: DataEnv): AnyRef = e match { + override def invokeUnlifted(e: Elem[_], mc: MethodCall, dataEnv: DataEnv): Any = e match { case _: CollElem[_,_] => mc match { case CollMethods.map(xs, f) => val newMC = mc.copy(args = mc.args :+ f.elem.eRange)(mc.resultType, mc.isAdapterCall) diff --git a/core/src/main/scala/scalan/MethodCalls.scala b/graph-ir/src/main/scala/scalan/MethodCalls.scala similarity index 79% rename from core/src/main/scala/scalan/MethodCalls.scala rename to graph-ir/src/main/scala/scalan/MethodCalls.scala index c981d10639..b1bf67ebe6 100644 --- a/core/src/main/scala/scalan/MethodCalls.scala +++ b/graph-ir/src/main/scala/scalan/MethodCalls.scala @@ -1,20 +1,18 @@ package scalan -import java.lang.reflect.{InvocationTargetException, Method} -import scala.annotation.tailrec +import scala.annotation.{tailrec, unused} import scala.reflect.ClassTag -import scalan.compilation.{GraphVizConfig, GraphVizExport} -import scalan.util.ScalaNameUtil import debox.{Buffer => DBuffer} import debox.cfor +import scalan.reflection.RMethod -trait MethodCalls extends Base with GraphVizExport { self: Scalan => +trait MethodCalls extends Base { self: Scalan => def delayInvoke = throw new DelayInvokeException /** Graph node to represent invocation of the method of some class. * @param receiver node ref representing instance on which the method is called - * @param method method which is called (descriptor from `java.lang.reflect`) + * @param method method which is called (descriptor from `scalan.reflection`) * @param args node refs representing arguments passed to the method * @param neverInvoke it true this method cannot be performed, even if the * receiver node allow this @@ -23,7 +21,7 @@ trait MethodCalls extends Base with GraphVizExport { self: Scalan => * This typically means, that receiver node doesn't implement * given `method`. */ - case class MethodCall private[MethodCalls](receiver: Sym, method: Method, args: Seq[AnyRef], neverInvoke: Boolean) + case class MethodCall private[MethodCalls](receiver: Sym, method: RMethod, args: Seq[AnyRef], neverInvoke: Boolean) (val resultType: Elem[Any], val isAdapterCall: Boolean = false) extends Def[Any] { override def mirror(t: Transformer): Ref[Any] = { @@ -45,7 +43,7 @@ trait MethodCalls extends Base with GraphVizExport { self: Scalan => /** Try invoke `method` on the node instance refered by `receiver`. * Each MC node contains enough information to perform invocation using - * `java.lang.reflect.Method.invoke` method. However, this is not possible + * `scalan.reflection.RMethod.invoke` method. However, this is not possible * if the node pointed to by `receiver` don't implement this method, * for example when receiver is Lambda variable pointing to Variable node * instance (in which case this MC was created by adapter) @@ -98,7 +96,7 @@ trait MethodCalls extends Base with GraphVizExport { self: Scalan => } /** Creates new MethodCall node and returns its node ref. */ - def mkMethodCall(receiver: Sym, method: Method, args: Seq[AnyRef], + def mkMethodCall(receiver: Sym, method: RMethod, args: Seq[AnyRef], neverInvoke: Boolean, isAdapterCall: Boolean, resultElem: Elem[_]): Sym = { reifyObject(MethodCall(receiver, method, args, neverInvoke)(asElem[Any](resultElem), isAdapterCall)) } @@ -110,36 +108,17 @@ trait MethodCalls extends Base with GraphVizExport { self: Scalan => @tailrec private def baseCause(e: Throwable): Throwable = e match { - case e: java.lang.reflect.UndeclaredThrowableException => baseCause(e.getCause) - case e: InvocationTargetException => baseCause(e.getCause) case e: ExceptionInInitializerError => baseCause(e.getCause) case e => e } - /** Used by Graphviz dot file generator to format text label of the graph node. */ - override protected def formatDef(d: Def[_])(implicit config: GraphVizConfig): String = d match { - case MethodCall(obj, method, args, _) => - val methodCallStr = - s"${ScalaNameUtil.cleanScalaName(method.getName)}(${args.mkString(", ")})" - if (obj.isCompanionType) { - s"$obj.$methodCallStr" - } else { - val className = ScalaNameUtil.cleanNestedClassName(method.getDeclaringClass.getName) - s"$obj.$className.$methodCallStr" - } - case NewObject(eA, args) => - val className = ScalaNameUtil.cleanNestedClassName(eA.sourceType.name) - s"new $className(${args.mkString(", ")})" - case _ => super.formatDef(d) - } - /** This method is called for each MethodCall node which is about to be added to the graph. * This means `mc` has been examined by all the rewrite rules, but has not need rewritten. * Now, if this method returns null, then mc will be added to the graph. * However, in this method, `mc` can be examined by a second set of RW rules * (kind of lower priority rules). These rules kind of context dependent, because at this * point we know that the first RW set didn't triggered any rewrite. */ - def rewriteNonInvokableMethodCall(mc: MethodCall): Ref[_] = null + def rewriteNonInvokableMethodCall(@unused mc: MethodCall): Ref[_] = null /** Create delegate instance suitable for method invocation. * It is used when T is a class or a trait and the node referred by x doesn't conform to T. @@ -157,14 +136,14 @@ trait MethodCalls extends Base with GraphVizExport { self: Scalan => } /** Generic helper to call the given method on the given receiver node. */ - private[scalan] def invokeMethod[A](receiver: Sym, m: Method, args: Array[AnyRef], - onInvokeSuccess: AnyRef => A, + private[scalan] def invokeMethod[A](receiver: Sym, m: RMethod, args: Array[AnyRef], + onInvokeSuccess: Any => A, onInvokeException: Throwable => A, onInvokeImpossible: => A): A = { val d = receiver.node if (canBeInvoked(d, m, args)) { try { - val res = m.invoke(d, args: _*) + val res = m.invoke(d, args:_*) onInvokeSuccess(res) } catch { case e: Exception => onInvokeException(baseCause(e)) @@ -176,10 +155,10 @@ trait MethodCalls extends Base with GraphVizExport { self: Scalan => /** Method invocation enabler. * @return true if the given method can be invoked on the given node. */ - def isInvokeEnabled(d: Def[_], m: Method) = true + def isInvokeEnabled(d: Def[_], m: RMethod) = true /** Method invocation checker. */ - protected def canBeInvoked(d: Def[_], m: Method, args: Array[AnyRef]) = { + protected def canBeInvoked(d: Def[_], m: RMethod, args: Array[AnyRef]) = { m.getDeclaringClass.isAssignableFrom(d.getClass) && isInvokeEnabled(d, m) } @@ -193,7 +172,7 @@ trait MethodCalls extends Base with GraphVizExport { self: Scalan => /** Invocation is not possible, e.g. when receiver doesn't implemented the method. */ case object InvokeImpossible extends InvokeResult - def throwInvocationException(whatFailed: String, cause: Throwable, receiver: Sym, m: Method, args: Seq[Any]) = { + def throwInvocationException(whatFailed: String, cause: Throwable, receiver: Sym, m: RMethod, args: Seq[Any]) = { val buf = DBuffer.empty[Sym] buf += receiver Def.extractSyms(args, buf) diff --git a/common/src/main/scala/scalan/ModuleInfo.scala b/graph-ir/src/main/scala/scalan/ModuleInfo.scala similarity index 74% rename from common/src/main/scala/scalan/ModuleInfo.scala rename to graph-ir/src/main/scala/scalan/ModuleInfo.scala index 2d8e10116a..86fce48ce6 100644 --- a/common/src/main/scala/scalan/ModuleInfo.scala +++ b/graph-ir/src/main/scala/scalan/ModuleInfo.scala @@ -4,10 +4,16 @@ import scalan.meta.SSymName /** Information about generated Special library module. * Instances are created in generated code. + * * @see *Impl.scala files */ -case class ModuleInfo(packageName: String, moduleName: String, extension: String = ".scalan") { +case class ModuleInfo( + packageName: String, + moduleName: String, + extension: String = ".scalan") { val name = SSymName(packageName, moduleName) + def getKey = name.mkFullName + def sourceFileName = packageName.replace('.', '/') + s"/$moduleName$extension" } diff --git a/core/src/main/scala/scalan/Modules.scala b/graph-ir/src/main/scala/scalan/Modules.scala similarity index 100% rename from core/src/main/scala/scalan/Modules.scala rename to graph-ir/src/main/scala/scalan/Modules.scala diff --git a/common/src/main/scala/scalan/MutableLazy.scala b/graph-ir/src/main/scala/scalan/MutableLazy.scala similarity index 100% rename from common/src/main/scala/scalan/MutableLazy.scala rename to graph-ir/src/main/scala/scalan/MutableLazy.scala diff --git a/core/src/main/scala/scalan/Scalan.scala b/graph-ir/src/main/scala/scalan/Scalan.scala similarity index 100% rename from core/src/main/scala/scalan/Scalan.scala rename to graph-ir/src/main/scala/scalan/Scalan.scala diff --git a/sigma-library/src/main/scala/scalan/SigmaLibrary.scala b/graph-ir/src/main/scala/scalan/SigmaLibrary.scala similarity index 71% rename from sigma-library/src/main/scala/scalan/SigmaLibrary.scala rename to graph-ir/src/main/scala/scalan/SigmaLibrary.scala index 7658fd5eb1..46c235758b 100644 --- a/sigma-library/src/main/scala/scalan/SigmaLibrary.scala +++ b/graph-ir/src/main/scala/scalan/SigmaLibrary.scala @@ -1,7 +1,8 @@ package scalan -import special.sigma._ +import special.sigma.SigmaDslModule +/** Main trait which represents sigma operations in graph IR cake. */ trait SigmaLibrary extends Library with special.sigma.wrappers.WrappersModule with SigmaDslModule @@ -10,6 +11,6 @@ trait SigmaLibrary extends Library implicit lazy val wRTypeAnyElement = wRTypeElement(AnyElement) - /** During compilation represent a global value Global, see also SGlobal type.*/ + /** During compilation represent a global value Global, see also SGlobal type. */ def sigmaDslBuilder: Ref[SigmaDslBuilder] } diff --git a/core/src/main/scala/scalan/TypeDescs.scala b/graph-ir/src/main/scala/scalan/TypeDescs.scala similarity index 86% rename from core/src/main/scala/scalan/TypeDescs.scala rename to graph-ir/src/main/scala/scalan/TypeDescs.scala index 97689c169d..fd028f15bb 100644 --- a/core/src/main/scala/scalan/TypeDescs.scala +++ b/graph-ir/src/main/scala/scalan/TypeDescs.scala @@ -1,14 +1,15 @@ package scalan -import java.lang.reflect.{InvocationTargetException, Method} import scala.language.{implicitConversions, higherKinds} import scala.annotation.implicitNotFound import scala.collection.immutable.ListMap import scalan.util._ import scalan.RType._ -import scalan.util.ReflectionUtil.ClassOps +import ReflectionUtil._ // don't remove + import scala.collection.mutable import debox.cfor +import scalan.reflection.{RClass, RMethod, RConstructor} abstract class TypeDescs extends Base { self: Scalan => @@ -47,37 +48,23 @@ abstract class TypeDescs extends Base { self: Scalan => } } + /** Abstract class for a method descriptors to assist invocation of MethodCall nodes. */ sealed abstract class MethodDesc { - def method: Method + /** The described method */ + def method: RMethod } - case class RMethodDesc(method: Method) extends MethodDesc - case class WMethodDesc(wrapSpec: WrapSpec, method: Method) extends MethodDesc - -// TODO optimize: benchmark this version agains the version below -// def getSourceValues(dataEnv: DataEnv, forWrapper: Boolean, stagedValue: AnyRef, out: DBuffer[AnyRef]): Unit = { -// import OverloadHack._ -// stagedValue match { -// case s: Sym => -// out += dataEnv(s) -// case vec: Seq[AnyRef]@unchecked => -// val sub = DBuffer.ofSize[AnyRef](vec.length) -// getSourceValues(dataEnv, forWrapper, vec, sub) -// out += (sub.toArray: Seq[AnyRef]) -// case e: Elem[_] => -// val arg = -// if (forWrapper) e.sourceType.classTag // WrapSpec classes use ClassTag implicit arguments -// else e.sourceType -// out += arg -// case _: Overloaded => // filter out special arguments -// } -// } -// def getSourceValues(dataEnv: DataEnv, forWrapper: Boolean, stagedValues: Seq[AnyRef], out: DBuffer[AnyRef]): Unit = { -// val limit = stagedValues.length -// cfor(0)(_ < limit, _ + 1) { i => -// val v = stagedValues.apply(i) -// getSourceValues(dataEnv, forWrapper, v, out) -// } -// } + + /** Decriptor for a method of a class. + * @param method The RMethod object representing the method. + */ + case class RMethodDesc(method: RMethod) extends MethodDesc + + /** Descriptor for a method of a wrapper class. + * + * @param wrapSpec The wrapping specification of the method. + * @param method The RMethod object representing the method. + */ + case class WMethodDesc(wrapSpec: WrapSpec, method: RMethod) extends MethodDesc // TODO optimize performance hot spot (45% of invokeUnlifted time), reduce allocation of Some final def getSourceValues(dataEnv: DataEnv, forWrapper: Boolean, stagedValues: AnyRef*): Seq[AnyRef] = { @@ -149,8 +136,8 @@ abstract class TypeDescs extends Base { self: Scalan => !!!(s"Cannot get Liftable instance for $this") final lazy val sourceType: RType[_] = liftable.sourceType - protected def collectMethods: Map[Method, MethodDesc] = Map() // TODO optimize: all implementations - protected lazy val methods: Map[Method, MethodDesc] = collectMethods + protected def collectMethods: Map[RMethod, MethodDesc] = Map() // TODO optimize: all implementations + protected lazy val methods: Map[RMethod, MethodDesc] = collectMethods // TODO optimize: benchamrk against the version below it // def invokeUnlifted(mc: MethodCall, dataEnv: DataEnv): AnyRef = { @@ -163,7 +150,6 @@ abstract class TypeDescs extends Base { self: Scalan => // val res = // try method.invoke(wrapSpec, srcArgs.toArray:_*) // catch { - // case e: InvocationTargetException => !!!(msg, e.getTargetException) // case t: Throwable => !!!(msg, t) // } // res @@ -176,7 +162,6 @@ abstract class TypeDescs extends Base { self: Scalan => // val res = // try method.invoke(srcObj, srcArgs.toArray:_*) // catch { - // case e: InvocationTargetException => !!!(msg, e.getTargetException) // case t: Throwable => !!!(msg, t) // } // res @@ -194,7 +179,7 @@ abstract class TypeDescs extends Base { self: Scalan => * @param dataEnv environment where each symbol of 'mc' has associated data value * @return data value returned from invoked method */ - def invokeUnlifted(mc: MethodCall, dataEnv: DataEnv): AnyRef = { + def invokeUnlifted(mc: MethodCall, dataEnv: DataEnv): Any = { val res = methods.get(mc.method) match { case Some(WMethodDesc(wrapSpec, method)) => val srcArgs = getSourceValues(dataEnv, true, mc.receiver +: mc.args:_*) @@ -202,7 +187,6 @@ abstract class TypeDescs extends Base { self: Scalan => val res = try method.invoke(wrapSpec, srcArgs:_*) catch { - case e: InvocationTargetException => !!!(msg, e.getTargetException) case t: Throwable => !!!(msg, t) } res @@ -213,7 +197,6 @@ abstract class TypeDescs extends Base { self: Scalan => val res = try method.invoke(srcObj, srcArgs:_*) catch { - case e: InvocationTargetException => !!!(msg, e.getTargetException) case t: Throwable => !!!(msg, t) } res @@ -243,7 +226,7 @@ abstract class TypeDescs extends Base { self: Scalan => * @return a sequence of pairs relating for each staged method the corresponding method from * source classes. */ - def declaredMethods(cls: Class[_], srcCls: Class[_], methodNames: Set[String]): Seq[(Method, MethodDesc)] = { + def declaredMethods(cls: RClass[_], srcCls: RClass[_], methodNames: Set[String]): Seq[(RMethod, MethodDesc)] = { val rmethods = cls.getDeclaredMethods.filter(m => methodNames.contains(m.getName)) val smethods = srcCls.getDeclaredMethods.filter(m => methodNames.contains(m.getName)) val mapping = CollectionUtil.joinSeqs(rmethods, smethods)(_.getName, _.getName) @@ -260,8 +243,8 @@ abstract class TypeDescs extends Base { self: Scalan => * @return a sequence of pairs relating for each wrapper method the corresponding method from * source classes. */ - def declaredWrapperMethods(wrapSpec: WrapSpec, wcls: Class[_], methodNames: Set[String]): Seq[(Method, MethodDesc)] = { - val specCls = wrapSpec.getClass + def declaredWrapperMethods(wrapSpec: WrapSpec, wcls: RClass[_], methodNames: Set[String]): Seq[(RMethod, MethodDesc)] = { + val specCls = RClass(wrapSpec.getClass) val wMethods = wcls.getDeclaredMethods.filter(m => methodNames.contains(m.getName)) val specMethods = specCls.getDeclaredMethods.filter(m => methodNames.contains(m.getName)) val mapping = CollectionUtil.joinSeqs(wMethods, specMethods)(_.getName, _.getName) @@ -279,12 +262,12 @@ abstract class TypeDescs extends Base { self: Scalan => * @param dataEnv environment where each symbol of 'mc' has associated data value * @return data value returned from invoked method */ - def invokeUnlifted(e: Elem[_], mc: MethodCall, dataEnv: DataEnv): AnyRef = + def invokeUnlifted(e: Elem[_], mc: MethodCall, dataEnv: DataEnv): Any = e.invokeUnlifted(mc, dataEnv) /** Get first (and the only) constructor of the `clazz`. */ - private[scalan] final def getConstructor(clazz: Class[_]) = { - val constructors = clazz.getDeclaredConstructors() + private[scalan] final def getConstructor(clazz: RClass[_]): RConstructor[_] = { + val constructors = clazz.getConstructors() if (constructors.length != 1) !!!(s"Element class $clazz has ${constructors.length} constructors, 1 expected") else @@ -297,23 +280,23 @@ abstract class TypeDescs extends Base { self: Scalan => * @param args arguments of Elem class constructor * @param clazz Elem class */ - final def cachedElemByClass[E <: Elem[_]](args: AnyRef*)(implicit clazz: Class[E]) = { - cachedElem0(clazz, Nullable.None, args).asInstanceOf[E] + final def cachedElemByClass[E <: Elem[_]](args: AnyRef*)(implicit clazz: RClass[E]) = { + cachedElem0(clazz, Nullable.None.asInstanceOf[Nullable[RConstructor[_]]], args).asInstanceOf[E] } /** Elements cache information for each Elem class. */ class ElemCacheEntry( /** Constructor of the class to create new instances. */ - val constructor: java.lang.reflect.Constructor[_], + val constructor: RConstructor[_], /** Whether owner argument of constructor exists and of which kind. */ val ownerType: OwnerKind, /** Created instances of elements, one for each unique collection of args. */ val elements: AVHashMap[Seq[AnyRef], AnyRef] ) - protected val elemCache = AVHashMap[Class[_], ElemCacheEntry](1000) + protected val elemCache = AVHashMap[RClass[_], ElemCacheEntry](1000) - private[scalan] final def cachedElem0(clazz: Class[_], optConstructor: Nullable[java.lang.reflect.Constructor[_]], args: Seq[AnyRef]) = { + private[scalan] final def cachedElem0(clazz: RClass[_], optConstructor: Nullable[RConstructor[_]], args: Seq[AnyRef]): Elem[_] = { val entry = elemCache.get(clazz) match { case Nullable(entry) => entry case _ => @@ -402,12 +385,17 @@ abstract class TypeDescs extends Base { self: Scalan => implicit val StringElement: Elem[String] = new BaseElemLiftable("", StringType) implicit val CharElement: Elem[Char] = new BaseElemLiftable('\u0000', CharType) + /** Implicitly defines element type for pairs. */ implicit final def pairElement[A, B](implicit ea: Elem[A], eb: Elem[B]): Elem[(A, B)] = - cachedElemByClass[PairElem[A, B]](ea, eb)(classOf[PairElem[A, B]]) + cachedElemByClass[PairElem[A, B]](ea, eb)(RClass(classOf[PairElem[A, B]])) + + /** Implicitly defines element type for sum types. */ implicit final def sumElement[A, B](implicit ea: Elem[A], eb: Elem[B]): Elem[A | B] = - cachedElemByClass[SumElem[A, B]](ea, eb)(classOf[SumElem[A, B]]) + cachedElemByClass[SumElem[A, B]](ea, eb)(RClass(classOf[SumElem[A, B]])) + + /** Implicitly defines element type for functions. */ implicit final def funcElement[A, B](implicit ea: Elem[A], eb: Elem[B]): Elem[A => B] = - cachedElemByClass[FuncElem[A, B]](ea, eb)(classOf[FuncElem[A, B]]) + cachedElemByClass[FuncElem[A, B]](ea, eb)(RClass(classOf[FuncElem[A, B]])) implicit final def PairElemExtensions[A, B](eAB: Elem[(A, B)]): PairElem[A, B] = eAB.asInstanceOf[PairElem[A, B]] implicit final def SumElemExtensions[A, B](eAB: Elem[A | B]): SumElem[A, B] = eAB.asInstanceOf[SumElem[A, B]] diff --git a/common/src/main/scala/scalan/meta/SSymName.scala b/graph-ir/src/main/scala/scalan/meta/SSymName.scala similarity index 100% rename from common/src/main/scala/scalan/meta/SSymName.scala rename to graph-ir/src/main/scala/scalan/meta/SSymName.scala diff --git a/core/src/main/scala/scalan/primitives/Equal.scala b/graph-ir/src/main/scala/scalan/primitives/Equal.scala similarity index 100% rename from core/src/main/scala/scalan/primitives/Equal.scala rename to graph-ir/src/main/scala/scalan/primitives/Equal.scala diff --git a/core/src/main/scala/scalan/primitives/Functions.scala b/graph-ir/src/main/scala/scalan/primitives/Functions.scala similarity index 100% rename from core/src/main/scala/scalan/primitives/Functions.scala rename to graph-ir/src/main/scala/scalan/primitives/Functions.scala diff --git a/core/src/main/scala/scalan/primitives/IfThenElse.scala b/graph-ir/src/main/scala/scalan/primitives/IfThenElse.scala similarity index 100% rename from core/src/main/scala/scalan/primitives/IfThenElse.scala rename to graph-ir/src/main/scala/scalan/primitives/IfThenElse.scala diff --git a/core/src/main/scala/scalan/primitives/LogicalOps.scala b/graph-ir/src/main/scala/scalan/primitives/LogicalOps.scala similarity index 100% rename from core/src/main/scala/scalan/primitives/LogicalOps.scala rename to graph-ir/src/main/scala/scalan/primitives/LogicalOps.scala diff --git a/core/src/main/scala/scalan/primitives/NumericOps.scala b/graph-ir/src/main/scala/scalan/primitives/NumericOps.scala similarity index 100% rename from core/src/main/scala/scalan/primitives/NumericOps.scala rename to graph-ir/src/main/scala/scalan/primitives/NumericOps.scala diff --git a/core/src/main/scala/scalan/primitives/OrderingOps.scala b/graph-ir/src/main/scala/scalan/primitives/OrderingOps.scala similarity index 100% rename from core/src/main/scala/scalan/primitives/OrderingOps.scala rename to graph-ir/src/main/scala/scalan/primitives/OrderingOps.scala diff --git a/core/src/main/scala/scalan/primitives/Thunks.scala b/graph-ir/src/main/scala/scalan/primitives/Thunks.scala similarity index 94% rename from core/src/main/scala/scalan/primitives/Thunks.scala rename to graph-ir/src/main/scala/scalan/primitives/Thunks.scala index 6f1dc80918..892518d7ca 100644 --- a/core/src/main/scala/scalan/primitives/Thunks.scala +++ b/graph-ir/src/main/scala/scalan/primitives/Thunks.scala @@ -1,10 +1,10 @@ package scalan.primitives import scala.language.{existentials, implicitConversions} -import scalan.compilation.{GraphVizConfig, GraphVizExport} import scalan._ -import debox.{Set => DSet, Buffer => DBuffer} +import debox.{Buffer => DBuffer, Set => DSet} import debox.cfor +import scalan.reflection.RClass import scala.reflect.runtime.universe._ import scalan.util.{Covariant, GraphUtil} @@ -16,7 +16,7 @@ import scala.collection.Seq * Thunks are used to represent lazy operations in the graph IR. * @see ApplyBinOpLazy, IfThenElseLazy */ -trait Thunks extends Functions with GraphVizExport { self: Scalan => +trait Thunks extends Functions { self: Scalan => type Th[+T] = Ref[Thunk[T]] @@ -89,10 +89,6 @@ trait Thunks extends Functions with GraphVizExport { self: Scalan => RType[SThunk[ST]] } override def lift(x: SThunk[ST]): Ref[Thunk[T]] = ThunkConst(x, lT) - override def unlift(w: Ref[Thunk[T]]): SThunk[ST] = w.node match { - case ThunkConst(x: SThunk[_], l) if l == lT => x.asInstanceOf[SThunk[ST]] - case _ => unliftError(w) - } } implicit def liftableThunk[ST,T](implicit lT: Liftable[ST,T]): Liftable[SThunk[ST], Thunk[T]] = @@ -106,8 +102,9 @@ trait Thunks extends Functions with GraphVizExport { self: Scalan => override lazy val typeArgs = TypeArgs("A" -> (eItem -> Covariant)) } + /** Implicitly defines element type for thunks (aka lazy values). */ implicit def thunkElement[T](implicit eItem: Elem[T]): Elem[Thunk[T]] = - cachedElemByClass(eItem)(classOf[ThunkElem[T]]) + cachedElemByClass(eItem)(RClass(classOf[ThunkElem[T]])) /** Implicit conversion (downcast) to access `ThunkElem.eItem` field. */ implicit def extendThunkElement[T](elem: Elem[Thunk[T]]): ThunkElem[T] = elem.asInstanceOf[ThunkElem[T]] @@ -373,15 +370,5 @@ trait Thunks extends Functions with GraphVizExport { self: Scalan => def unapply(s: Sym): Option[Const[_]] = unapply(s.node) } - - override protected def formatDef(d: Def[_])(implicit config: GraphVizConfig): String = d match { - case ThunkDef(r, sch) => s"Thunk($r, [${sch.mkString(",")}])" - case _ => super.formatDef(d) - } - - override protected def nodeColor(td: TypeDesc, d: Def[_])(implicit config: GraphVizConfig) = td match { - case _: ThunkElem[_] => "red" - case _ => super.nodeColor(td, d) - } } diff --git a/core/src/main/scala/scalan/primitives/Tuples.scala b/graph-ir/src/main/scala/scalan/primitives/Tuples.scala similarity index 100% rename from core/src/main/scala/scalan/primitives/Tuples.scala rename to graph-ir/src/main/scala/scalan/primitives/Tuples.scala diff --git a/core/src/main/scala/scalan/primitives/UnBinOps.scala b/graph-ir/src/main/scala/scalan/primitives/UnBinOps.scala similarity index 100% rename from core/src/main/scala/scalan/primitives/UnBinOps.scala rename to graph-ir/src/main/scala/scalan/primitives/UnBinOps.scala diff --git a/core/src/main/scala/scalan/primitives/UniversalOps.scala b/graph-ir/src/main/scala/scalan/primitives/UniversalOps.scala similarity index 100% rename from core/src/main/scala/scalan/primitives/UniversalOps.scala rename to graph-ir/src/main/scala/scalan/primitives/UniversalOps.scala diff --git a/core/src/main/scala/scalan/staged/AstGraphs.scala b/graph-ir/src/main/scala/scalan/staged/AstGraphs.scala similarity index 96% rename from core/src/main/scala/scalan/staged/AstGraphs.scala rename to graph-ir/src/main/scala/scalan/staged/AstGraphs.scala index 7274e0350b..bec0c36eed 100644 --- a/core/src/main/scala/scalan/staged/AstGraphs.scala +++ b/graph-ir/src/main/scala/scalan/staged/AstGraphs.scala @@ -2,7 +2,6 @@ package scalan.staged import scala.collection._ import scalan.{Base, Scalan, emptyDBufferOfInt} -import scalan.compilation.GraphVizConfig import debox.cfor import debox.{Set => DSet, Buffer => DBuffer, Map => DMap} @@ -211,11 +210,6 @@ trait AstGraphs extends Transforming { self: Scalan => } def hasManyUsages(s: Sym): Boolean = usagesOf(s.node.nodeId).length > 1 - - def show(): Unit = show(defaultGraphVizConfig) - def show(emitMetadata: Boolean): Unit = show(defaultGraphVizConfig.copy(emitMetadata = emitMetadata)) - def show(config: GraphVizConfig): Unit = showGraphs(this)(config) - } // AstGraph diff --git a/core/src/main/scala/scalan/staged/ProgramGraphs.scala b/graph-ir/src/main/scala/scalan/staged/ProgramGraphs.scala similarity index 100% rename from core/src/main/scala/scalan/staged/ProgramGraphs.scala rename to graph-ir/src/main/scala/scalan/staged/ProgramGraphs.scala diff --git a/core/src/main/scala/scalan/staged/Transforming.scala b/graph-ir/src/main/scala/scalan/staged/Transforming.scala similarity index 98% rename from core/src/main/scala/scalan/staged/Transforming.scala rename to graph-ir/src/main/scala/scalan/staged/Transforming.scala index 0a16fbc224..9dd714d049 100644 --- a/core/src/main/scala/scalan/staged/Transforming.scala +++ b/graph-ir/src/main/scala/scalan/staged/Transforming.scala @@ -1,12 +1,11 @@ package scalan.staged -import java.lang.reflect.Method import java.util - import scala.language.existentials -import scalan.{Nullable, DelayInvokeException, Lazy, Scalan, AVHashMap} +import scalan.{AVHashMap, DelayInvokeException, Lazy, Nullable, Scalan} import debox.{Buffer => DBuffer} import debox.cfor +import scalan.reflection.RMethod trait Transforming { self: Scalan => @@ -27,7 +26,7 @@ trait Transforming { self: Scalan => * @param m method to invoke * @return Some(decision) if some this Pass defines some logic, None - then core behavior is used */ - def isInvokeEnabled(d: Def[_], m: Method): Option[Boolean] = None + def isInvokeEnabled(d: Def[_], m: RMethod): Option[Boolean] = None } object Pass { val defaultPassName = "default" diff --git a/common/src/main/scala/scalan/util/Variance.scala b/graph-ir/src/main/scala/scalan/util/Variance.scala similarity index 100% rename from common/src/main/scala/scalan/util/Variance.scala rename to graph-ir/src/main/scala/scalan/util/Variance.scala diff --git a/library/src/main/scala/special/collection/CollsUnit.scala b/graph-ir/src/main/scala/special/collection/CollsUnit.scala similarity index 51% rename from library/src/main/scala/special/collection/CollsUnit.scala rename to graph-ir/src/main/scala/special/collection/CollsUnit.scala index f43e31e689..747ab25e68 100644 --- a/library/src/main/scala/special/collection/CollsUnit.scala +++ b/graph-ir/src/main/scala/special/collection/CollsUnit.scala @@ -4,17 +4,11 @@ package special.collection { trait Colls extends Base { self: Library => import Coll._; import CollBuilder._; - import PairColl._; import WOption._; trait Coll[A] extends Def[Coll[A]] { implicit def eA: Elem[A]; - def builder: Ref[CollBuilder]; def length: Ref[Int]; - def size: Ref[Int] = this.length; - def isEmpty: Ref[Boolean]; - def nonEmpty: Ref[Boolean]; def apply(i: Ref[Int]): Ref[A]; - def isDefinedAt(idx: Ref[Int]): Ref[Boolean]; def getOrElse(index: Ref[Int], default: Ref[A]): Ref[A]; def map[B](f: Ref[scala.Function1[A, B]]): Ref[Coll[B]]; def zip[B](ys: Ref[Coll[B]]): Ref[Coll[scala.Tuple2[A, B]]]; @@ -24,40 +18,19 @@ package special.collection { def foldLeft[B](zero: Ref[B], op: Ref[scala.Function1[scala.Tuple2[B, A], B]]): Ref[B]; def indices: Ref[Coll[Int]]; def flatMap[B](f: Ref[scala.Function1[A, Coll[B]]]): Ref[Coll[B]]; - def segmentLength(p: Ref[scala.Function1[A, Boolean]], from: Ref[Int]): Ref[Int]; - def find(p: Ref[scala.Function1[A, Boolean]]): Ref[WOption[A]] = delayInvoke; - def indexWhere(p: Ref[scala.Function1[A, Boolean]], from: Ref[Int]): Ref[Int]; - def indexOf(elem: Ref[A], from: Ref[Int]): Ref[Int] = delayInvoke; - def lastIndexWhere(p: Ref[scala.Function1[A, Boolean]], end: Ref[Int]): Ref[Int]; - def take(n: Ref[Int]): Ref[Coll[A]]; + def indexOf(elem: Ref[A], from: Ref[Int]): Ref[Int]; def patch(from: Ref[Int], patch: Ref[Coll[A]], replaced: Ref[Int]): Ref[Coll[A]]; def updated(index: Ref[Int], elem: Ref[A]): Ref[Coll[A]]; def updateMany(indexes: Ref[Coll[Int]], values: Ref[Coll[A]]): Ref[Coll[A]]; - def unionSet(that: Ref[Coll[A]]): Ref[Coll[A]]; - def diff(that: Ref[Coll[A]]): Ref[Coll[A]] = delayInvoke; - def intersect(that: Ref[Coll[A]]): Ref[Coll[A]] = delayInvoke; def slice(from: Ref[Int], until: Ref[Int]): Ref[Coll[A]]; def append(other: Ref[Coll[A]]): Ref[Coll[A]]; - def reverse: Ref[Coll[A]] - }; - trait PairColl[L, R] extends Coll[scala.Tuple2[L, R]] { - implicit def eL: Elem[L]; - implicit def eR: Elem[R]; - def ls: Ref[Coll[L]]; - def rs: Ref[Coll[R]]; - def mapFirst[T1](f: Ref[scala.Function1[L, T1]]): Ref[Coll[scala.Tuple2[T1, R]]]; - def mapSecond[T1](f: Ref[scala.Function1[R, T1]]): Ref[Coll[scala.Tuple2[L, T1]]] }; trait CollBuilder extends Def[CollBuilder] { - def pairColl[A, B](as: Ref[Coll[A]], bs: Ref[Coll[B]]): Ref[PairColl[A, B]]; def fromItems[T](items: Ref[T]*)(implicit cT: Elem[T]): Ref[Coll[T]]; - def unzip[A, B](xs: Ref[Coll[scala.Tuple2[A, B]]]): Ref[scala.Tuple2[Coll[A], Coll[B]]]; def xor(left: Ref[Coll[Byte]], right: Ref[Coll[Byte]]): Ref[Coll[Byte]]; def replicate[T](n: Ref[Int], v: Ref[T]): Ref[Coll[T]]; - def emptyColl[T](implicit tT: Elem[T]): Ref[Coll[T]]; }; trait CollCompanion; - trait PairCollCompanion; trait CollBuilderCompanion } } \ No newline at end of file diff --git a/graph-ir/src/main/scala/special/collection/impl/CollsImpl.scala b/graph-ir/src/main/scala/special/collection/impl/CollsImpl.scala new file mode 100644 index 0000000000..63203f2f90 --- /dev/null +++ b/graph-ir/src/main/scala/special/collection/impl/CollsImpl.scala @@ -0,0 +1,648 @@ +package special.collection + +import scala.language.{existentials,implicitConversions} +import scalan._ +import scala.reflect.runtime.universe._ +import scala.reflect._ +import scala.collection.compat.immutable.ArraySeq + +package impl { + import scalan.reflection.CommonReflection.registerClassEntry + import scalan.reflection.{SRConstructor, RClass, RMethod, SRMethod} + + // Abs ----------------------------------- +trait CollsDefs extends scalan.Scalan with Colls { + self: Library => +import Coll._ +import CollBuilder._ +import WOption._ + +class CollCls extends EntityObject("Coll") { + // entityConst: single const for each entity + import Liftables._ + import scala.reflect.{ClassTag, classTag} + type SColl[A] = special.collection.Coll[A] + case class CollConst[SA, A]( + constValue: SColl[SA], + lA: Liftable[SA, A] + ) extends LiftedConst[SColl[SA], Coll[A]] with Coll[A] + with Def[Coll[A]] with CollConstMethods[A] { + implicit final def eA: Elem[A] = lA.eW + + val liftable: Liftable[SColl[SA], Coll[A]] = liftableColl(lA) + val resultType: Elem[Coll[A]] = liftable.eW + } + + trait CollConstMethods[A] extends Coll[A] { thisConst: Def[_] => + implicit def eA: Elem[A] + private val CollClass = RClass(classOf[Coll[A]]) + + override def length: Ref[Int] = { + asRep[Int](mkMethodCall(self, + CollClass.getMethod("length"), + ArraySeq.empty, + true, false, element[Int])) + } + + override def apply(i: Ref[Int]): Ref[A] = { + asRep[A](mkMethodCall(self, + CollClass.getMethod("apply", classOf[Sym]), + Array[AnyRef](i), + true, false, element[A])) + } + + override def getOrElse(index: Ref[Int], default: Ref[A]): Ref[A] = { + asRep[A](mkMethodCall(self, + CollClass.getMethod("getOrElse", classOf[Sym], classOf[Sym]), + Array[AnyRef](index, default), + true, false, element[A])) + } + + override def map[B](f: Ref[A => B]): Ref[Coll[B]] = { + implicit val eB = f.elem.eRange + asRep[Coll[B]](mkMethodCall(self, + CollClass.getMethod("map", classOf[Sym]), + Array[AnyRef](f), + true, false, element[Coll[B]])) + } + + override def zip[B](ys: Ref[Coll[B]]): Ref[Coll[(A, B)]] = { + implicit val eB = ys.eA + asRep[Coll[(A, B)]](mkMethodCall(self, + CollClass.getMethod("zip", classOf[Sym]), + Array[AnyRef](ys), + true, false, element[Coll[(A, B)]])) + } + + override def exists(p: Ref[A => Boolean]): Ref[Boolean] = { + asRep[Boolean](mkMethodCall(self, + CollClass.getMethod("exists", classOf[Sym]), + Array[AnyRef](p), + true, false, element[Boolean])) + } + + override def forall(p: Ref[A => Boolean]): Ref[Boolean] = { + asRep[Boolean](mkMethodCall(self, + CollClass.getMethod("forall", classOf[Sym]), + Array[AnyRef](p), + true, false, element[Boolean])) + } + + override def filter(p: Ref[A => Boolean]): Ref[Coll[A]] = { + asRep[Coll[A]](mkMethodCall(self, + CollClass.getMethod("filter", classOf[Sym]), + Array[AnyRef](p), + true, false, element[Coll[A]])) + } + + override def foldLeft[B](zero: Ref[B], op: Ref[((B, A)) => B]): Ref[B] = { + implicit val eB = zero.elem + asRep[B](mkMethodCall(self, + CollClass.getMethod("foldLeft", classOf[Sym], classOf[Sym]), + Array[AnyRef](zero, op), + true, false, element[B])) + } + + override def indices: Ref[Coll[Int]] = { + asRep[Coll[Int]](mkMethodCall(self, + CollClass.getMethod("indices"), + ArraySeq.empty, + true, false, element[Coll[Int]])) + } + + override def flatMap[B](f: Ref[A => Coll[B]]): Ref[Coll[B]] = { + implicit val eB = f.elem.eRange.typeArgs("A")._1.asInstanceOf[Elem[B]] + asRep[Coll[B]](mkMethodCall(self, + CollClass.getMethod("flatMap", classOf[Sym]), + Array[AnyRef](f), + true, false, element[Coll[B]])) + } + + override def indexOf(elem: Ref[A], from: Ref[Int]): Ref[Int] = { + asRep[Int](mkMethodCall(self, + CollClass.getMethod("indexOf", classOf[Sym], classOf[Sym]), + Array[AnyRef](elem, from), + true, false, element[Int])) + } + + override def patch(from: Ref[Int], patch: Ref[Coll[A]], replaced: Ref[Int]): Ref[Coll[A]] = { + asRep[Coll[A]](mkMethodCall(self, + CollClass.getMethod("patch", classOf[Sym], classOf[Sym], classOf[Sym]), + Array[AnyRef](from, patch, replaced), + true, false, element[Coll[A]])) + } + + override def updated(index: Ref[Int], elem: Ref[A]): Ref[Coll[A]] = { + asRep[Coll[A]](mkMethodCall(self, + CollClass.getMethod("updated", classOf[Sym], classOf[Sym]), + Array[AnyRef](index, elem), + true, false, element[Coll[A]])) + } + + override def updateMany(indexes: Ref[Coll[Int]], values: Ref[Coll[A]]): Ref[Coll[A]] = { + asRep[Coll[A]](mkMethodCall(self, + CollClass.getMethod("updateMany", classOf[Sym], classOf[Sym]), + Array[AnyRef](indexes, values), + true, false, element[Coll[A]])) + } + + override def slice(from: Ref[Int], until: Ref[Int]): Ref[Coll[A]] = { + asRep[Coll[A]](mkMethodCall(self, + CollClass.getMethod("slice", classOf[Sym], classOf[Sym]), + Array[AnyRef](from, until), + true, false, element[Coll[A]])) + } + + override def append(other: Ref[Coll[A]]): Ref[Coll[A]] = { + asRep[Coll[A]](mkMethodCall(self, + CollClass.getMethod("append", classOf[Sym]), + Array[AnyRef](other), + true, false, element[Coll[A]])) + } + } + + case class LiftableColl[SA, A](lA: Liftable[SA, A]) + extends Liftable[SColl[SA], Coll[A]] { + lazy val eW: Elem[Coll[A]] = collElement(lA.eW) + lazy val sourceType: RType[SColl[SA]] = { + implicit val tagSA = lA.sourceType.asInstanceOf[RType[SA]] + RType[SColl[SA]] + } + def lift(x: SColl[SA]): Ref[Coll[A]] = CollConst(x, lA) + } + implicit final def liftableColl[SA, A](implicit lA: Liftable[SA,A]): Liftable[SColl[SA], Coll[A]] = + LiftableColl(lA) + + private val CollClass = RClass(classOf[Coll[_]]) + + // entityAdapter for Coll trait + case class CollAdapter[A](source: Ref[Coll[A]]) + extends Node with Coll[A] + with Def[Coll[A]] { + implicit lazy val eA = source.elem.typeArgs("A")._1.asInstanceOf[Elem[A]] + + val resultType: Elem[Coll[A]] = element[Coll[A]] + override def transform(t: Transformer) = CollAdapter[A](t(source)) + + def length: Ref[Int] = { + asRep[Int](mkMethodCall(source, + CollClass.getMethod("length"), + ArraySeq.empty, + true, true, element[Int])) + } + + def apply(i: Ref[Int]): Ref[A] = { + asRep[A](mkMethodCall(source, + CollClass.getMethod("apply", classOf[Sym]), + Array[AnyRef](i), + true, true, element[A])) + } + + def getOrElse(index: Ref[Int], default: Ref[A]): Ref[A] = { + asRep[A](mkMethodCall(source, + CollClass.getMethod("getOrElse", classOf[Sym], classOf[Sym]), + Array[AnyRef](index, default), + true, true, element[A])) + } + + def map[B](f: Ref[A => B]): Ref[Coll[B]] = { + implicit val eB = f.elem.eRange + asRep[Coll[B]](mkMethodCall(source, + CollClass.getMethod("map", classOf[Sym]), + Array[AnyRef](f), + true, true, element[Coll[B]])) + } + + def zip[B](ys: Ref[Coll[B]]): Ref[Coll[(A, B)]] = { + implicit val eB = ys.eA + asRep[Coll[(A, B)]](mkMethodCall(source, + CollClass.getMethod("zip", classOf[Sym]), + Array[AnyRef](ys), + true, true, element[Coll[(A, B)]])) + } + + def exists(p: Ref[A => Boolean]): Ref[Boolean] = { + asRep[Boolean](mkMethodCall(source, + CollClass.getMethod("exists", classOf[Sym]), + Array[AnyRef](p), + true, true, element[Boolean])) + } + + def forall(p: Ref[A => Boolean]): Ref[Boolean] = { + asRep[Boolean](mkMethodCall(source, + CollClass.getMethod("forall", classOf[Sym]), + Array[AnyRef](p), + true, true, element[Boolean])) + } + + def filter(p: Ref[A => Boolean]): Ref[Coll[A]] = { + asRep[Coll[A]](mkMethodCall(source, + CollClass.getMethod("filter", classOf[Sym]), + Array[AnyRef](p), + true, true, element[Coll[A]])) + } + + def foldLeft[B](zero: Ref[B], op: Ref[((B, A)) => B]): Ref[B] = { + implicit val eB = zero.elem + asRep[B](mkMethodCall(source, + CollClass.getMethod("foldLeft", classOf[Sym], classOf[Sym]), + Array[AnyRef](zero, op), + true, true, element[B])) + } + + def indices: Ref[Coll[Int]] = { + asRep[Coll[Int]](mkMethodCall(source, + CollClass.getMethod("indices"), + ArraySeq.empty, + true, true, element[Coll[Int]])) + } + + def flatMap[B](f: Ref[A => Coll[B]]): Ref[Coll[B]] = { + implicit val eB = f.elem.eRange.typeArgs("A")._1.asInstanceOf[Elem[B]] + asRep[Coll[B]](mkMethodCall(source, + CollClass.getMethod("flatMap", classOf[Sym]), + Array[AnyRef](f), + true, true, element[Coll[B]])) + } + + override def indexOf(elem: Ref[A], from: Ref[Int]): Ref[Int] = { + asRep[Int](mkMethodCall(source, + CollClass.getMethod("indexOf", classOf[Sym], classOf[Sym]), + Array[AnyRef](elem, from), + true, true, element[Int])) + } + + def patch(from: Ref[Int], patch: Ref[Coll[A]], replaced: Ref[Int]): Ref[Coll[A]] = { + asRep[Coll[A]](mkMethodCall(source, + CollClass.getMethod("patch", classOf[Sym], classOf[Sym], classOf[Sym]), + Array[AnyRef](from, patch, replaced), + true, true, element[Coll[A]])) + } + + def updated(index: Ref[Int], elem: Ref[A]): Ref[Coll[A]] = { + asRep[Coll[A]](mkMethodCall(source, + CollClass.getMethod("updated", classOf[Sym], classOf[Sym]), + Array[AnyRef](index, elem), + true, true, element[Coll[A]])) + } + + def updateMany(indexes: Ref[Coll[Int]], values: Ref[Coll[A]]): Ref[Coll[A]] = { + asRep[Coll[A]](mkMethodCall(source, + CollClass.getMethod("updateMany", classOf[Sym], classOf[Sym]), + Array[AnyRef](indexes, values), + true, true, element[Coll[A]])) + } + + def slice(from: Ref[Int], until: Ref[Int]): Ref[Coll[A]] = { + asRep[Coll[A]](mkMethodCall(source, + CollClass.getMethod("slice", classOf[Sym], classOf[Sym]), + Array[AnyRef](from, until), + true, true, element[Coll[A]])) + } + + def append(other: Ref[Coll[A]]): Ref[Coll[A]] = { + asRep[Coll[A]](mkMethodCall(source, + CollClass.getMethod("append", classOf[Sym]), + Array[AnyRef](other), + true, true, element[Coll[A]])) + } + } + + // entityUnref: single unref method for each type family + val createCollAdapter: Ref[Coll[Any]] => Coll[Any] = x => CollAdapter(x) + + implicit final def unrefColl[A](p: Ref[Coll[A]]): Coll[A] = { + val sym = p.asInstanceOf[SingleRef[Coll[A]]] + sym.getAdapter( + p.node.isInstanceOf[Coll[A]@unchecked], + createCollAdapter.asInstanceOf[Ref[Coll[A]] => Coll[A]]) + } + + implicit final def castCollElement[A](elem: Elem[Coll[A]]): CollElem[A, Coll[A]] = + elem.asInstanceOf[CollElem[A, Coll[A]]] + + implicit lazy val containerColl: Functor[Coll] = new Functor[Coll] { + def lift[A](implicit evA: Elem[A]) = element[Coll[A]] + def unlift[A](implicit eFT: Elem[Coll[A]]) = + castCollElement(eFT).eA + def unapply[T](e: Elem[_]) = e match { + case e: CollElem[_,_] => Some(asElem[Coll[T]](e)) + case _ => None + } + def map[A,B](xs: Ref[Coll[A]])(f: Ref[A] => Ref[B]) = { implicit val eA = unlift(xs.elem); xs.map(fun(f))} + } + + // manual fix: CollIso, collIso + + // familyElem + class CollElem[A, To <: Coll[A]](implicit _eA: Elem[A]) + extends EntityElem1[A, To, Coll](_eA, container[Coll]) { + def eA = _eA + + override val liftable: Liftables.Liftable[_, To] = asLiftable[SColl[_], To](liftableColl(_eA.liftable)) + + override protected def collectMethods: Map[RMethod, MethodDesc] = { + super.collectMethods ++ + Elem.declaredMethods(RClass(classOf[Coll[A]]), RClass(classOf[SColl[_]]), Set( + "length", "apply", "getOrElse", "map", "zip", "exists", "forall", "filter", "foldLeft", "indices", "flatMap", "indexOf", "patch", "updated", "updateMany", "slice", "append" + )) + } + + override def buildTypeArgs = super.buildTypeArgs ++ TypeArgs("A" -> (eA -> scalan.util.Invariant)) + } + + implicit final def collElement[A](implicit eA: Elem[A]): Elem[Coll[A]] = + cachedElemByClass(eA)(RClass(classOf[CollElem[A, Coll[A]]])) + + // manual fix: ViewColl + + object CollMethods { + object length { + def unapply(d: Def[_]): Nullable[Ref[Coll[A]] forSome {type A}] = d match { + case MethodCall(receiver, method, _, _) if method.getName == "length" && receiver.elem.isInstanceOf[CollElem[_, _]] => + val res = receiver + Nullable(res).asInstanceOf[Nullable[Ref[Coll[A]] forSome {type A}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[Ref[Coll[A]] forSome {type A}] = unapply(exp.node) + } + + object apply { + def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Int]) forSome {type A}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "apply" && receiver.elem.isInstanceOf[CollElem[_, _]] => + val res = (receiver, args(0)) + Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Int]) forSome {type A}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Int]) forSome {type A}] = unapply(exp.node) + } + + object getOrElse { + def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Int], Ref[A]) forSome {type A}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "getOrElse" && receiver.elem.isInstanceOf[CollElem[_, _]] => + val res = (receiver, args(0), args(1)) + Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Int], Ref[A]) forSome {type A}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Int], Ref[A]) forSome {type A}] = unapply(exp.node) + } + + object map { + def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => B]) forSome {type A; type B}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "map" && receiver.elem.isInstanceOf[CollElem[_, _]] => + val res = (receiver, args(0)) + Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => B]) forSome {type A; type B}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => B]) forSome {type A; type B}] = unapply(exp.node) + } + + object zip { + def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Coll[B]]) forSome {type A; type B}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "zip" && receiver.elem.isInstanceOf[CollElem[_, _]] => + val res = (receiver, args(0)) + Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Coll[B]]) forSome {type A; type B}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Coll[B]]) forSome {type A; type B}] = unapply(exp.node) + } + + object exists { + def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "exists" && receiver.elem.isInstanceOf[CollElem[_, _]] => + val res = (receiver, args(0)) + Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = unapply(exp.node) + } + + object forall { + def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "forall" && receiver.elem.isInstanceOf[CollElem[_, _]] => + val res = (receiver, args(0)) + Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = unapply(exp.node) + } + + object filter { + def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "filter" && receiver.elem.isInstanceOf[CollElem[_, _]] => + val res = (receiver, args(0)) + Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = unapply(exp.node) + } + + object foldLeft { + def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[B], Ref[((B, A)) => B]) forSome {type A; type B}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "foldLeft" && receiver.elem.isInstanceOf[CollElem[_, _]] => + val res = (receiver, args(0), args(1)) + Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[B], Ref[((B, A)) => B]) forSome {type A; type B}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[B], Ref[((B, A)) => B]) forSome {type A; type B}] = unapply(exp.node) + } + + object indices { + def unapply(d: Def[_]): Nullable[Ref[Coll[A]] forSome {type A}] = d match { + case MethodCall(receiver, method, _, _) if method.getName == "indices" && receiver.elem.isInstanceOf[CollElem[_, _]] => + val res = receiver + Nullable(res).asInstanceOf[Nullable[Ref[Coll[A]] forSome {type A}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[Ref[Coll[A]] forSome {type A}] = unapply(exp.node) + } + + object flatMap { + def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => Coll[B]]) forSome {type A; type B}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "flatMap" && receiver.elem.isInstanceOf[CollElem[_, _]] => + val res = (receiver, args(0)) + Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => Coll[B]]) forSome {type A; type B}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => Coll[B]]) forSome {type A; type B}] = unapply(exp.node) + } + + object slice { + def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Int], Ref[Int]) forSome {type A}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "slice" && receiver.elem.isInstanceOf[CollElem[_, _]] => + val res = (receiver, args(0), args(1)) + Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Int], Ref[Int]) forSome {type A}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Int], Ref[Int]) forSome {type A}] = unapply(exp.node) + } + + object append { + def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "append" && receiver.elem.isInstanceOf[CollElem[_, _]] => + val res = (receiver, args(0)) + Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}] = unapply(exp.node) + } + + } + +} // of object Coll +object Coll extends CollCls + registerEntityObject("Coll", Coll) + +object CollBuilder extends EntityObject("CollBuilder") { + // entityConst: single const for each entity + import Liftables._ + import scala.reflect.{ClassTag, classTag} + type SCollBuilder = special.collection.CollBuilder + case class CollBuilderConst( + constValue: SCollBuilder + ) extends LiftedConst[SCollBuilder, CollBuilder] with CollBuilder + with Def[CollBuilder] with CollBuilderConstMethods { + val liftable: Liftable[SCollBuilder, CollBuilder] = LiftableCollBuilder + val resultType: Elem[CollBuilder] = liftable.eW + } + + trait CollBuilderConstMethods extends CollBuilder { thisConst: Def[_] => + + private val CollBuilderClass = RClass(classOf[CollBuilder]) + + override def fromItems[T](items: Ref[T]*)(implicit cT: Elem[T]): Ref[Coll[T]] = { + asRep[Coll[T]](mkMethodCall(self, + CollBuilderClass.getMethod("fromItems", classOf[Seq[_]], classOf[Elem[_]]), + Array[AnyRef](items, cT), + true, false, element[Coll[T]])) + } + + override def xor(left: Ref[Coll[Byte]], right: Ref[Coll[Byte]]): Ref[Coll[Byte]] = { + asRep[Coll[Byte]](mkMethodCall(self, + CollBuilderClass.getMethod("xor", classOf[Sym], classOf[Sym]), + Array[AnyRef](left, right), + true, false, element[Coll[Byte]])) + } + + override def replicate[T](n: Ref[Int], v: Ref[T]): Ref[Coll[T]] = { + implicit val eT = v.elem + asRep[Coll[T]](mkMethodCall(self, + CollBuilderClass.getMethod("replicate", classOf[Sym], classOf[Sym]), + Array[AnyRef](n, v), + true, false, element[Coll[T]])) + } + } + + implicit object LiftableCollBuilder + extends Liftable[SCollBuilder, CollBuilder] { + lazy val eW: Elem[CollBuilder] = collBuilderElement + lazy val sourceType: RType[SCollBuilder] = { + RType[SCollBuilder] + } + def lift(x: SCollBuilder): Ref[CollBuilder] = CollBuilderConst(x) + } + + private val CollBuilderClass = RClass(classOf[CollBuilder]) + + // entityAdapter for CollBuilder trait + case class CollBuilderAdapter(source: Ref[CollBuilder]) + extends Node with CollBuilder + with Def[CollBuilder] { + val resultType: Elem[CollBuilder] = element[CollBuilder] + override def transform(t: Transformer) = CollBuilderAdapter(t(source)) + + def fromItems[T](items: Ref[T]*)(implicit cT: Elem[T]): Ref[Coll[T]] = { + asRep[Coll[T]](mkMethodCall(source, + CollBuilderClass.getMethod("fromItems", classOf[Seq[_]], classOf[Elem[_]]), + Array[AnyRef](items, cT), + true, true, element[Coll[T]])) + } + + def xor(left: Ref[Coll[Byte]], right: Ref[Coll[Byte]]): Ref[Coll[Byte]] = { + asRep[Coll[Byte]](mkMethodCall(source, + CollBuilderClass.getMethod("xor", classOf[Sym], classOf[Sym]), + Array[AnyRef](left, right), + true, true, element[Coll[Byte]])) + } + + def replicate[T](n: Ref[Int], v: Ref[T]): Ref[Coll[T]] = { + implicit val eT = v.elem + asRep[Coll[T]](mkMethodCall(source, + CollBuilderClass.getMethod("replicate", classOf[Sym], classOf[Sym]), + Array[AnyRef](n, v), + true, true, element[Coll[T]])) + } + } + + // entityUnref: single unref method for each type family + val createCollBuilderAdapter: Ref[CollBuilder] => CollBuilder = x => CollBuilderAdapter(x) + + implicit final def unrefCollBuilder(p: Ref[CollBuilder]): CollBuilder = + p.asInstanceOf[SingleRef[CollBuilder]].getAdapter( + p.node.isInstanceOf[CollBuilder], + createCollBuilderAdapter.asInstanceOf[Ref[CollBuilder] => CollBuilder]) + + // familyElem + class CollBuilderElem[To <: CollBuilder] + extends EntityElem[To] { + override val liftable: Liftables.Liftable[_, To] = asLiftable[SCollBuilder, To](LiftableCollBuilder) + + override protected def collectMethods: Map[RMethod, MethodDesc] = { + super.collectMethods ++ + Elem.declaredMethods(RClass(classOf[CollBuilder]), RClass(classOf[SCollBuilder]), Set( + "fromItems", "xor", "replicate" + )) + } + } + + implicit lazy val collBuilderElement: Elem[CollBuilder] = + new CollBuilderElem[CollBuilder] + + object CollBuilderMethods { + object fromItems { + def unapply(d: Def[_]): Nullable[(Ref[CollBuilder], Seq[Ref[T]], Elem[T]) forSome {type T}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "fromItems" && receiver.elem.isInstanceOf[CollBuilderElem[_]] => + val res = (receiver, args(0), args(1)) + Nullable(res).asInstanceOf[Nullable[(Ref[CollBuilder], Seq[Ref[T]], Elem[T]) forSome {type T}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[CollBuilder], Seq[Ref[T]], Elem[T]) forSome {type T}] = unapply(exp.node) + } + + object xor { + def unapply(d: Def[_]): Nullable[(Ref[CollBuilder], Ref[Coll[Byte]], Ref[Coll[Byte]])] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "xor" && receiver.elem.isInstanceOf[CollBuilderElem[_]] => + val res = (receiver, args(0), args(1)) + Nullable(res).asInstanceOf[Nullable[(Ref[CollBuilder], Ref[Coll[Byte]], Ref[Coll[Byte]])]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[CollBuilder], Ref[Coll[Byte]], Ref[Coll[Byte]])] = unapply(exp.node) + } + + object replicate { + def unapply(d: Def[_]): Nullable[(Ref[CollBuilder], Ref[Int], Ref[T]) forSome {type T}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "replicate" && receiver.elem.isInstanceOf[CollBuilderElem[_]] => + val res = (receiver, args(0), args(1)) + Nullable(res).asInstanceOf[Nullable[(Ref[CollBuilder], Ref[Int], Ref[T]) forSome {type T}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[CollBuilder], Ref[Int], Ref[T]) forSome {type T}] = unapply(exp.node) + } + } + +} // of object CollBuilder + registerEntityObject("CollBuilder", CollBuilder) + + override def resetContext(): Unit = { + super.resetContext() + } + + registerModule(CollsModule) +} + +object CollsModule extends scalan.ModuleInfo("special.collection", "Colls") { + val reflection = GraphIRReflection +} +} + +trait CollsModule extends special.collection.impl.CollsDefs {self: Library =>} diff --git a/sigma-library/src/main/scala/special/sigma/SigmaDslUnit.scala b/graph-ir/src/main/scala/special/sigma/SigmaDslUnit.scala similarity index 72% rename from sigma-library/src/main/scala/special/sigma/SigmaDslUnit.scala rename to graph-ir/src/main/scala/special/sigma/SigmaDslUnit.scala index 5bd2ad784b..43ba7f5db2 100644 --- a/sigma-library/src/main/scala/special/sigma/SigmaDslUnit.scala +++ b/graph-ir/src/main/scala/special/sigma/SigmaDslUnit.scala @@ -1,35 +1,17 @@ package special.sigma { - import scalan.OverloadHack.Overloaded1 // manual fix import scalan._ trait SigmaDsl extends Base { self: SigmaLibrary => trait BigInt extends Def[BigInt] { - def toByte: Ref[Byte]; - def toShort: Ref[Short]; - def toInt: Ref[Int]; - def toLong: Ref[Long]; - def toBytes: Ref[Coll[Byte]]; - def toBits: Ref[Coll[Boolean]]; - def toAbs: Ref[BigInt]; - def compareTo(that: Ref[BigInt]): Ref[Int]; - def modQ: Ref[BigInt]; - def plusModQ(other: Ref[BigInt]): Ref[BigInt]; - def minusModQ(other: Ref[BigInt]): Ref[BigInt]; - def multModQ(other: Ref[BigInt]): Ref[BigInt]; - def inverseModQ: Ref[BigInt]; - def signum: Ref[Int]; def add(that: Ref[BigInt]): Ref[BigInt]; def subtract(that: Ref[BigInt]): Ref[BigInt]; def multiply(that: Ref[BigInt]): Ref[BigInt]; def divide(that: Ref[BigInt]): Ref[BigInt]; def mod(m: Ref[BigInt]): Ref[BigInt]; - def remainder(that: Ref[BigInt]): Ref[BigInt]; def min(that: Ref[BigInt]): Ref[BigInt]; def max(that: Ref[BigInt]): Ref[BigInt]; - def negate: Ref[BigInt] }; trait GroupElement extends Def[GroupElement] { - def isInfinity: Ref[Boolean]; def exp(k: Ref[BigInt]): Ref[GroupElement]; def multiply(that: Ref[GroupElement]): Ref[GroupElement]; def negate: Ref[GroupElement]; @@ -41,31 +23,15 @@ package special.sigma { def &&(other: Ref[SigmaProp]): Ref[SigmaProp]; def ||(other: Ref[SigmaProp]): Ref[SigmaProp]; }; - trait AnyValue extends Def[AnyValue] { - def value: Ref[Any]; - def tVal: Ref[WRType[Any]] - }; trait Box extends Def[Box] { def id: Ref[Coll[Byte]]; def value: Ref[Long]; def propositionBytes: Ref[Coll[Byte]]; def bytes: Ref[Coll[Byte]]; def bytesWithoutRef: Ref[Coll[Byte]]; - def registers: Ref[Coll[AnyValue]]; def getReg[T](i: Ref[Int])(implicit cT: Elem[T]): Ref[WOption[T]]; - def R0[T](implicit cT: Elem[T]): Ref[WOption[T]] = this.getReg[T](toRep(0.asInstanceOf[Int])); - def R1[T](implicit cT: Elem[T]): Ref[WOption[T]] = this.getReg[T](toRep(1.asInstanceOf[Int])); - def R2[T](implicit cT: Elem[T]): Ref[WOption[T]] = this.getReg[T](toRep(2.asInstanceOf[Int])); - def R3[T](implicit cT: Elem[T]): Ref[WOption[T]] = this.getReg[T](toRep(3.asInstanceOf[Int])); - def R4[T](implicit cT: Elem[T]): Ref[WOption[T]] = this.getReg[T](toRep(4.asInstanceOf[Int])); - def R5[T](implicit cT: Elem[T]): Ref[WOption[T]] = this.getReg[T](toRep(5.asInstanceOf[Int])); - def R6[T](implicit cT: Elem[T]): Ref[WOption[T]] = this.getReg[T](toRep(6.asInstanceOf[Int])); - def R7[T](implicit cT: Elem[T]): Ref[WOption[T]] = this.getReg[T](toRep(7.asInstanceOf[Int])); - def R8[T](implicit cT: Elem[T]): Ref[WOption[T]] = this.getReg[T](toRep(8.asInstanceOf[Int])); - def R9[T](implicit cT: Elem[T]): Ref[WOption[T]] = this.getReg[T](toRep(9.asInstanceOf[Int])); def tokens: Ref[Coll[scala.Tuple2[Coll[Byte], Long]]]; def creationInfo: Ref[scala.Tuple2[Int, Coll[Byte]]]; - def executeFromRegister[T](regId: Ref[Byte])(implicit cT: Elem[T]): Ref[T] }; trait AvlTree extends Def[AvlTree] { def digest: Ref[Coll[Byte]]; @@ -111,7 +77,6 @@ package special.sigma { def votes: Ref[Coll[Byte]] }; trait Context extends Def[Context] { - def builder: Ref[SigmaDslBuilder]; def OUTPUTS: Ref[Coll[Box]]; def INPUTS: Ref[Coll[Box]]; def dataInputs: Ref[Coll[Box]]; @@ -123,11 +88,9 @@ package special.sigma { def preHeader: Ref[PreHeader]; def minerPubKey: Ref[Coll[Byte]]; def getVar[T](id: Ref[Byte])(implicit cT: Elem[T]): Ref[WOption[T]]; - def vars: Ref[Coll[AnyValue]] }; trait SigmaDslBuilder extends Def[SigmaDslBuilder] { def Colls: Ref[CollBuilder]; - def verifyZK(cond: Ref[Thunk[SigmaProp]]): Ref[Boolean]; def atLeast(bound: Ref[Int], props: Ref[Coll[SigmaProp]]): Ref[SigmaProp]; def allOf(conditions: Ref[Coll[Boolean]]): Ref[Boolean]; def allZK(conditions: Ref[Coll[SigmaProp]]): Ref[SigmaProp]; @@ -145,6 +108,7 @@ package special.sigma { def groupGenerator: Ref[GroupElement]; def substConstants[T](scriptBytes: Ref[Coll[Byte]], positions: Ref[Coll[Int]], newValues: Ref[Coll[T]]): Ref[Coll[Byte]]; def decodePoint(encoded: Ref[Coll[Byte]]): Ref[GroupElement]; + /** This method will be used in v6.0 to handle CreateAvlTree operation in GraphBuilding */ def avlTree(operationFlags: Ref[Byte], digest: Ref[Coll[Byte]], keyLength: Ref[Int], valueLengthOpt: Ref[WOption[Int]]): Ref[AvlTree]; def xor(l: Ref[Coll[Byte]], r: Ref[Coll[Byte]]): Ref[Coll[Byte]] }; @@ -152,7 +116,6 @@ package special.sigma { trait BigIntCompanion; trait GroupElementCompanion; trait SigmaPropCompanion; - trait AnyValueCompanion; trait BoxCompanion; trait AvlTreeCompanion; trait PreHeaderCompanion; diff --git a/sigma-library/src/main/scala/special/sigma/impl/SigmaDslImpl.scala b/graph-ir/src/main/scala/special/sigma/impl/SigmaDslImpl.scala similarity index 65% rename from sigma-library/src/main/scala/special/sigma/impl/SigmaDslImpl.scala rename to graph-ir/src/main/scala/special/sigma/impl/SigmaDslImpl.scala index 8195aed696..c82b88c94e 100644 --- a/sigma-library/src/main/scala/special/sigma/impl/SigmaDslImpl.scala +++ b/graph-ir/src/main/scala/special/sigma/impl/SigmaDslImpl.scala @@ -7,12 +7,13 @@ import scala.reflect._ import scala.collection.compat.immutable.ArraySeq package impl { - import scalan.OverloadHack.Overloaded1 // manual fix + import scalan.OverloadHack.Overloaded1 + import scalan.reflection.CommonReflection.registerClassEntry + import scalan.reflection.{RClass, RMethod, SRMethod} // manual fix // Abs ----------------------------------- trait SigmaDslDefs extends scalan.Scalan with SigmaDsl { self: SigmaLibrary => -import AnyValue._ import AvlTree._ import BigInt._ import Box._ @@ -42,105 +43,7 @@ object BigInt extends EntityObject("BigInt") { trait BigIntConstMethods extends BigInt { thisConst: Def[_] => - private val BigIntClass = classOf[BigInt] - - override def toByte: Ref[Byte] = { - asRep[Byte](mkMethodCall(self, - BigIntClass.getMethod("toByte"), - ArraySeq.empty, - true, false, element[Byte])) - } - - override def toShort: Ref[Short] = { - asRep[Short](mkMethodCall(self, - BigIntClass.getMethod("toShort"), - ArraySeq.empty, - true, false, element[Short])) - } - - override def toInt: Ref[Int] = { - asRep[Int](mkMethodCall(self, - BigIntClass.getMethod("toInt"), - ArraySeq.empty, - true, false, element[Int])) - } - - override def toLong: Ref[Long] = { - asRep[Long](mkMethodCall(self, - BigIntClass.getMethod("toLong"), - ArraySeq.empty, - true, false, element[Long])) - } - - override def toBytes: Ref[Coll[Byte]] = { - asRep[Coll[Byte]](mkMethodCall(self, - BigIntClass.getMethod("toBytes"), - ArraySeq.empty, - true, false, element[Coll[Byte]])) - } - - override def toBits: Ref[Coll[Boolean]] = { - asRep[Coll[Boolean]](mkMethodCall(self, - BigIntClass.getMethod("toBits"), - ArraySeq.empty, - true, false, element[Coll[Boolean]])) - } - - override def toAbs: Ref[BigInt] = { - asRep[BigInt](mkMethodCall(self, - BigIntClass.getMethod("toAbs"), - ArraySeq.empty, - true, false, element[BigInt])) - } - - override def compareTo(that: Ref[BigInt]): Ref[Int] = { - asRep[Int](mkMethodCall(self, - BigIntClass.getMethod("compareTo", classOf[Sym]), - Array[AnyRef](that), - true, false, element[Int])) - } - - override def modQ: Ref[BigInt] = { - asRep[BigInt](mkMethodCall(self, - BigIntClass.getMethod("modQ"), - ArraySeq.empty, - true, false, element[BigInt])) - } - - override def plusModQ(other: Ref[BigInt]): Ref[BigInt] = { - asRep[BigInt](mkMethodCall(self, - BigIntClass.getMethod("plusModQ", classOf[Sym]), - Array[AnyRef](other), - true, false, element[BigInt])) - } - - override def minusModQ(other: Ref[BigInt]): Ref[BigInt] = { - asRep[BigInt](mkMethodCall(self, - BigIntClass.getMethod("minusModQ", classOf[Sym]), - Array[AnyRef](other), - true, false, element[BigInt])) - } - - override def multModQ(other: Ref[BigInt]): Ref[BigInt] = { - asRep[BigInt](mkMethodCall(self, - BigIntClass.getMethod("multModQ", classOf[Sym]), - Array[AnyRef](other), - true, false, element[BigInt])) - } - - override def inverseModQ: Ref[BigInt] = { - asRep[BigInt](mkMethodCall(self, - BigIntClass.getMethod("inverseModQ"), - ArraySeq.empty, - true, false, element[BigInt])) - } - - override def signum: Ref[Int] = { - asRep[Int](mkMethodCall(self, - BigIntClass.getMethod("signum"), - ArraySeq.empty, - true, false, element[Int])) - } + private val BigIntClass = RClass(classOf[BigInt]) override def add(that: Ref[BigInt]): Ref[BigInt] = { asRep[BigInt](mkMethodCall(self, @@ -177,13 +80,6 @@ object BigInt extends EntityObject("BigInt") { true, false, element[BigInt])) } - override def remainder(that: Ref[BigInt]): Ref[BigInt] = { - asRep[BigInt](mkMethodCall(self, - BigIntClass.getMethod("remainder", classOf[Sym]), - Array[AnyRef](that), - true, false, element[BigInt])) - } - override def min(that: Ref[BigInt]): Ref[BigInt] = { asRep[BigInt](mkMethodCall(self, BigIntClass.getMethod("min", classOf[Sym]), @@ -197,13 +93,6 @@ object BigInt extends EntityObject("BigInt") { Array[AnyRef](that), true, false, element[BigInt])) } - - override def negate: Ref[BigInt] = { - asRep[BigInt](mkMethodCall(self, - BigIntClass.getMethod("negate"), - ArraySeq.empty, - true, false, element[BigInt])) - } } implicit object LiftableBigInt @@ -213,14 +102,9 @@ object BigInt extends EntityObject("BigInt") { RType[SBigInt] } def lift(x: SBigInt): Ref[BigInt] = BigIntConst(x) - def unlift(w: Ref[BigInt]): SBigInt = w match { - case Def(BigIntConst(x: SBigInt)) - => x.asInstanceOf[SBigInt] - case _ => unliftError(w) - } } - private val BigIntClass = classOf[BigInt] + private val BigIntClass = RClass(classOf[BigInt]) // entityAdapter for BigInt trait case class BigIntAdapter(source: Ref[BigInt]) @@ -229,104 +113,6 @@ object BigInt extends EntityObject("BigInt") { val resultType: Elem[BigInt] = element[BigInt] override def transform(t: Transformer) = BigIntAdapter(t(source)) - def toByte: Ref[Byte] = { - asRep[Byte](mkMethodCall(source, - BigIntClass.getMethod("toByte"), - ArraySeq.empty, - true, true, element[Byte])) - } - - def toShort: Ref[Short] = { - asRep[Short](mkMethodCall(source, - BigIntClass.getMethod("toShort"), - ArraySeq.empty, - true, true, element[Short])) - } - - def toInt: Ref[Int] = { - asRep[Int](mkMethodCall(source, - BigIntClass.getMethod("toInt"), - ArraySeq.empty, - true, true, element[Int])) - } - - def toLong: Ref[Long] = { - asRep[Long](mkMethodCall(source, - BigIntClass.getMethod("toLong"), - ArraySeq.empty, - true, true, element[Long])) - } - - def toBytes: Ref[Coll[Byte]] = { - asRep[Coll[Byte]](mkMethodCall(source, - BigIntClass.getMethod("toBytes"), - ArraySeq.empty, - true, true, element[Coll[Byte]])) - } - - def toBits: Ref[Coll[Boolean]] = { - asRep[Coll[Boolean]](mkMethodCall(source, - BigIntClass.getMethod("toBits"), - ArraySeq.empty, - true, true, element[Coll[Boolean]])) - } - - def toAbs: Ref[BigInt] = { - asRep[BigInt](mkMethodCall(source, - BigIntClass.getMethod("toAbs"), - ArraySeq.empty, - true, true, element[BigInt])) - } - - def compareTo(that: Ref[BigInt]): Ref[Int] = { - asRep[Int](mkMethodCall(source, - BigIntClass.getMethod("compareTo", classOf[Sym]), - Array[AnyRef](that), - true, true, element[Int])) - } - - def modQ: Ref[BigInt] = { - asRep[BigInt](mkMethodCall(source, - BigIntClass.getMethod("modQ"), - ArraySeq.empty, - true, true, element[BigInt])) - } - - def plusModQ(other: Ref[BigInt]): Ref[BigInt] = { - asRep[BigInt](mkMethodCall(source, - BigIntClass.getMethod("plusModQ", classOf[Sym]), - Array[AnyRef](other), - true, true, element[BigInt])) - } - - def minusModQ(other: Ref[BigInt]): Ref[BigInt] = { - asRep[BigInt](mkMethodCall(source, - BigIntClass.getMethod("minusModQ", classOf[Sym]), - Array[AnyRef](other), - true, true, element[BigInt])) - } - - def multModQ(other: Ref[BigInt]): Ref[BigInt] = { - asRep[BigInt](mkMethodCall(source, - BigIntClass.getMethod("multModQ", classOf[Sym]), - Array[AnyRef](other), - true, true, element[BigInt])) - } - - def inverseModQ: Ref[BigInt] = { - asRep[BigInt](mkMethodCall(source, - BigIntClass.getMethod("inverseModQ"), - ArraySeq.empty, - true, true, element[BigInt])) - } - - def signum: Ref[Int] = { - asRep[Int](mkMethodCall(source, - BigIntClass.getMethod("signum"), - ArraySeq.empty, - true, true, element[Int])) - } - def add(that: Ref[BigInt]): Ref[BigInt] = { asRep[BigInt](mkMethodCall(source, BigIntClass.getMethod("add", classOf[Sym]), @@ -362,13 +148,6 @@ object BigInt extends EntityObject("BigInt") { true, true, element[BigInt])) } - def remainder(that: Ref[BigInt]): Ref[BigInt] = { - asRep[BigInt](mkMethodCall(source, - BigIntClass.getMethod("remainder", classOf[Sym]), - Array[AnyRef](that), - true, true, element[BigInt])) - } - def min(that: Ref[BigInt]): Ref[BigInt] = { asRep[BigInt](mkMethodCall(source, BigIntClass.getMethod("min", classOf[Sym]), @@ -382,13 +161,6 @@ object BigInt extends EntityObject("BigInt") { Array[AnyRef](that), true, true, element[BigInt])) } - - def negate: Ref[BigInt] = { - asRep[BigInt](mkMethodCall(source, - BigIntClass.getMethod("negate"), - ArraySeq.empty, - true, true, element[BigInt])) - } } // entityUnref: single unref method for each type family @@ -403,10 +175,10 @@ object BigInt extends EntityObject("BigInt") { extends EntityElem[To] { override val liftable: Liftables.Liftable[_, To] = asLiftable[SBigInt, To](LiftableBigInt) - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { + override protected def collectMethods: Map[RMethod, MethodDesc] = { super.collectMethods ++ - Elem.declaredMethods(classOf[BigInt], classOf[SBigInt], Set( - "toByte", "toShort", "toInt", "toLong", "toBytes", "toBits", "toAbs", "compareTo", "modQ", "plusModQ", "minusModQ", "multModQ", "inverseModQ", "signum", "add", "subtract", "multiply", "divide", "mod", "remainder", "min", "max", "negate" + Elem.declaredMethods(RClass(classOf[BigInt]), RClass(classOf[SBigInt]), Set( + "add", "subtract", "multiply", "divide", "mod", "min", "max" )) } } @@ -414,159 +186,7 @@ object BigInt extends EntityObject("BigInt") { implicit lazy val bigIntElement: Elem[BigInt] = new BigIntElem[BigInt] - implicit case object BigIntCompanionElem extends CompanionElem[BigIntCompanionCtor] - - abstract class BigIntCompanionCtor extends CompanionDef[BigIntCompanionCtor] with BigIntCompanion { - def resultType = BigIntCompanionElem - override def toString = "BigInt" - } - implicit final def unrefBigIntCompanionCtor(p: Ref[BigIntCompanionCtor]): BigIntCompanionCtor = - p.node.asInstanceOf[BigIntCompanionCtor] - - lazy val RBigInt: MutableLazy[BigIntCompanionCtor] = MutableLazy(new BigIntCompanionCtor { - private val thisClass = classOf[BigIntCompanion] - }) - object BigIntMethods { - object toByte { - def unapply(d: Def[_]): Nullable[Ref[BigInt]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "toByte" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[BigInt]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[BigInt]] = unapply(exp.node) - } - - object toShort { - def unapply(d: Def[_]): Nullable[Ref[BigInt]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "toShort" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[BigInt]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[BigInt]] = unapply(exp.node) - } - - object toInt { - def unapply(d: Def[_]): Nullable[Ref[BigInt]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "toInt" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[BigInt]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[BigInt]] = unapply(exp.node) - } - - object toLong { - def unapply(d: Def[_]): Nullable[Ref[BigInt]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "toLong" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[BigInt]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[BigInt]] = unapply(exp.node) - } - - object toBytes { - def unapply(d: Def[_]): Nullable[Ref[BigInt]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "toBytes" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[BigInt]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[BigInt]] = unapply(exp.node) - } - - object toBits { - def unapply(d: Def[_]): Nullable[Ref[BigInt]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "toBits" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[BigInt]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[BigInt]] = unapply(exp.node) - } - - object toAbs { - def unapply(d: Def[_]): Nullable[Ref[BigInt]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "toAbs" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[BigInt]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[BigInt]] = unapply(exp.node) - } - - object compareTo { - def unapply(d: Def[_]): Nullable[(Ref[BigInt], Ref[BigInt])] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "compareTo" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[BigInt], Ref[BigInt])]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[BigInt], Ref[BigInt])] = unapply(exp.node) - } - - object modQ { - def unapply(d: Def[_]): Nullable[Ref[BigInt]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "modQ" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[BigInt]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[BigInt]] = unapply(exp.node) - } - - object plusModQ { - def unapply(d: Def[_]): Nullable[(Ref[BigInt], Ref[BigInt])] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "plusModQ" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[BigInt], Ref[BigInt])]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[BigInt], Ref[BigInt])] = unapply(exp.node) - } - - object minusModQ { - def unapply(d: Def[_]): Nullable[(Ref[BigInt], Ref[BigInt])] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "minusModQ" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[BigInt], Ref[BigInt])]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[BigInt], Ref[BigInt])] = unapply(exp.node) - } - - object multModQ { - def unapply(d: Def[_]): Nullable[(Ref[BigInt], Ref[BigInt])] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "multModQ" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[BigInt], Ref[BigInt])]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[BigInt], Ref[BigInt])] = unapply(exp.node) - } - - object inverseModQ { - def unapply(d: Def[_]): Nullable[Ref[BigInt]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "inverseModQ" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[BigInt]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[BigInt]] = unapply(exp.node) - } - - object signum { - def unapply(d: Def[_]): Nullable[Ref[BigInt]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "signum" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[BigInt]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[BigInt]] = unapply(exp.node) - } object add { def unapply(d: Def[_]): Nullable[(Ref[BigInt], Ref[BigInt])] = d match { @@ -618,16 +238,6 @@ object BigInt extends EntityObject("BigInt") { def unapply(exp: Sym): Nullable[(Ref[BigInt], Ref[BigInt])] = unapply(exp.node) } - object remainder { - def unapply(d: Def[_]): Nullable[(Ref[BigInt], Ref[BigInt])] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "remainder" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[BigInt], Ref[BigInt])]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[BigInt], Ref[BigInt])] = unapply(exp.node) - } - object min { def unapply(d: Def[_]): Nullable[(Ref[BigInt], Ref[BigInt])] = d match { case MethodCall(receiver, method, args, _) if method.getName == "min" && receiver.elem.isInstanceOf[BigIntElem[_]] => @@ -648,19 +258,8 @@ object BigInt extends EntityObject("BigInt") { def unapply(exp: Sym): Nullable[(Ref[BigInt], Ref[BigInt])] = unapply(exp.node) } - object negate { - def unapply(d: Def[_]): Nullable[Ref[BigInt]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "negate" && receiver.elem.isInstanceOf[BigIntElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[BigInt]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[BigInt]] = unapply(exp.node) - } } - object BigIntCompanionMethods { - } } // of object BigInt registerEntityObject("BigInt", BigInt) @@ -679,14 +278,7 @@ object GroupElement extends EntityObject("GroupElement") { trait GroupElementConstMethods extends GroupElement { thisConst: Def[_] => - private val GroupElementClass = classOf[GroupElement] - - override def isInfinity: Ref[Boolean] = { - asRep[Boolean](mkMethodCall(self, - GroupElementClass.getMethod("isInfinity"), - ArraySeq.empty, - true, false, element[Boolean])) - } + private val GroupElementClass = RClass(classOf[GroupElement]) override def exp(k: Ref[BigInt]): Ref[GroupElement] = { asRep[GroupElement](mkMethodCall(self, @@ -724,14 +316,9 @@ object GroupElement extends EntityObject("GroupElement") { RType[SGroupElement] } def lift(x: SGroupElement): Ref[GroupElement] = GroupElementConst(x) - def unlift(w: Ref[GroupElement]): SGroupElement = w match { - case Def(GroupElementConst(x: SGroupElement)) - => x.asInstanceOf[SGroupElement] - case _ => unliftError(w) - } } - private val GroupElementClass = classOf[GroupElement] + private val GroupElementClass = RClass(classOf[GroupElement]) // entityAdapter for GroupElement trait case class GroupElementAdapter(source: Ref[GroupElement]) @@ -740,13 +327,6 @@ object GroupElement extends EntityObject("GroupElement") { val resultType: Elem[GroupElement] = element[GroupElement] override def transform(t: Transformer) = GroupElementAdapter(t(source)) - def isInfinity: Ref[Boolean] = { - asRep[Boolean](mkMethodCall(source, - GroupElementClass.getMethod("isInfinity"), - ArraySeq.empty, - true, true, element[Boolean])) - } - def exp(k: Ref[BigInt]): Ref[GroupElement] = { asRep[GroupElement](mkMethodCall(source, GroupElementClass.getMethod("exp", classOf[Sym]), @@ -788,10 +368,10 @@ object GroupElement extends EntityObject("GroupElement") { extends EntityElem[To] { override val liftable: Liftables.Liftable[_, To] = asLiftable[SGroupElement, To](LiftableGroupElement) - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { + override protected def collectMethods: Map[RMethod, MethodDesc] = { super.collectMethods ++ - Elem.declaredMethods(classOf[GroupElement], classOf[SGroupElement], Set( - "isInfinity", "exp", "multiply", "negate", "getEncoded" + Elem.declaredMethods(RClass(classOf[GroupElement]), RClass(classOf[SGroupElement]), Set( + "exp", "multiply", "negate", "getEncoded" )) } } @@ -799,30 +379,7 @@ object GroupElement extends EntityObject("GroupElement") { implicit lazy val groupElementElement: Elem[GroupElement] = new GroupElementElem[GroupElement] - implicit case object GroupElementCompanionElem extends CompanionElem[GroupElementCompanionCtor] - - abstract class GroupElementCompanionCtor extends CompanionDef[GroupElementCompanionCtor] with GroupElementCompanion { - def resultType = GroupElementCompanionElem - override def toString = "GroupElement" - } - implicit final def unrefGroupElementCompanionCtor(p: Ref[GroupElementCompanionCtor]): GroupElementCompanionCtor = - p.node.asInstanceOf[GroupElementCompanionCtor] - - lazy val RGroupElement: MutableLazy[GroupElementCompanionCtor] = MutableLazy(new GroupElementCompanionCtor { - private val thisClass = classOf[GroupElementCompanion] - }) - object GroupElementMethods { - object isInfinity { - def unapply(d: Def[_]): Nullable[Ref[GroupElement]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "isInfinity" && receiver.elem.isInstanceOf[GroupElementElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[GroupElement]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[GroupElement]] = unapply(exp.node) - } - object exp { def unapply(d: Def[_]): Nullable[(Ref[GroupElement], Ref[BigInt])] = d match { case MethodCall(receiver, method, args, _) if method.getName == "exp" && receiver.elem.isInstanceOf[GroupElementElem[_]] => @@ -842,29 +399,6 @@ object GroupElement extends EntityObject("GroupElement") { } def unapply(exp: Sym): Nullable[(Ref[GroupElement], Ref[GroupElement])] = unapply(exp.node) } - - object negate { - def unapply(d: Def[_]): Nullable[Ref[GroupElement]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "negate" && receiver.elem.isInstanceOf[GroupElementElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[GroupElement]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[GroupElement]] = unapply(exp.node) - } - - object getEncoded { - def unapply(d: Def[_]): Nullable[Ref[GroupElement]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "getEncoded" && receiver.elem.isInstanceOf[GroupElementElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[GroupElement]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[GroupElement]] = unapply(exp.node) - } - } - - object GroupElementCompanionMethods { } } // of object GroupElement registerEntityObject("GroupElement", GroupElement) @@ -884,7 +418,7 @@ object SigmaProp extends EntityObject("SigmaProp") { trait SigmaPropConstMethods extends SigmaProp { thisConst: Def[_] => - private val SigmaPropClass = classOf[SigmaProp] + private val SigmaPropClass = RClass(classOf[SigmaProp]) override def isValid: Ref[Boolean] = { asRep[Boolean](mkMethodCall(self, @@ -924,14 +458,9 @@ object SigmaProp extends EntityObject("SigmaProp") { RType[SSigmaProp] } def lift(x: SSigmaProp): Ref[SigmaProp] = SigmaPropConst(x) - def unlift(w: Ref[SigmaProp]): SSigmaProp = w match { - case Def(SigmaPropConst(x: SSigmaProp)) - => x.asInstanceOf[SSigmaProp] - case _ => unliftError(w) - } } - private val SigmaPropClass = classOf[SigmaProp] + private val SigmaPropClass = RClass(classOf[SigmaProp]) // entityAdapter for SigmaProp trait case class SigmaPropAdapter(source: Ref[SigmaProp]) @@ -962,240 +491,81 @@ object SigmaProp extends EntityObject("SigmaProp") { true, true, element[SigmaProp])) } - // manual fix || - def ||(other: Ref[SigmaProp]): Ref[SigmaProp] = { - asRep[SigmaProp](mkMethodCall(source, - SigmaPropClass.getMethod("$bar$bar", classOf[Sym]), - Array[AnyRef](other), - true, true, element[SigmaProp])) - } - - // manual fix - def builder: Ref[SigmaDslBuilder] = { - asRep[SigmaDslBuilder](mkMethodCall(source, - SigmaPropClass.getMethod("builder"), - Array[AnyRef](), - true, true, element[SigmaDslBuilder])) - } - } - - // entityUnref: single unref method for each type family - implicit final def unrefSigmaProp(p: Ref[SigmaProp]): SigmaProp = { - if (p.node.isInstanceOf[SigmaProp]) p.node.asInstanceOf[SigmaProp] - else - SigmaPropAdapter(p) - } - - // familyElem - class SigmaPropElem[To <: SigmaProp] - extends EntityElem[To] { - override val liftable: Liftables.Liftable[_, To] = asLiftable[SSigmaProp, To](LiftableSigmaProp) - - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { - super.collectMethods ++ - Elem.declaredMethods(classOf[SigmaProp], classOf[SSigmaProp], Set( - "isValid", "propBytes", "$amp$amp", "$bar$bar" - )) - } - } - - implicit lazy val sigmaPropElement: Elem[SigmaProp] = - new SigmaPropElem[SigmaProp] - - implicit case object SigmaPropCompanionElem extends CompanionElem[SigmaPropCompanionCtor] - - abstract class SigmaPropCompanionCtor extends CompanionDef[SigmaPropCompanionCtor] with SigmaPropCompanion { - def resultType = SigmaPropCompanionElem - override def toString = "SigmaProp" - } - implicit final def unrefSigmaPropCompanionCtor(p: Ref[SigmaPropCompanionCtor]): SigmaPropCompanionCtor = - p.node.asInstanceOf[SigmaPropCompanionCtor] - - lazy val RSigmaProp: MutableLazy[SigmaPropCompanionCtor] = MutableLazy(new SigmaPropCompanionCtor { - private val thisClass = classOf[SigmaPropCompanion] - }) - - object SigmaPropMethods { - object isValid { - def unapply(d: Def[_]): Nullable[Ref[SigmaProp]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "isValid" && receiver.elem.isInstanceOf[SigmaPropElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[SigmaProp]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[SigmaProp]] = unapply(exp.node) - } - - object propBytes { - def unapply(d: Def[_]): Nullable[Ref[SigmaProp]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "propBytes" && receiver.elem.isInstanceOf[SigmaPropElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[SigmaProp]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[SigmaProp]] = unapply(exp.node) - } - - object and_sigma_&& { - def unapply(d: Def[_]): Nullable[(Ref[SigmaProp], Ref[SigmaProp])] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "$amp$amp" && receiver.elem.isInstanceOf[SigmaPropElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[SigmaProp], Ref[SigmaProp])]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[SigmaProp], Ref[SigmaProp])] = unapply(exp.node) - } - - object or_sigma_|| { - def unapply(d: Def[_]): Nullable[(Ref[SigmaProp], Ref[SigmaProp])] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "$bar$bar" && receiver.elem.isInstanceOf[SigmaPropElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[SigmaProp], Ref[SigmaProp])]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[SigmaProp], Ref[SigmaProp])] = unapply(exp.node) - } - } - - object SigmaPropCompanionMethods { - } -} // of object SigmaProp - registerEntityObject("SigmaProp", SigmaProp) - -object AnyValue extends EntityObject("AnyValue") { - // entityConst: single const for each entity - import Liftables._ - import scala.reflect.{ClassTag, classTag} - type SAnyValue = special.sigma.AnyValue - case class AnyValueConst( - constValue: SAnyValue - ) extends LiftedConst[SAnyValue, AnyValue] with AnyValue - with Def[AnyValue] with AnyValueConstMethods { - val liftable: Liftable[SAnyValue, AnyValue] = LiftableAnyValue - val resultType: Elem[AnyValue] = liftable.eW - } - - trait AnyValueConstMethods extends AnyValue { thisConst: Def[_] => - - private val AnyValueClass = classOf[AnyValue] - - // manual fix - override def value: Ref[Any] = { - asRep[Any](mkMethodCall(self, - AnyValueClass.getMethod("value"), - ArraySeq.empty, - true, false, AnyElement)) - } - - override def tVal: Ref[WRType[Any]] = { - asRep[WRType[Any]](mkMethodCall(self, - AnyValueClass.getMethod("tVal"), - ArraySeq.empty, - true, false, element[WRType[Any]])) - } - } - - implicit object LiftableAnyValue - extends Liftable[SAnyValue, AnyValue] { - lazy val eW: Elem[AnyValue] = anyValueElement - lazy val sourceType: RType[SAnyValue] = { - RType[SAnyValue] - } - def lift(x: SAnyValue): Ref[AnyValue] = AnyValueConst(x) - def unlift(w: Ref[AnyValue]): SAnyValue = w match { - case Def(AnyValueConst(x: SAnyValue)) - => x.asInstanceOf[SAnyValue] - case _ => unliftError(w) - } - } - - private val AnyValueClass = classOf[AnyValue] - - // entityAdapter for AnyValue trait - case class AnyValueAdapter(source: Ref[AnyValue]) - extends Node with AnyValue - with Def[AnyValue] { - val resultType: Elem[AnyValue] = element[AnyValue] - override def transform(t: Transformer) = AnyValueAdapter(t(source)) - - // manual fix - def value: Ref[Any] = { - asRep[Any](mkMethodCall(source, - AnyValueClass.getMethod("value"), - ArraySeq.empty, - true, true, AnyElement)) - } - - def tVal: Ref[WRType[Any]] = { - asRep[WRType[Any]](mkMethodCall(source, - AnyValueClass.getMethod("tVal"), - ArraySeq.empty, - true, true, element[WRType[Any]])) + // manual fix || + def ||(other: Ref[SigmaProp]): Ref[SigmaProp] = { + asRep[SigmaProp](mkMethodCall(source, + SigmaPropClass.getMethod("$bar$bar", classOf[Sym]), + Array[AnyRef](other), + true, true, element[SigmaProp])) } } // entityUnref: single unref method for each type family - implicit final def unrefAnyValue(p: Ref[AnyValue]): AnyValue = { - if (p.node.isInstanceOf[AnyValue]) p.node.asInstanceOf[AnyValue] + implicit final def unrefSigmaProp(p: Ref[SigmaProp]): SigmaProp = { + if (p.node.isInstanceOf[SigmaProp]) p.node.asInstanceOf[SigmaProp] else - AnyValueAdapter(p) + SigmaPropAdapter(p) } // familyElem - class AnyValueElem[To <: AnyValue] + class SigmaPropElem[To <: SigmaProp] extends EntityElem[To] { - override val liftable: Liftables.Liftable[_, To] = asLiftable[SAnyValue, To](LiftableAnyValue) + override val liftable: Liftables.Liftable[_, To] = asLiftable[SSigmaProp, To](LiftableSigmaProp) - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { + override protected def collectMethods: Map[RMethod, MethodDesc] = { super.collectMethods ++ - Elem.declaredMethods(classOf[AnyValue], classOf[SAnyValue], Set( - "value", "tVal" + Elem.declaredMethods(RClass(classOf[SigmaProp]), RClass(classOf[SSigmaProp]), Set( + "isValid", "propBytes", "$amp$amp", "$bar$bar" )) } } - implicit lazy val anyValueElement: Elem[AnyValue] = - new AnyValueElem[AnyValue] - - implicit case object AnyValueCompanionElem extends CompanionElem[AnyValueCompanionCtor] - - abstract class AnyValueCompanionCtor extends CompanionDef[AnyValueCompanionCtor] with AnyValueCompanion { - def resultType = AnyValueCompanionElem - override def toString = "AnyValue" - } - implicit final def unrefAnyValueCompanionCtor(p: Ref[AnyValueCompanionCtor]): AnyValueCompanionCtor = - p.node.asInstanceOf[AnyValueCompanionCtor] - - lazy val RAnyValue: MutableLazy[AnyValueCompanionCtor] = MutableLazy(new AnyValueCompanionCtor { - private val thisClass = classOf[AnyValueCompanion] - }) + implicit lazy val sigmaPropElement: Elem[SigmaProp] = + new SigmaPropElem[SigmaProp] - object AnyValueMethods { - object value { - def unapply(d: Def[_]): Nullable[Ref[AnyValue]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "value" && receiver.elem.isInstanceOf[AnyValueElem[_]] => + object SigmaPropMethods { + object isValid { + def unapply(d: Def[_]): Nullable[Ref[SigmaProp]] = d match { + case MethodCall(receiver, method, _, _) if method.getName == "isValid" && receiver.elem.isInstanceOf[SigmaPropElem[_]] => val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[AnyValue]]] + Nullable(res).asInstanceOf[Nullable[Ref[SigmaProp]]] case _ => Nullable.None } - def unapply(exp: Sym): Nullable[Ref[AnyValue]] = unapply(exp.node) + def unapply(exp: Sym): Nullable[Ref[SigmaProp]] = unapply(exp.node) } - object tVal { - def unapply(d: Def[_]): Nullable[Ref[AnyValue]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "tVal" && receiver.elem.isInstanceOf[AnyValueElem[_]] => + object propBytes { + def unapply(d: Def[_]): Nullable[Ref[SigmaProp]] = d match { + case MethodCall(receiver, method, _, _) if method.getName == "propBytes" && receiver.elem.isInstanceOf[SigmaPropElem[_]] => val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[AnyValue]]] + Nullable(res).asInstanceOf[Nullable[Ref[SigmaProp]]] case _ => Nullable.None } - def unapply(exp: Sym): Nullable[Ref[AnyValue]] = unapply(exp.node) + def unapply(exp: Sym): Nullable[Ref[SigmaProp]] = unapply(exp.node) + } + + object and_sigma_&& { + def unapply(d: Def[_]): Nullable[(Ref[SigmaProp], Ref[SigmaProp])] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "$amp$amp" && receiver.elem.isInstanceOf[SigmaPropElem[_]] => + val res = (receiver, args(0)) + Nullable(res).asInstanceOf[Nullable[(Ref[SigmaProp], Ref[SigmaProp])]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[SigmaProp], Ref[SigmaProp])] = unapply(exp.node) } - } - object AnyValueCompanionMethods { + object or_sigma_|| { + def unapply(d: Def[_]): Nullable[(Ref[SigmaProp], Ref[SigmaProp])] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "$bar$bar" && receiver.elem.isInstanceOf[SigmaPropElem[_]] => + val res = (receiver, args(0)) + Nullable(res).asInstanceOf[Nullable[(Ref[SigmaProp], Ref[SigmaProp])]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[(Ref[SigmaProp], Ref[SigmaProp])] = unapply(exp.node) + } } -} // of object AnyValue - registerEntityObject("AnyValue", AnyValue) +} // of object SigmaProp + registerEntityObject("SigmaProp", SigmaProp) object Box extends EntityObject("Box") { // entityConst: single const for each entity @@ -1212,7 +582,7 @@ object Box extends EntityObject("Box") { trait BoxConstMethods extends Box { thisConst: Def[_] => - private val BoxClass = classOf[Box] + private val BoxClass = RClass(classOf[Box]) override def id: Ref[Coll[Byte]] = { asRep[Coll[Byte]](mkMethodCall(self, @@ -1249,13 +619,6 @@ object Box extends EntityObject("Box") { true, false, element[Coll[Byte]])) } - override def registers: Ref[Coll[AnyValue]] = { - asRep[Coll[AnyValue]](mkMethodCall(self, - BoxClass.getMethod("registers"), - ArraySeq.empty, - true, false, element[Coll[AnyValue]])) - } - override def getReg[T](i: Ref[Int])(implicit cT: Elem[T]): Ref[WOption[T]] = { asRep[WOption[T]](mkMethodCall(self, BoxClass.getMethod("getReg", classOf[Sym], classOf[Elem[_]]), @@ -1276,13 +639,6 @@ object Box extends EntityObject("Box") { ArraySeq.empty, true, false, element[(Int, Coll[Byte])])) } - - override def executeFromRegister[T](regId: Ref[Byte])(implicit cT: Elem[T]): Ref[T] = { - asRep[T](mkMethodCall(self, - BoxClass.getMethod("executeFromRegister", classOf[Sym], classOf[Elem[_]]), - Array[AnyRef](regId, cT), - true, false, element[T])) - } } implicit object LiftableBox @@ -1292,14 +648,9 @@ object Box extends EntityObject("Box") { RType[SBox] } def lift(x: SBox): Ref[Box] = BoxConst(x) - def unlift(w: Ref[Box]): SBox = w match { - case Def(BoxConst(x: SBox)) - => x.asInstanceOf[SBox] - case _ => unliftError(w) - } } - private val BoxClass = classOf[Box] + private val BoxClass = RClass(classOf[Box]) // entityAdapter for Box trait case class BoxAdapter(source: Ref[Box]) @@ -1343,13 +694,6 @@ object Box extends EntityObject("Box") { true, true, element[Coll[Byte]])) } - def registers: Ref[Coll[AnyValue]] = { - asRep[Coll[AnyValue]](mkMethodCall(source, - BoxClass.getMethod("registers"), - ArraySeq.empty, - true, true, element[Coll[AnyValue]])) - } - def getReg[T](i: Ref[Int])(implicit cT: Elem[T]): Ref[WOption[T]] = { asRep[WOption[T]](mkMethodCall(source, BoxClass.getMethod("getReg", classOf[Sym], classOf[Elem[_]]), @@ -1370,13 +714,6 @@ object Box extends EntityObject("Box") { ArraySeq.empty, true, true, element[(Int, Coll[Byte])])) } - - def executeFromRegister[T](regId: Ref[Byte])(implicit cT: Elem[T]): Ref[T] = { - asRep[T](mkMethodCall(source, - BoxClass.getMethod("executeFromRegister", classOf[Sym], classOf[Elem[_]]), - Array[AnyRef](regId, cT), - true, true, element[T])) - } } // entityUnref: single unref method for each type family @@ -1391,10 +728,10 @@ object Box extends EntityObject("Box") { extends EntityElem[To] { override val liftable: Liftables.Liftable[_, To] = asLiftable[SBox, To](LiftableBox) - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { + override protected def collectMethods: Map[RMethod, MethodDesc] = { super.collectMethods ++ - Elem.declaredMethods(classOf[Box], classOf[SBox], Set( - "id", "value", "propositionBytes", "bytes", "bytesWithoutRef", "registers", "getReg", "R0", "R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8", "R9", "tokens", "creationInfo", "executeFromRegister" + Elem.declaredMethods(RClass(classOf[Box]), RClass(classOf[SBox]), Set( + "id", "value", "propositionBytes", "bytes", "bytesWithoutRef", "registers", "getReg", "R0", "R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8", "R9", "tokens", "creationInfo" )) } } @@ -1402,19 +739,6 @@ object Box extends EntityObject("Box") { implicit lazy val boxElement: Elem[Box] = new BoxElem[Box] - implicit case object BoxCompanionElem extends CompanionElem[BoxCompanionCtor] - - abstract class BoxCompanionCtor extends CompanionDef[BoxCompanionCtor] with BoxCompanion { - def resultType = BoxCompanionElem - override def toString = "Box" - } - implicit final def unrefBoxCompanionCtor(p: Ref[BoxCompanionCtor]): BoxCompanionCtor = - p.node.asInstanceOf[BoxCompanionCtor] - - lazy val RBox: MutableLazy[BoxCompanionCtor] = MutableLazy(new BoxCompanionCtor { - private val thisClass = classOf[BoxCompanion] - }) - object BoxMethods { object id { def unapply(d: Def[_]): Nullable[Ref[Box]] = d match { @@ -1466,16 +790,6 @@ object Box extends EntityObject("Box") { def unapply(exp: Sym): Nullable[Ref[Box]] = unapply(exp.node) } - object registers { - def unapply(d: Def[_]): Nullable[Ref[Box]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "registers" && receiver.elem.isInstanceOf[BoxElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Box]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Box]] = unapply(exp.node) - } - object getReg { def unapply(d: Def[_]): Nullable[(Ref[Box], Ref[Int], Elem[T]) forSome {type T}] = d match { case MethodCall(receiver, method, args, _) if method.getName == "getReg" && receiver.elem.isInstanceOf[BoxElem[_]] => @@ -1486,116 +800,6 @@ object Box extends EntityObject("Box") { def unapply(exp: Sym): Nullable[(Ref[Box], Ref[Int], Elem[T]) forSome {type T}] = unapply(exp.node) } - object R0 { - def unapply(d: Def[_]): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "R0" && receiver.elem.isInstanceOf[BoxElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Box], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = unapply(exp.node) - } - - object R1 { - def unapply(d: Def[_]): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "R1" && receiver.elem.isInstanceOf[BoxElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Box], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = unapply(exp.node) - } - - object R2 { - def unapply(d: Def[_]): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "R2" && receiver.elem.isInstanceOf[BoxElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Box], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = unapply(exp.node) - } - - object R3 { - def unapply(d: Def[_]): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "R3" && receiver.elem.isInstanceOf[BoxElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Box], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = unapply(exp.node) - } - - object R4 { - def unapply(d: Def[_]): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "R4" && receiver.elem.isInstanceOf[BoxElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Box], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = unapply(exp.node) - } - - object R5 { - def unapply(d: Def[_]): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "R5" && receiver.elem.isInstanceOf[BoxElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Box], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = unapply(exp.node) - } - - object R6 { - def unapply(d: Def[_]): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "R6" && receiver.elem.isInstanceOf[BoxElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Box], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = unapply(exp.node) - } - - object R7 { - def unapply(d: Def[_]): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "R7" && receiver.elem.isInstanceOf[BoxElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Box], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = unapply(exp.node) - } - - object R8 { - def unapply(d: Def[_]): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "R8" && receiver.elem.isInstanceOf[BoxElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Box], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = unapply(exp.node) - } - - object R9 { - def unapply(d: Def[_]): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "R9" && receiver.elem.isInstanceOf[BoxElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Box], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Box], Elem[T]) forSome {type T}] = unapply(exp.node) - } - - object tokens { - def unapply(d: Def[_]): Nullable[Ref[Box]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "tokens" && receiver.elem.isInstanceOf[BoxElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Box]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Box]] = unapply(exp.node) - } - object creationInfo { def unapply(d: Def[_]): Nullable[Ref[Box]] = d match { case MethodCall(receiver, method, _, _) if method.getName == "creationInfo" && receiver.elem.isInstanceOf[BoxElem[_]] => @@ -1605,19 +809,6 @@ object Box extends EntityObject("Box") { } def unapply(exp: Sym): Nullable[Ref[Box]] = unapply(exp.node) } - - object executeFromRegister { - def unapply(d: Def[_]): Nullable[(Ref[Box], Ref[Byte], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "executeFromRegister" && receiver.elem.isInstanceOf[BoxElem[_]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[Box], Ref[Byte], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Box], Ref[Byte], Elem[T]) forSome {type T}] = unapply(exp.node) - } - } - - object BoxCompanionMethods { } } // of object Box registerEntityObject("Box", Box) @@ -1637,7 +828,7 @@ object AvlTree extends EntityObject("AvlTree") { trait AvlTreeConstMethods extends AvlTree { thisConst: Def[_] => - private val AvlTreeClass = classOf[AvlTree] + private val AvlTreeClass = RClass(classOf[AvlTree]) override def digest: Ref[Coll[Byte]] = { asRep[Coll[Byte]](mkMethodCall(self, @@ -1752,14 +943,9 @@ object AvlTree extends EntityObject("AvlTree") { RType[SAvlTree] } def lift(x: SAvlTree): Ref[AvlTree] = AvlTreeConst(x) - def unlift(w: Ref[AvlTree]): SAvlTree = w match { - case Def(AvlTreeConst(x: SAvlTree)) - => x.asInstanceOf[SAvlTree] - case _ => unliftError(w) - } } - private val AvlTreeClass = classOf[AvlTree] + private val AvlTreeClass = RClass(classOf[AvlTree]) // entityAdapter for AvlTree trait case class AvlTreeAdapter(source: Ref[AvlTree]) @@ -1886,9 +1072,9 @@ object AvlTree extends EntityObject("AvlTree") { extends EntityElem[To] { override val liftable: Liftables.Liftable[_, To] = asLiftable[SAvlTree, To](LiftableAvlTree) - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { + override protected def collectMethods: Map[RMethod, MethodDesc] = { super.collectMethods ++ - Elem.declaredMethods(classOf[AvlTree], classOf[SAvlTree], Set( + Elem.declaredMethods(RClass(classOf[AvlTree]), RClass(classOf[SAvlTree]), Set( "digest", "enabledOperations", "keyLength", "valueLengthOpt", "isInsertAllowed", "isUpdateAllowed", "isRemoveAllowed", "updateDigest", "updateOperations", "contains", "get", "getMany", "insert", "update", "remove" )) } @@ -1897,18 +1083,6 @@ object AvlTree extends EntityObject("AvlTree") { implicit lazy val avlTreeElement: Elem[AvlTree] = new AvlTreeElem[AvlTree] - implicit case object AvlTreeCompanionElem extends CompanionElem[AvlTreeCompanionCtor] - - abstract class AvlTreeCompanionCtor extends CompanionDef[AvlTreeCompanionCtor] with AvlTreeCompanion { - def resultType = AvlTreeCompanionElem - override def toString = "AvlTree" - } - implicit final def unrefAvlTreeCompanionCtor(p: Ref[AvlTreeCompanionCtor]): AvlTreeCompanionCtor = - p.node.asInstanceOf[AvlTreeCompanionCtor] - - lazy val RAvlTree: MutableLazy[AvlTreeCompanionCtor] = MutableLazy(new AvlTreeCompanionCtor { - private val thisClass = classOf[AvlTreeCompanion] - }) } // of object AvlTree registerEntityObject("AvlTree", AvlTree) @@ -1927,7 +1101,7 @@ object PreHeader extends EntityObject("PreHeader") { trait PreHeaderConstMethods extends PreHeader { thisConst: Def[_] => - private val PreHeaderClass = classOf[PreHeader] + private val PreHeaderClass = RClass(classOf[PreHeader]) override def version: Ref[Byte] = { asRep[Byte](mkMethodCall(self, @@ -1986,14 +1160,9 @@ object PreHeader extends EntityObject("PreHeader") { RType[SPreHeader] } def lift(x: SPreHeader): Ref[PreHeader] = PreHeaderConst(x) - def unlift(w: Ref[PreHeader]): SPreHeader = w match { - case Def(PreHeaderConst(x: SPreHeader)) - => x.asInstanceOf[SPreHeader] - case _ => unliftError(w) - } } - private val PreHeaderClass = classOf[PreHeader] + private val PreHeaderClass = RClass(classOf[PreHeader]) // entityAdapter for PreHeader trait case class PreHeaderAdapter(source: Ref[PreHeader]) @@ -2064,9 +1233,9 @@ object PreHeader extends EntityObject("PreHeader") { extends EntityElem[To] { override val liftable: Liftables.Liftable[_, To] = asLiftable[SPreHeader, To](LiftablePreHeader) - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { + override protected def collectMethods: Map[RMethod, MethodDesc] = { super.collectMethods ++ - Elem.declaredMethods(classOf[PreHeader], classOf[SPreHeader], Set( + Elem.declaredMethods(RClass(classOf[PreHeader]), RClass(classOf[SPreHeader]), Set( "version", "parentId", "timestamp", "nBits", "height", "minerPk", "votes" )) } @@ -2075,18 +1244,6 @@ object PreHeader extends EntityObject("PreHeader") { implicit lazy val preHeaderElement: Elem[PreHeader] = new PreHeaderElem[PreHeader] - implicit case object PreHeaderCompanionElem extends CompanionElem[PreHeaderCompanionCtor] - - abstract class PreHeaderCompanionCtor extends CompanionDef[PreHeaderCompanionCtor] with PreHeaderCompanion { - def resultType = PreHeaderCompanionElem - override def toString = "PreHeader" - } - implicit final def unrefPreHeaderCompanionCtor(p: Ref[PreHeaderCompanionCtor]): PreHeaderCompanionCtor = - p.node.asInstanceOf[PreHeaderCompanionCtor] - - lazy val RPreHeader: MutableLazy[PreHeaderCompanionCtor] = MutableLazy(new PreHeaderCompanionCtor { - private val thisClass = classOf[PreHeaderCompanion] - }) } // of object PreHeader registerEntityObject("PreHeader", PreHeader) @@ -2105,7 +1262,7 @@ object Header extends EntityObject("Header") { trait HeaderConstMethods extends Header { thisConst: Def[_] => - private val HeaderClass = classOf[Header] + private val HeaderClass = RClass(classOf[Header]) override def id: Ref[Coll[Byte]] = { asRep[Coll[Byte]](mkMethodCall(self, @@ -2220,14 +1377,9 @@ object Header extends EntityObject("Header") { RType[SHeader] } def lift(x: SHeader): Ref[Header] = HeaderConst(x) - def unlift(w: Ref[Header]): SHeader = w match { - case Def(HeaderConst(x: SHeader)) - => x.asInstanceOf[SHeader] - case _ => unliftError(w) - } } - private val HeaderClass = classOf[Header] + private val HeaderClass = RClass(classOf[Header]) // entityAdapter for Header trait case class HeaderAdapter(source: Ref[Header]) @@ -2354,9 +1506,9 @@ object Header extends EntityObject("Header") { extends EntityElem[To] { override val liftable: Liftables.Liftable[_, To] = asLiftable[SHeader, To](LiftableHeader) - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { + override protected def collectMethods: Map[RMethod, MethodDesc] = { super.collectMethods ++ - Elem.declaredMethods(classOf[Header], classOf[SHeader], Set( + Elem.declaredMethods(RClass(classOf[Header]), RClass(classOf[SHeader]), Set( "id", "version", "parentId", "ADProofsRoot", "stateRoot", "transactionsRoot", "timestamp", "nBits", "height", "extensionRoot", "minerPk", "powOnetimePk", "powNonce", "powDistance", "votes" )) } @@ -2365,18 +1517,6 @@ object Header extends EntityObject("Header") { implicit lazy val headerElement: Elem[Header] = new HeaderElem[Header] - implicit case object HeaderCompanionElem extends CompanionElem[HeaderCompanionCtor] - - abstract class HeaderCompanionCtor extends CompanionDef[HeaderCompanionCtor] with HeaderCompanion { - def resultType = HeaderCompanionElem - override def toString = "Header" - } - implicit final def unrefHeaderCompanionCtor(p: Ref[HeaderCompanionCtor]): HeaderCompanionCtor = - p.node.asInstanceOf[HeaderCompanionCtor] - - lazy val RHeader: MutableLazy[HeaderCompanionCtor] = MutableLazy(new HeaderCompanionCtor { - private val thisClass = classOf[HeaderCompanion] - }) } // of object Header registerEntityObject("Header", Header) @@ -2395,14 +1535,7 @@ object Context extends EntityObject("Context") { trait ContextConstMethods extends Context { thisConst: Def[_] => - private val ContextClass = classOf[Context] - - override def builder: Ref[SigmaDslBuilder] = { - asRep[SigmaDslBuilder](mkMethodCall(self, - ContextClass.getMethod("builder"), - ArraySeq.empty, - true, false, element[SigmaDslBuilder])) - } + private val ContextClass = RClass(classOf[Context]) override def OUTPUTS: Ref[Coll[Box]] = { asRep[Coll[Box]](mkMethodCall(self, @@ -2481,12 +1614,6 @@ object Context extends EntityObject("Context") { true, false, element[WOption[T]])) } - override def vars: Ref[Coll[AnyValue]] = { - asRep[Coll[AnyValue]](mkMethodCall(self, - ContextClass.getMethod("vars"), - ArraySeq.empty, - true, false, element[Coll[AnyValue]])) - } } implicit object LiftableContext @@ -2496,14 +1623,9 @@ object Context extends EntityObject("Context") { RType[SContext] } def lift(x: SContext): Ref[Context] = ContextConst(x) - def unlift(w: Ref[Context]): SContext = w match { - case Def(ContextConst(x: SContext)) - => x.asInstanceOf[SContext] - case _ => unliftError(w) - } } - private val ContextClass = classOf[Context] + private val ContextClass = RClass(classOf[Context]) // entityAdapter for Context trait case class ContextAdapter(source: Ref[Context]) @@ -2512,13 +1634,6 @@ object Context extends EntityObject("Context") { val resultType: Elem[Context] = element[Context] override def transform(t: Transformer) = ContextAdapter(t(source)) - def builder: Ref[SigmaDslBuilder] = { - asRep[SigmaDslBuilder](mkMethodCall(source, - ContextClass.getMethod("builder"), - ArraySeq.empty, - true, true, element[SigmaDslBuilder])) - } - def OUTPUTS: Ref[Coll[Box]] = { asRep[Coll[Box]](mkMethodCall(source, ContextClass.getMethod("OUTPUTS"), @@ -2595,13 +1710,6 @@ object Context extends EntityObject("Context") { Array[AnyRef](id, cT), true, true, element[WOption[T]])) } - - def vars: Ref[Coll[AnyValue]] = { - asRep[Coll[AnyValue]](mkMethodCall(source, - ContextClass.getMethod("vars"), - ArraySeq.empty, - true, true, element[Coll[AnyValue]])) - } } // entityUnref: single unref method for each type family @@ -2616,10 +1724,10 @@ object Context extends EntityObject("Context") { extends EntityElem[To] { override val liftable: Liftables.Liftable[_, To] = asLiftable[SContext, To](LiftableContext) - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { + override protected def collectMethods: Map[RMethod, MethodDesc] = { super.collectMethods ++ - Elem.declaredMethods(classOf[Context], classOf[SContext], Set( - "builder", "OUTPUTS", "INPUTS", "dataInputs", "HEIGHT", "SELF", "selfBoxIndex", "LastBlockUtxoRootHash", "headers", "preHeader", "minerPubKey", "getVar", "vars" + Elem.declaredMethods(RClass(classOf[Context]), RClass(classOf[SContext]), Set( + "OUTPUTS", "INPUTS", "dataInputs", "HEIGHT", "SELF", "selfBoxIndex", "LastBlockUtxoRootHash", "headers", "preHeader", "minerPubKey", "getVar", "vars" )) } } @@ -2627,30 +1735,7 @@ object Context extends EntityObject("Context") { implicit lazy val contextElement: Elem[Context] = new ContextElem[Context] - implicit case object ContextCompanionElem extends CompanionElem[ContextCompanionCtor] - - abstract class ContextCompanionCtor extends CompanionDef[ContextCompanionCtor] with ContextCompanion { - def resultType = ContextCompanionElem - override def toString = "Context" - } - implicit final def unrefContextCompanionCtor(p: Ref[ContextCompanionCtor]): ContextCompanionCtor = - p.node.asInstanceOf[ContextCompanionCtor] - - lazy val RContext: MutableLazy[ContextCompanionCtor] = MutableLazy(new ContextCompanionCtor { - private val thisClass = classOf[ContextCompanion] - }) - object ContextMethods { - object builder { - def unapply(d: Def[_]): Nullable[Ref[Context]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "builder" && receiver.elem.isInstanceOf[ContextElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Context]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Context]] = unapply(exp.node) - } - object OUTPUTS { def unapply(d: Def[_]): Nullable[Ref[Context]] = d match { case MethodCall(receiver, method, _, _) if method.getName == "OUTPUTS" && receiver.elem.isInstanceOf[ContextElem[_]] => @@ -2671,16 +1756,6 @@ object Context extends EntityObject("Context") { def unapply(exp: Sym): Nullable[Ref[Context]] = unapply(exp.node) } - object dataInputs { - def unapply(d: Def[_]): Nullable[Ref[Context]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "dataInputs" && receiver.elem.isInstanceOf[ContextElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Context]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Context]] = unapply(exp.node) - } - object HEIGHT { def unapply(d: Def[_]): Nullable[Ref[Context]] = d match { case MethodCall(receiver, method, _, _) if method.getName == "HEIGHT" && receiver.elem.isInstanceOf[ContextElem[_]] => @@ -2701,56 +1776,6 @@ object Context extends EntityObject("Context") { def unapply(exp: Sym): Nullable[Ref[Context]] = unapply(exp.node) } - object selfBoxIndex { - def unapply(d: Def[_]): Nullable[Ref[Context]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "selfBoxIndex" && receiver.elem.isInstanceOf[ContextElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Context]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Context]] = unapply(exp.node) - } - - object LastBlockUtxoRootHash { - def unapply(d: Def[_]): Nullable[Ref[Context]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "LastBlockUtxoRootHash" && receiver.elem.isInstanceOf[ContextElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Context]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Context]] = unapply(exp.node) - } - - object headers { - def unapply(d: Def[_]): Nullable[Ref[Context]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "headers" && receiver.elem.isInstanceOf[ContextElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Context]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Context]] = unapply(exp.node) - } - - object preHeader { - def unapply(d: Def[_]): Nullable[Ref[Context]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "preHeader" && receiver.elem.isInstanceOf[ContextElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Context]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Context]] = unapply(exp.node) - } - - object minerPubKey { - def unapply(d: Def[_]): Nullable[Ref[Context]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "minerPubKey" && receiver.elem.isInstanceOf[ContextElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Context]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Context]] = unapply(exp.node) - } - object getVar { def unapply(d: Def[_]): Nullable[(Ref[Context], Ref[Byte], Elem[T]) forSome {type T}] = d match { case MethodCall(receiver, method, args, _) if method.getName == "getVar" && receiver.elem.isInstanceOf[ContextElem[_]] => @@ -2760,19 +1785,6 @@ object Context extends EntityObject("Context") { } def unapply(exp: Sym): Nullable[(Ref[Context], Ref[Byte], Elem[T]) forSome {type T}] = unapply(exp.node) } - - object vars { - def unapply(d: Def[_]): Nullable[Ref[Context]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "vars" && receiver.elem.isInstanceOf[ContextElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Context]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Context]] = unapply(exp.node) - } - } - - object ContextCompanionMethods { } } // of object Context registerEntityObject("Context", Context) @@ -2792,7 +1804,7 @@ object SigmaDslBuilder extends EntityObject("SigmaDslBuilder") { trait SigmaDslBuilderConstMethods extends SigmaDslBuilder { thisConst: Def[_] => - private val SigmaDslBuilderClass = classOf[SigmaDslBuilder] + private val SigmaDslBuilderClass = RClass(classOf[SigmaDslBuilder]) override def Colls: Ref[CollBuilder] = { asRep[CollBuilder](mkMethodCall(self, @@ -2801,13 +1813,6 @@ object SigmaDslBuilder extends EntityObject("SigmaDslBuilder") { true, false, element[CollBuilder])) } - override def verifyZK(cond: Ref[Thunk[SigmaProp]]): Ref[Boolean] = { - asRep[Boolean](mkMethodCall(self, - SigmaDslBuilderClass.getMethod("verifyZK", classOf[Sym]), - Array[AnyRef](cond), - true, false, element[Boolean])) - } - override def atLeast(bound: Ref[Int], props: Ref[Coll[SigmaProp]]): Ref[SigmaProp] = { asRep[SigmaProp](mkMethodCall(self, SigmaDslBuilderClass.getMethod("atLeast", classOf[Sym], classOf[Sym]), @@ -2950,14 +1955,9 @@ object SigmaDslBuilder extends EntityObject("SigmaDslBuilder") { RType[SSigmaDslBuilder] } def lift(x: SSigmaDslBuilder): Ref[SigmaDslBuilder] = SigmaDslBuilderConst(x) - def unlift(w: Ref[SigmaDslBuilder]): SSigmaDslBuilder = w match { - case Def(SigmaDslBuilderConst(x: SSigmaDslBuilder)) - => x.asInstanceOf[SSigmaDslBuilder] - case _ => unliftError(w) - } } - private val SigmaDslBuilderClass = classOf[SigmaDslBuilder] + private val SigmaDslBuilderClass = RClass(classOf[SigmaDslBuilder]) // entityAdapter for SigmaDslBuilder trait case class SigmaDslBuilderAdapter(source: Ref[SigmaDslBuilder]) @@ -2973,13 +1973,6 @@ object SigmaDslBuilder extends EntityObject("SigmaDslBuilder") { true, true, element[CollBuilder])) } - def verifyZK(cond: Ref[Thunk[SigmaProp]]): Ref[Boolean] = { - asRep[Boolean](mkMethodCall(source, - SigmaDslBuilderClass.getMethod("verifyZK", classOf[Sym]), - Array[AnyRef](cond), - true, true, element[Boolean])) - } - def atLeast(bound: Ref[Int], props: Ref[Coll[SigmaProp]]): Ref[SigmaProp] = { asRep[SigmaProp](mkMethodCall(source, SigmaDslBuilderClass.getMethod("atLeast", classOf[Sym], classOf[Sym]), @@ -3127,9 +2120,9 @@ object SigmaDslBuilder extends EntityObject("SigmaDslBuilder") { extends EntityElem[To] { override val liftable: Liftables.Liftable[_, To] = asLiftable[SSigmaDslBuilder, To](LiftableSigmaDslBuilder) - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { + override protected def collectMethods: Map[RMethod, MethodDesc] = { super.collectMethods ++ - Elem.declaredMethods(classOf[SigmaDslBuilder], classOf[SSigmaDslBuilder], Set( + Elem.declaredMethods(RClass(classOf[SigmaDslBuilder]), RClass(classOf[SSigmaDslBuilder]), Set( "Colls", "verifyZK", "atLeast", "allOf", "allZK", "anyOf", "anyZK", "xorOf", "sigmaProp", "blake2b256", "sha256", "byteArrayToBigInt", "longToByteArray", "byteArrayToLong", "proveDlog", "proveDHTuple", "groupGenerator", "substConstants", "decodePoint", "avlTree", "xor" )) } @@ -3138,19 +2131,6 @@ object SigmaDslBuilder extends EntityObject("SigmaDslBuilder") { implicit lazy val sigmaDslBuilderElement: Elem[SigmaDslBuilder] = new SigmaDslBuilderElem[SigmaDslBuilder] - implicit case object SigmaDslBuilderCompanionElem extends CompanionElem[SigmaDslBuilderCompanionCtor] - - abstract class SigmaDslBuilderCompanionCtor extends CompanionDef[SigmaDslBuilderCompanionCtor] with SigmaDslBuilderCompanion { - def resultType = SigmaDslBuilderCompanionElem - override def toString = "SigmaDslBuilder" - } - implicit final def unrefSigmaDslBuilderCompanionCtor(p: Ref[SigmaDslBuilderCompanionCtor]): SigmaDslBuilderCompanionCtor = - p.node.asInstanceOf[SigmaDslBuilderCompanionCtor] - - lazy val RSigmaDslBuilder: MutableLazy[SigmaDslBuilderCompanionCtor] = MutableLazy(new SigmaDslBuilderCompanionCtor { - private val thisClass = classOf[SigmaDslBuilderCompanion] - }) - object SigmaDslBuilderMethods { object Colls { def unapply(d: Def[_]): Nullable[Ref[SigmaDslBuilder]] = d match { @@ -3162,16 +2142,6 @@ object SigmaDslBuilder extends EntityObject("SigmaDslBuilder") { def unapply(exp: Sym): Nullable[Ref[SigmaDslBuilder]] = unapply(exp.node) } - object verifyZK { - def unapply(d: Def[_]): Nullable[(Ref[SigmaDslBuilder], Ref[Thunk[SigmaProp]])] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "verifyZK" && receiver.elem.isInstanceOf[SigmaDslBuilderElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[SigmaDslBuilder], Ref[Thunk[SigmaProp]])]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[SigmaDslBuilder], Ref[Thunk[SigmaProp]])] = unapply(exp.node) - } - object atLeast { def unapply(d: Def[_]): Nullable[(Ref[SigmaDslBuilder], Ref[Int], Ref[Coll[SigmaProp]])] = d match { case MethodCall(receiver, method, args, _) if method.getName == "atLeast" && receiver.elem.isInstanceOf[SigmaDslBuilderElem[_]] => @@ -3342,6 +2312,7 @@ object SigmaDslBuilder extends EntityObject("SigmaDslBuilder") { def unapply(exp: Sym): Nullable[(Ref[SigmaDslBuilder], Ref[Coll[Byte]])] = unapply(exp.node) } + /** This is necessary to handle CreateAvlTree in GraphBuilding (v6.0) */ object avlTree { def unapply(d: Def[_]): Nullable[(Ref[SigmaDslBuilder], Ref[Byte], Ref[Coll[Byte]], Ref[Int], Ref[WOption[Int]])] = d match { case MethodCall(receiver, method, args, _) if method.getName == "avlTree" && receiver.elem.isInstanceOf[SigmaDslBuilderElem[_]] => @@ -3362,26 +2333,9 @@ object SigmaDslBuilder extends EntityObject("SigmaDslBuilder") { def unapply(exp: Sym): Nullable[(Ref[SigmaDslBuilder], Ref[Coll[Byte]], Ref[Coll[Byte]])] = unapply(exp.node) } } - - object SigmaDslBuilderCompanionMethods { - } } // of object SigmaDslBuilder registerEntityObject("SigmaDslBuilder", SigmaDslBuilder) - override def resetContext(): Unit = { - super.resetContext() - RBigInt.reset() - RGroupElement.reset() - RSigmaProp.reset() - RAnyValue.reset() - RBox.reset() - RAvlTree.reset() - RPreHeader.reset() - RHeader.reset() - RContext.reset() - RSigmaDslBuilder.reset() - } - registerModule(SigmaDslModule) } diff --git a/sigma-library/src/main/scala/special/sigma/wrappers/WrappersModule.scala b/graph-ir/src/main/scala/special/sigma/wrappers/WrappersModule.scala similarity index 100% rename from sigma-library/src/main/scala/special/sigma/wrappers/WrappersModule.scala rename to graph-ir/src/main/scala/special/sigma/wrappers/WrappersModule.scala diff --git a/library/src/main/scala/special/wrappers/WrappersModule.scala b/graph-ir/src/main/scala/special/wrappers/WrappersModule.scala similarity index 100% rename from library/src/main/scala/special/wrappers/WrappersModule.scala rename to graph-ir/src/main/scala/special/wrappers/WrappersModule.scala diff --git a/library/src/main/scala/wrappers/scala/WOptions.scala b/graph-ir/src/main/scala/wrappers/scala/WOptions.scala similarity index 68% rename from library/src/main/scala/wrappers/scala/WOptions.scala rename to graph-ir/src/main/scala/wrappers/scala/WOptions.scala index 34c7a26035..4bd314c1de 100644 --- a/library/src/main/scala/wrappers/scala/WOptions.scala +++ b/graph-ir/src/main/scala/wrappers/scala/WOptions.scala @@ -6,15 +6,11 @@ package wrappers.scala { trait WOptions extends Base { self: WrappersModule => trait WOption[A] extends Def[WOption[A]] { implicit def eA: Elem[A]; - def fold[B](ifEmpty: Ref[Thunk[B]], f: Ref[scala.Function1[A, B]]): Ref[B]; - def isEmpty: Ref[Boolean]; def isDefined: Ref[Boolean]; def filter(p: Ref[scala.Function1[A, Boolean]]): Ref[WOption[A]]; - def flatMap[B](f: Ref[scala.Function1[A, WOption[B]]]): Ref[WOption[B]]; def map[B](f: Ref[scala.Function1[A, B]]): Ref[WOption[B]]; def getOrElse[B](default: Ref[Thunk[B]]): Ref[B]; def get: Ref[A] }; - trait WOptionCompanion } } \ No newline at end of file diff --git a/library/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala b/graph-ir/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala similarity index 62% rename from library/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala rename to graph-ir/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala index c4ea9b91b3..9b5cdb595b 100644 --- a/library/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala +++ b/graph-ir/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala @@ -7,11 +7,13 @@ import special.wrappers.OptionWrapSpec import scala.collection.compat.immutable.ArraySeq package impl { -// Abs ----------------------------------- + import scalan.reflection.{RClass, RMethod} + + // Abs ----------------------------------- trait WOptionsDefs extends scalan.Scalan with WOptions { self: WrappersModule => -object WOption extends EntityObject("WOption") { +class WOptionCls extends EntityObject("WOption") { // entityConst: single const for each entity import Liftables._ @@ -28,22 +30,7 @@ object WOption extends EntityObject("WOption") { trait WOptionConstMethods[A] extends WOption[A] { thisConst: Def[_] => implicit def eA: Elem[A] - private val WOptionClass = classOf[WOption[A]] - - override def fold[B](ifEmpty: Ref[Thunk[B]], f: Ref[A => B]): Ref[B] = { - implicit val eB = ifEmpty.elem.eItem - asRep[B](mkMethodCall(self, - WOptionClass.getMethod("fold", classOf[Sym], classOf[Sym]), - Array[AnyRef](ifEmpty, f), - true, false, element[B])) - } - - override def isEmpty: Ref[Boolean] = { - asRep[Boolean](mkMethodCall(self, - WOptionClass.getMethod("isEmpty"), - ArraySeq.empty, - true, false, element[Boolean])) - } + private val WOptionClass = RClass(classOf[WOption[A]]) override def isDefined: Ref[Boolean] = { asRep[Boolean](mkMethodCall(self, @@ -59,14 +46,6 @@ object WOption extends EntityObject("WOption") { true, false, element[WOption[A]])) } - override def flatMap[B](f: Ref[A => WOption[B]]): Ref[WOption[B]] = { - implicit val eB = f.elem.eRange.typeArgs("A")._1.asInstanceOf[Elem[B]] - asRep[WOption[B]](mkMethodCall(self, - WOptionClass.getMethod("flatMap", classOf[Sym]), - Array[AnyRef](f), - true, false, element[WOption[B]])) - } - override def map[B](f: Ref[A => B]): Ref[WOption[B]] = { implicit val eB = f.elem.eRange asRep[WOption[B]](mkMethodCall(self, @@ -95,22 +74,17 @@ object WOption extends EntityObject("WOption") { extends Liftable[Option[SA], WOption[A]] { lazy val eW: Elem[WOption[A]] = wOptionElement(lA.eW) lazy val sourceType: RType[Option[SA]] = { - implicit val tagSA = lA.sourceType.asInstanceOf[RType[SA]] + implicit val tagSA = lA.sourceType.asInstanceOf[RType[SA]] RType[Option[SA]] } def lift(x: Option[SA]): Ref[WOption[A]] = WOptionConst(x, lA) - def unlift(w: Ref[WOption[A]]): Option[SA] = w match { - case Def(WOptionConst(x: Option[_], _lA)) - if _lA == lA => x.asInstanceOf[Option[SA]] - case _ => unliftError(w) - } } implicit final def liftableOption[SA, A](implicit lA: Liftable[SA,A]): Liftable[Option[SA], WOption[A]] = LiftableOption(lA) - private val _OptionWrapSpec = new OptionWrapSpec {} + private val _OptionWrapSpec = new OptionWrapSpec - private val WOptionClass = classOf[WOption[_]] + private val WOptionClass = RClass(classOf[WOption[_]]) // entityAdapter for WOption trait case class WOptionAdapter[A](source: Ref[WOption[A]]) @@ -121,21 +95,6 @@ object WOption extends EntityObject("WOption") { val resultType: Elem[WOption[A]] = element[WOption[A]] override def transform(t: Transformer) = WOptionAdapter[A](t(source)) - def fold[B](ifEmpty: Ref[Thunk[B]], f: Ref[A => B]): Ref[B] = { - implicit val eB = ifEmpty.elem.eItem - asRep[B](mkMethodCall(source, - WOptionClass.getMethod("fold", classOf[Sym], classOf[Sym]), - Array[AnyRef](ifEmpty, f), - true, true, element[B])) - } - - def isEmpty: Ref[Boolean] = { - asRep[Boolean](mkMethodCall(source, - WOptionClass.getMethod("isEmpty"), - ArraySeq.empty, - true, true, element[Boolean])) - } - def isDefined: Ref[Boolean] = { asRep[Boolean](mkMethodCall(source, WOptionClass.getMethod("isDefined"), @@ -150,14 +109,6 @@ object WOption extends EntityObject("WOption") { true, true, element[WOption[A]])) } - def flatMap[B](f: Ref[A => WOption[B]]): Ref[WOption[B]] = { - implicit val eB = f.elem.eRange.typeArgs("A")._1.asInstanceOf[Elem[B]] - asRep[WOption[B]](mkMethodCall(source, - WOptionClass.getMethod("flatMap", classOf[Sym]), - Array[AnyRef](f), - true, true, element[WOption[B]])) - } - def map[B](f: Ref[A => B]): Ref[WOption[B]] = { implicit val eB = f.elem.eRange asRep[WOption[B]](mkMethodCall(source, @@ -203,8 +154,6 @@ object WOption extends EntityObject("WOption") { def map[A,B](xs: Ref[WOption[A]])(f: Ref[A] => Ref[B]) = { implicit val eA = unlift(xs.elem); xs.map(fun(f))} } - // manual fix: WOptionIso, wOptionIso - // familyElem class WOptionElem[A, To <: WOption[A]](implicit _eA: Elem[A]) extends EntityElem1[A, To, WOption](_eA, container[WOption]) { @@ -212,10 +161,10 @@ object WOption extends EntityObject("WOption") { override val liftable: Liftables.Liftable[_, To] = asLiftable[Option[_], To](liftableOption(_eA.liftable)) - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { + override protected def collectMethods: Map[RMethod, MethodDesc] = { super.collectMethods ++ - Elem.declaredWrapperMethods(_OptionWrapSpec, classOf[WOption[A]], Set( - "fold", "isEmpty", "isDefined", "filter", "flatMap", "map", "getOrElse", "get" + Elem.declaredWrapperMethods(_OptionWrapSpec, RClass(classOf[WOption[A]]), Set( + "isDefined", "filter", "map", "getOrElse", "get" )) } @@ -223,44 +172,9 @@ object WOption extends EntityObject("WOption") { } implicit final def wOptionElement[A](implicit eA: Elem[A]): Elem[WOption[A]] = - cachedElemByClass(eA)(classOf[WOptionElem[A, WOption[A]]]) - - implicit case object WOptionCompanionElem extends CompanionElem[WOptionCompanionCtor] - - abstract class WOptionCompanionCtor extends CompanionDef[WOptionCompanionCtor] with WOptionCompanion { - def resultType = WOptionCompanionElem - override def toString = "WOption" - } - implicit final def unrefWOptionCompanionCtor(p: Ref[WOptionCompanionCtor]): WOptionCompanionCtor = - p.node.asInstanceOf[WOptionCompanionCtor] - - lazy val RWOption: MutableLazy[WOptionCompanionCtor] = MutableLazy(new WOptionCompanionCtor { - private val thisClass = classOf[WOptionCompanion] - }) - - // manual fix: ViewWOption + cachedElemByClass(eA)(RClass(classOf[WOptionElem[A, WOption[A]]])) object WOptionMethods { - object fold { - def unapply(d: Def[_]): Nullable[(Ref[WOption[A]], Ref[Thunk[B]], Ref[A => B]) forSome {type A; type B}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "fold" && receiver.elem.isInstanceOf[WOptionElem[_, _]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[WOption[A]], Ref[Thunk[B]], Ref[A => B]) forSome {type A; type B}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[WOption[A]], Ref[Thunk[B]], Ref[A => B]) forSome {type A; type B}] = unapply(exp.node) - } - - object isEmpty { - def unapply(d: Def[_]): Nullable[Ref[WOption[A]] forSome {type A}] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "isEmpty" && receiver.elem.isInstanceOf[WOptionElem[_, _]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[WOption[A]] forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[WOption[A]] forSome {type A}] = unapply(exp.node) - } - object isDefined { def unapply(d: Def[_]): Nullable[Ref[WOption[A]] forSome {type A}] = d match { case MethodCall(receiver, method, _, _) if method.getName == "isDefined" && receiver.elem.isInstanceOf[WOptionElem[_, _]] => @@ -281,16 +195,6 @@ object WOption extends EntityObject("WOption") { def unapply(exp: Sym): Nullable[(Ref[WOption[A]], Ref[A => Boolean]) forSome {type A}] = unapply(exp.node) } - object flatMap { - def unapply(d: Def[_]): Nullable[(Ref[WOption[A]], Ref[A => WOption[B]]) forSome {type A; type B}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "flatMap" && receiver.elem.isInstanceOf[WOptionElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[WOption[A]], Ref[A => WOption[B]]) forSome {type A; type B}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[WOption[A]], Ref[A => WOption[B]]) forSome {type A; type B}] = unapply(exp.node) - } - object map { def unapply(d: Def[_]): Nullable[(Ref[WOption[A]], Ref[A => B]) forSome {type A; type B}] = d match { case MethodCall(receiver, method, args, _) if method.getName == "map" && receiver.elem.isInstanceOf[WOptionElem[_, _]] => @@ -321,21 +225,15 @@ object WOption extends EntityObject("WOption") { def unapply(exp: Sym): Nullable[Ref[WOption[A]] forSome {type A}] = unapply(exp.node) } } - - object WOptionCompanionMethods { - } } // of object WOption - registerEntityObject("WOption", WOption) - - // manual fix: UserTypeWOption removed - // manual fix: unapplyViews removed - // manual fix: RepWOption removed - // manual fix: rewriteDef removed - +object WOption extends WOptionCls registerModule(WOptionsModule) + registerEntityObject("WOption", WOption) } -object WOptionsModule extends scalan.ModuleInfo("wrappers.scala", "WOptions") +object WOptionsModule extends scalan.ModuleInfo("wrappers.scala", "WOptions") { + val reflection = GraphIRReflection +} } trait WOptionsModule extends wrappers.scala.impl.WOptionsDefs {self: WrappersModule =>} diff --git a/library/src/main/scala/wrappers/scalan/WRTypes.scala b/graph-ir/src/main/scala/wrappers/scalan/WRTypes.scala similarity index 100% rename from library/src/main/scala/wrappers/scalan/WRTypes.scala rename to graph-ir/src/main/scala/wrappers/scalan/WRTypes.scala diff --git a/library/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala b/graph-ir/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala similarity index 60% rename from library/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala rename to graph-ir/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala index 6e94bffded..4a85b46661 100644 --- a/library/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala +++ b/graph-ir/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala @@ -1,19 +1,23 @@ package wrappers.scalan import scala.language.{existentials,implicitConversions} -import scalan._ import scalan.RType import special.wrappers.WrappersModule import special.wrappers.RTypeWrapSpec import scala.collection.compat.immutable.ArraySeq package impl { -// Abs ----------------------------------- + import scalan.reflection.{RClass, RMethod} + + // Abs ----------------------------------- trait WRTypesDefs extends scalan.Scalan with WRTypes { self: WrappersModule => -import WRType._ -object WRType extends EntityObject("WRType") { +/** IR implementation for RType methods. + * Prefix `W` means that this is implementation of IR wrapper over RType. + * @see [[EntityObject]], [[WRType]] + */ +class WRTypeCls extends EntityObject("WRType") { // entityConst: single const for each entity import Liftables._ @@ -30,7 +34,7 @@ object WRType extends EntityObject("WRType") { trait WRTypeConstMethods[A] extends WRType[A] { thisConst: Def[_] => implicit def eA: Elem[A] - private val WRTypeClass = classOf[WRType[A]] + private val WRTypeClass = RClass(classOf[WRType[A]]) override def name: Ref[String] = { asRep[String](mkMethodCall(self, @@ -48,18 +52,13 @@ object WRType extends EntityObject("WRType") { RType[RType[SA]] } def lift(x: RType[SA]): Ref[WRType[A]] = WRTypeConst(x, lA) - def unlift(w: Ref[WRType[A]]): RType[SA] = w match { - case Def(WRTypeConst(x: RType[_], _lA)) - if _lA == lA => x.asInstanceOf[RType[SA]] - case _ => unliftError(w) - } } implicit final def liftableRType[SA, A](implicit lA: Liftable[SA,A]): Liftable[RType[SA], WRType[A]] = LiftableRType(lA) - private val _RTypeWrapSpec = new RTypeWrapSpec {} + private val _RTypeWrapSpec = new RTypeWrapSpec - private val WRTypeClass = classOf[WRType[_]] + private val WRTypeClass = RClass(classOf[WRType[_]]) // entityAdapter for WRType trait case class WRTypeAdapter[A](source: Ref[WRType[A]]) @@ -92,55 +91,22 @@ object WRType extends EntityObject("WRType") { override val liftable: Liftables.Liftable[_, To] = asLiftable[RType[_], To](liftableRType(_eA.liftable)) - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { + override protected def collectMethods: Map[RMethod, MethodDesc] = { super.collectMethods ++ - Elem.declaredWrapperMethods(_RTypeWrapSpec, classOf[WRType[A]], Set( - "name" - )) + Elem.declaredWrapperMethods(_RTypeWrapSpec, RClass(classOf[WRType[A]]), Set("name")) } override def buildTypeArgs = super.buildTypeArgs ++ TypeArgs("A" -> (eA -> scalan.util.Invariant)) } implicit final def wRTypeElement[A](implicit eA: Elem[A]): Elem[WRType[A]] = - cachedElemByClass(eA)(classOf[WRTypeElem[A, WRType[A]]]) - - implicit case object WRTypeCompanionElem extends CompanionElem[WRTypeCompanionCtor] - - abstract class WRTypeCompanionCtor extends CompanionDef[WRTypeCompanionCtor] with WRTypeCompanion { - def resultType = WRTypeCompanionElem - override def toString = "WRType" - } - implicit final def unrefWRTypeCompanionCtor(p: Ref[WRTypeCompanionCtor]): WRTypeCompanionCtor = - p.node.asInstanceOf[WRTypeCompanionCtor] - - lazy val RWRType: MutableLazy[WRTypeCompanionCtor] = MutableLazy(new WRTypeCompanionCtor { - private val thisClass = classOf[WRTypeCompanion] - }) - - object WRTypeMethods { - object name { - def unapply(d: Def[_]): Nullable[Ref[WRType[A]] forSome {type A}] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "name" && receiver.elem.isInstanceOf[WRTypeElem[_, _]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[WRType[A]] forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[WRType[A]] forSome {type A}] = unapply(exp.node) - } - } + cachedElemByClass(eA)(RClass(classOf[WRTypeElem[A, WRType[A]]])) - object WRTypeCompanionMethods { - } } // of object WRType - registerEntityObject("WRType", WRType) - - override def resetContext(): Unit = { - super.resetContext() - RWRType.reset() - } +object WRType extends WRTypeCls +registerEntityObject("WRType", WRType) - registerModule(WRTypesModule) +registerModule(WRTypesModule) } object WRTypesModule extends scalan.ModuleInfo("wrappers.scalan", "WRTypes") diff --git a/library/src/main/scala/wrappers/special/WSpecialPredefs.scala b/graph-ir/src/main/scala/wrappers/special/WSpecialPredefs.scala similarity index 51% rename from library/src/main/scala/wrappers/special/WSpecialPredefs.scala rename to graph-ir/src/main/scala/wrappers/special/WSpecialPredefs.scala index 6a5731fa06..42bbbb4373 100644 --- a/library/src/main/scala/wrappers/special/WSpecialPredefs.scala +++ b/graph-ir/src/main/scala/wrappers/special/WSpecialPredefs.scala @@ -8,11 +8,7 @@ package wrappers.special { import WSpecialPredef._; trait WSpecialPredef extends Def[WSpecialPredef]; trait WSpecialPredefCompanion { - def optionGetOrElse[A](opt: Ref[WOption[A]], default: Ref[A]): Ref[A]; - def none[A](implicit emA: Elem[A]): Ref[WOption[A]]; def some[A](x: Ref[A]): Ref[WOption[A]]; - def cast[T](v: Ref[Any])(implicit emT: Elem[T]): Ref[WOption[T]]; - def loopUntil[A](s1: Ref[A], isMatch: Ref[scala.Function1[A, Boolean]], step: Ref[scala.Function1[A, A]]): Ref[A] } } } \ No newline at end of file diff --git a/graph-ir/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala b/graph-ir/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala new file mode 100644 index 0000000000..8803bc332e --- /dev/null +++ b/graph-ir/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala @@ -0,0 +1,64 @@ +package wrappers.special + +import scala.language.{existentials,implicitConversions} +import scalan._ +import special.wrappers.WrappersModule + +package impl { + import scalan.reflection.RClass + + // Abs ----------------------------------- +trait WSpecialPredefsDefs extends scalan.Scalan with WSpecialPredefs { + self: WrappersModule => +import WOption._ +import WSpecialPredef._ + +object WSpecialPredef extends EntityObject("WSpecialPredef") { + + implicit case object WSpecialPredefCompanionElem extends CompanionElem[WSpecialPredefCompanionCtor] + + abstract class WSpecialPredefCompanionCtor extends CompanionDef[WSpecialPredefCompanionCtor] with WSpecialPredefCompanion { + def resultType = WSpecialPredefCompanionElem + override def toString = "WSpecialPredef" + } + implicit final def unrefWSpecialPredefCompanionCtor(p: Ref[WSpecialPredefCompanionCtor]): WSpecialPredefCompanionCtor = + p.node.asInstanceOf[WSpecialPredefCompanionCtor] + + lazy val RWSpecialPredef: MutableLazy[WSpecialPredefCompanionCtor] = MutableLazy(new WSpecialPredefCompanionCtor { + private val thisClass = RClass(classOf[WSpecialPredefCompanion]) + + def some[A](x: Ref[A]): Ref[WOption[A]] = { + implicit val eA = x.elem + asRep[WOption[A]](mkMethodCall(self, + thisClass.getMethod("some", classOf[Sym]), + Array[AnyRef](x), + true, false, element[WOption[A]])) + } + }) + + object WSpecialPredefCompanionMethods { + object some { + def unapply(d: Def[_]): Nullable[Ref[A] forSome {type A}] = d match { + case MethodCall(receiver, method, args, _) if method.getName == "some" && receiver.elem == WSpecialPredefCompanionElem => + val res = args(0) + Nullable(res).asInstanceOf[Nullable[Ref[A] forSome {type A}]] + case _ => Nullable.None + } + def unapply(exp: Sym): Nullable[Ref[A] forSome {type A}] = unapply(exp.node) + } + } +} // of object WSpecialPredef + registerEntityObject("WSpecialPredef", WSpecialPredef) + + override def resetContext(): Unit = { + super.resetContext() + RWSpecialPredef.reset() + } + + registerModule(WSpecialPredefsModule) +} + +object WSpecialPredefsModule extends scalan.ModuleInfo("wrappers.special", "WSpecialPredefs") +} + +trait WSpecialPredefsModule extends wrappers.special.impl.WSpecialPredefsDefs {self: WrappersModule =>} diff --git a/core/src/test/scala/scalan/BaseLiftableTests.scala b/graph-ir/src/test/scala/scalan/BaseLiftableTests.scala similarity index 100% rename from core/src/test/scala/scalan/BaseLiftableTests.scala rename to graph-ir/src/test/scala/scalan/BaseLiftableTests.scala diff --git a/library/src/test/scala/scalan/LibraryTests.scala b/graph-ir/src/test/scala/scalan/LibraryTests.scala similarity index 69% rename from library/src/test/scala/scalan/LibraryTests.scala rename to graph-ir/src/test/scala/scalan/LibraryTests.scala index 4714085ec7..3c3982430c 100644 --- a/library/src/test/scala/scalan/LibraryTests.scala +++ b/graph-ir/src/test/scala/scalan/LibraryTests.scala @@ -3,15 +3,17 @@ package scalan import scalan.util.BenchmarkUtil._ class Benchmark[T <: Scalan](createContext: => T) { + val printDebugInfo: Boolean = false + def run() = { val (ctx, total) = measureTime { var ctx = createContext - measure(100000, false) { i => + measure(100000, okShowIterTime = printDebugInfo, okShowTotalTime = printDebugInfo) { i => ctx = createContext } ctx } - println(s"Def count: ${ctx.defCount}, total: $total msec") + if (printDebugInfo) println(s"Def count: ${ctx.defCount}, total: $total msec") /*Total time: 9335 ms*/ } } diff --git a/core/src/test/scala/scalan/TestContexts.scala b/graph-ir/src/test/scala/scalan/TestContexts.scala similarity index 66% rename from core/src/test/scala/scalan/TestContexts.scala rename to graph-ir/src/test/scala/scalan/TestContexts.scala index 3d89f76c1a..f2a9291d5e 100644 --- a/core/src/test/scala/scalan/TestContexts.scala +++ b/graph-ir/src/test/scala/scalan/TestContexts.scala @@ -1,20 +1,21 @@ package scalan -import java.lang.reflect.Method - -import scalan.compilation.GraphVizConfig +import scalan.compilation.GraphVizExport +import scalan.reflection.RMethod import scalan.util.FileUtil +import special.CoreLibReflection trait TestContexts extends TestUtils { - protected[this] def stage(scalan: Scalan)(testName: String, name: String, sfs: Seq[() => scalan.Sym]): Unit = { + protected[this] def stage[Ctx <: Scalan](scalan: Ctx)(testName: String, name: String, sfs: Seq[() => scalan.Sym]): Unit = { val directory = FileUtil.file(prefix, testName) - implicit val graphVizConfig = scalan.defaultGraphVizConfig + val gv = new GraphVizExport(scalan) + implicit val graphVizConfig = gv.defaultGraphVizConfig try { - val ss = sfs.map(_.apply()) - scalan.emitDepGraph(ss, directory, name) + val ss = sfs.map(_.apply()).asInstanceOf[Seq[gv.scalan.Sym]] + gv.emitDepGraph(ss, directory, name)(graphVizConfig) } catch { case e: Exception => - val graphMsg = scalan.emitExceptionGraph(e, directory, name) match { + val graphMsg = gv.emitExceptionGraph(e, directory, name) match { case Some(graphFile) => s"See ${graphFile.file.getAbsolutePath} for exception graph." case None => @@ -26,7 +27,7 @@ trait TestContexts extends TestUtils { trait TestContextApi { scalan: Scalan => def invokeAll: Boolean - def isInvokeEnabled(d: Def[_], m: Method): Boolean + def isInvokeEnabled(d: Def[_], m: RMethod): Boolean def shouldUnpack(e: Elem[_]): Boolean def testName: String def emitF(name: String, sfs: (() => Sym)*): Unit @@ -43,7 +44,7 @@ trait TestContexts extends TestUtils { def this() = this(currentTestNameAsFileName) override val invokeAll = true - override def isInvokeEnabled(d: Def[_], m: Method) = invokeAll + override def isInvokeEnabled(d: Def[_], m: RMethod) = invokeAll override def shouldUnpack(e: Elem[_]) = true // workaround for non-existence of by-name repeated parameters @@ -53,7 +54,9 @@ trait TestContexts extends TestUtils { } -abstract class BaseCtxTests extends BaseTests with TestContexts +abstract class BaseCtxTests extends BaseTests with TestContexts { + val reflection = (CoreLibReflection, GraphIRReflection) +} abstract class BaseNestedCtxTests extends BaseNestedTests with TestContexts diff --git a/library/src/test/scala/scalan/TestLibrary.scala b/graph-ir/src/test/scala/scalan/TestLibrary.scala similarity index 78% rename from library/src/test/scala/scalan/TestLibrary.scala rename to graph-ir/src/test/scala/scalan/TestLibrary.scala index d3ce5de652..efbce25e68 100644 --- a/library/src/test/scala/scalan/TestLibrary.scala +++ b/graph-ir/src/test/scala/scalan/TestLibrary.scala @@ -2,6 +2,6 @@ package scalan trait TestLibrary extends Library { import CollBuilder._ - + val reflection = (GraphIRReflection) lazy val colBuilder: Ref[CollBuilder] = variable[CollBuilder] } diff --git a/core/src/main/scala/scalan/compilation/GraphVizExport.scala b/graph-ir/src/test/scala/scalan/compilation/GraphVizExport.scala similarity index 98% rename from core/src/main/scala/scalan/compilation/GraphVizExport.scala rename to graph-ir/src/test/scala/scalan/compilation/GraphVizExport.scala index 01c2985f70..11cc2de629 100644 --- a/core/src/main/scala/scalan/compilation/GraphVizExport.scala +++ b/graph-ir/src/test/scala/scalan/compilation/GraphVizExport.scala @@ -1,17 +1,17 @@ package scalan.compilation import java.awt.Desktop -import java.io.{PrintWriter, File} +import java.io.{File, PrintWriter} +import scalan.Scalan +import scalan.util.{StringUtil, ScalaNameUtil, FileUtil, ProcessUtil} -import scalan.{Scalan, Base} -import scalan.util.{ProcessUtil, FileUtil, StringUtil, ScalaNameUtil} import scala.collection.immutable.StringOps // TODO implement this outside of the cake /** Implementation of Graphviz's dot file generator. */ -trait GraphVizExport extends Base { self: Scalan => - +class GraphVizExport[Ctx <: Scalan](val scalan: Ctx) { + import scalan._ case class GraphFile(file: File, fileType: String) { def open() = { Desktop.getDesktop.open(file) diff --git a/common/src/main/scala/scalan/util/ScalaNameUtil.scala b/graph-ir/src/test/scala/scalan/util/ScalaNameUtil.scala similarity index 63% rename from common/src/main/scala/scalan/util/ScalaNameUtil.scala rename to graph-ir/src/test/scala/scalan/util/ScalaNameUtil.scala index fadc8126ef..0f54e958c7 100644 --- a/common/src/main/scala/scalan/util/ScalaNameUtil.scala +++ b/graph-ir/src/test/scala/scalan/util/ScalaNameUtil.scala @@ -3,22 +3,22 @@ package scalan.util object ScalaNameUtil { val opChars = Set('+', '-', '*', '/', ':', '>', '<', '=', '!', '@', '#', '%', '&', '~', '?', '|', '\\', '^') - + def cleanNestedClassName(className: String): String = cleanScalaName(className.substring(className.lastIndexOf("$") + 1)) def cleanScalaName(name: String): String = { name.replace("$plus", "+").replace("$minus", "-"). - replace("$times", "*").replace("$div", "/"). - replace("$colon", ":").replace("$greater", ">"). - replace("$less", "<").replace("$eq", "="). - replace("$bang", "!").replace("$at", "@"). - replace("$hash", "#").replace("$percent", "%"). - replace("$amp", "&").replace("$tilde", "~"). - replace("$qmark", "?").replace("$bar", "|"). - replace("$bslash", "\\").replace("$up", "^") + replace("$times", "*").replace("$div", "/"). + replace("$colon", ":").replace("$greater", ">"). + replace("$less", "<").replace("$eq", "="). + replace("$bang", "!").replace("$at", "@"). + replace("$hash", "#").replace("$percent", "%"). + replace("$amp", "&").replace("$tilde", "~"). + replace("$qmark", "?").replace("$bar", "|"). + replace("$bslash", "\\").replace("$up", "^") } - + def isOpName(name: String) = !name.isEmpty && opChars.contains(name.last) object PackageAndName { @@ -30,5 +30,4 @@ object ScalaNameUtil { None } } - } diff --git a/common/src/test/scala/scalan/util/ScalaNameUtilSuite.scala b/graph-ir/src/test/scala/scalan/util/ScalaNameUtilSuite.scala similarity index 100% rename from common/src/test/scala/scalan/util/ScalaNameUtilSuite.scala rename to graph-ir/src/test/scala/scalan/util/ScalaNameUtilSuite.scala diff --git a/library/src/test/scala/special/collections/BaseCostedTests.scala b/graph-ir/src/test/scala/special/collections/BaseCostedTests.scala similarity index 100% rename from library/src/test/scala/special/collections/BaseCostedTests.scala rename to graph-ir/src/test/scala/special/collections/BaseCostedTests.scala diff --git a/library/src/test/scala/special/collections/BasicBenchmarks.scala b/graph-ir/src/test/scala/special/collections/BasicBenchmarks.scala similarity index 100% rename from library/src/test/scala/special/collections/BasicBenchmarks.scala rename to graph-ir/src/test/scala/special/collections/BasicBenchmarks.scala diff --git a/library/src/test/scala/special/collections/BenchmarkGens.scala b/graph-ir/src/test/scala/special/collections/BenchmarkGens.scala similarity index 100% rename from library/src/test/scala/special/collections/BenchmarkGens.scala rename to graph-ir/src/test/scala/special/collections/BenchmarkGens.scala diff --git a/library/src/test/scala/special/collections/BufferBenchmark.scala b/graph-ir/src/test/scala/special/collections/BufferBenchmark.scala similarity index 100% rename from library/src/test/scala/special/collections/BufferBenchmark.scala rename to graph-ir/src/test/scala/special/collections/BufferBenchmark.scala diff --git a/library/src/test/scala/special/collections/CollBenchmark.scala b/graph-ir/src/test/scala/special/collections/CollBenchmark.scala similarity index 100% rename from library/src/test/scala/special/collections/CollBenchmark.scala rename to graph-ir/src/test/scala/special/collections/CollBenchmark.scala diff --git a/library/src/test/scala/special/collections/CollGens.scala b/graph-ir/src/test/scala/special/collections/CollGens.scala similarity index 100% rename from library/src/test/scala/special/collections/CollGens.scala rename to graph-ir/src/test/scala/special/collections/CollGens.scala diff --git a/library/src/test/scala/special/collections/CollsStagingTests.scala b/graph-ir/src/test/scala/special/collections/CollsStagingTests.scala similarity index 86% rename from library/src/test/scala/special/collections/CollsStagingTests.scala rename to graph-ir/src/test/scala/special/collections/CollsStagingTests.scala index ea37389eb6..9c160c6093 100644 --- a/library/src/test/scala/special/collections/CollsStagingTests.scala +++ b/graph-ir/src/test/scala/special/collections/CollsStagingTests.scala @@ -6,6 +6,8 @@ import scalan._ import scalan.util.BenchmarkUtil._ class CollsStagingTests extends WrappersTests { + val printDebugInfo: Boolean = false + class Ctx extends TestContext with TestLibrary { import Coll._ import CollBuilder._ @@ -34,19 +36,19 @@ class CollsStagingTests extends WrappersTests { var res: Sym = null val nIters = 10 - measure(nIters) { i => + measure(nIters, okShowIterTime = printDebugInfo, okShowTotalTime = printDebugInfo) { i => for (j <- 0 until 1000) { val col = colBuilder.replicate(i*j, 0) res = col.map(fun {x => x + 1}) } - println(s"Defs: ${ctx.defCount}") + if (printDebugInfo) println(s"Defs: ${ctx.defCount}") if (i == nIters - 1) emit("res", res) ctx.resetContext() } } test("measure: build graph with new context") { - measure(10) { i => + measure(10, okShowIterTime = printDebugInfo, okShowTotalTime = printDebugInfo) { i => var sum: Int = 0 for (j <- 0 until 1000) { val ctx = new Ctx { @@ -59,12 +61,13 @@ class CollsStagingTests extends WrappersTests { val res = col.map(fun {x => x + 1}) sum += ctx.defCount } - println(s"Defs: ${sum}") + if (printDebugInfo) println(s"Defs: ${sum}") } } def runMeasure(nRepeats: Int, name: String, alphaEq: Boolean, keepOrig: Boolean, unfoldWithOrig: Boolean) = { - println(s"runMeasure($name, alphaEq = $alphaEq, keepOrig = $keepOrig, unfoldWithOrig = $unfoldWithOrig)") + if (printDebugInfo) + println(s"runMeasure($name, alphaEq = $alphaEq, keepOrig = $keepOrig, unfoldWithOrig = $unfoldWithOrig)") val nIters = 10 def warmUp(i: Int) = { val ctx = new Ctx { @@ -106,14 +109,14 @@ class CollsStagingTests extends WrappersTests { } outGraph = Pair(f, f(Pair(colBuilder, 1))) } - println(s"Defs: ${ctx.defCount}") + if (printDebugInfo) println(s"Defs: ${ctx.defCount}") if (i == nIters - 1) emit(name, outGraph) } - measure(nIters)(warmUp) + measure(nIters, okShowIterTime = printDebugInfo, okShowTotalTime = printDebugInfo)(warmUp) System.gc() - measure(nIters)(measureUp) + measure(nIters, okShowIterTime = printDebugInfo, okShowTotalTime = printDebugInfo)(measureUp) } test("measure: unfoldLambda") { @@ -190,7 +193,7 @@ Total time: 5406 ms // check(Cols, { env: EnvRep[CollBuilder] => for { b <- env; arrL <- lifted(arr) } yield b.fromArray(arrL) }, Cols.fromArray(arr)) - measure(10) { i => + measure(10, okShowIterTime = printDebugInfo, okShowTotalTime = printDebugInfo) { i => (1 to 100).foreach { j => check(Cols, {env: EnvRep[CollBuilder] => for { @@ -198,7 +201,7 @@ Total time: 5406 ms } yield b.fromItems(x1, x2, x3) }, Cols.fromItems(1, j, i)) } - println(s"Defs: ${ctx.defCount}") + if (printDebugInfo) println(s"Defs: ${ctx.defCount}") } } diff --git a/library/src/test/scala/special/collections/CollsTests.scala b/graph-ir/src/test/scala/special/collections/CollsTests.scala similarity index 100% rename from library/src/test/scala/special/collections/CollsTests.scala rename to graph-ir/src/test/scala/special/collections/CollsTests.scala diff --git a/library/src/test/scala/special/collections/MapBenchmark.scala b/graph-ir/src/test/scala/special/collections/MapBenchmark.scala similarity index 100% rename from library/src/test/scala/special/collections/MapBenchmark.scala rename to graph-ir/src/test/scala/special/collections/MapBenchmark.scala diff --git a/library/src/test/scala/special/collections/SymBenchmark.scala b/graph-ir/src/test/scala/special/collections/SymBenchmark.scala similarity index 100% rename from library/src/test/scala/special/collections/SymBenchmark.scala rename to graph-ir/src/test/scala/special/collections/SymBenchmark.scala diff --git a/library/src/test/scala/special/wrappers/WOptionTests.scala b/graph-ir/src/test/scala/special/wrappers/WOptionTests.scala similarity index 54% rename from library/src/test/scala/special/wrappers/WOptionTests.scala rename to graph-ir/src/test/scala/special/wrappers/WOptionTests.scala index 95b0d27416..7e046739f0 100644 --- a/library/src/test/scala/special/wrappers/WOptionTests.scala +++ b/graph-ir/src/test/scala/special/wrappers/WOptionTests.scala @@ -13,7 +13,6 @@ class WOptionTests extends WrappersTests { val opt = Option(1) check(opt, { env: EnvRep[WOption[Int]] => for { xs <- env } yield xs.get }, opt.get) - check(opt, { env: EnvRep[WOption[Int]] => for { xs <- env } yield xs.isEmpty }, opt.isEmpty) check(opt, { env: EnvRep[WOption[Int]] => for { xs <- env } yield xs.isDefined }, opt.isDefined) val none: Option[Int] = None @@ -24,17 +23,7 @@ class WOptionTests extends WrappersTests { check(opt, { env: EnvRep[WOption[Int]] => for { xs <- env; pL <- lifted(p) } yield xs.filter(pL) }, opt.filter(p)) val inc = (x: Int) => x + 1 - check(opt, { env: EnvRep[WOption[Int]] => - for { xs <- env; thL <- lifted(th); incL <- lifted(inc) } yield xs.fold(thL, incL) }, - opt.fold(th())(inc)) - check(none, { env: EnvRep[WOption[Int]] => - for { xs <- env; thL <- lifted(th); incL <- lifted(inc) } yield xs.fold(thL, incL) }, none.fold(th())(inc)) check(opt, { env: EnvRep[WOption[Int]] => for { xs <- env; incL <- lifted(inc) } yield xs.map(incL) }, opt.map(inc)) - - val incOpt = (x: Int) => Option(x + 1) - val incNone = (x: Int) => (None: Option[Int]) - check(opt, { env: EnvRep[WOption[Int]] => for { xs <- env; incOptL <- lifted(incOpt)} yield xs.flatMap(incOptL) }, opt.flatMap(incOpt)) - check(opt, { env: EnvRep[WOption[Int]] => for { xs <- env; incNoneL <- lifted(incNone)} yield xs.flatMap(incNoneL) }, opt.flatMap(incNone)) } } diff --git a/library/src/test/scala/special/wrappers/WRTypeTests.scala b/graph-ir/src/test/scala/special/wrappers/WRTypeTests.scala similarity index 100% rename from library/src/test/scala/special/wrappers/WRTypeTests.scala rename to graph-ir/src/test/scala/special/wrappers/WRTypeTests.scala diff --git a/library/src/test/scala/special/wrappers/WSpecialPredefTests.scala b/graph-ir/src/test/scala/special/wrappers/WSpecialPredefTests.scala similarity index 100% rename from library/src/test/scala/special/wrappers/WSpecialPredefTests.scala rename to graph-ir/src/test/scala/special/wrappers/WSpecialPredefTests.scala diff --git a/library/src/test/scala/special/wrappers/WrappersTests.scala b/graph-ir/src/test/scala/special/wrappers/WrappersTests.scala similarity index 100% rename from library/src/test/scala/special/wrappers/WrappersTests.scala rename to graph-ir/src/test/scala/special/wrappers/WrappersTests.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/ErgoAddress.scala b/interpreter/src/main/scala/org/ergoplatform/ErgoAddress.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/ErgoAddress.scala rename to interpreter/src/main/scala/org/ergoplatform/ErgoAddress.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/ErgoBox.scala b/interpreter/src/main/scala/org/ergoplatform/ErgoBox.scala similarity index 94% rename from sigmastate/src/main/scala/org/ergoplatform/ErgoBox.scala rename to interpreter/src/main/scala/org/ergoplatform/ErgoBox.scala index 256f643d93..51b6434253 100644 --- a/sigmastate/src/main/scala/org/ergoplatform/ErgoBox.scala +++ b/interpreter/src/main/scala/org/ergoplatform/ErgoBox.scala @@ -116,14 +116,22 @@ object ErgoBox { type Amount = Long - trait RegisterId { + /** Represents id of a [[ErgoBox]] register. */ + sealed trait RegisterId { + /** Zero-based register index in [0, 9] range. */ val number: Byte + + /** Returns zero-based register index in [0, 9] range. */ def asIndex: Int = number.toInt + override def toString: String = "R" + number } - abstract class MandatoryRegisterId(override val number: Byte, val purpose: String) extends RegisterId - abstract class NonMandatoryRegisterId(override val number: Byte) extends RegisterId + /** Represents id of pre-defined mandatory registers of a box. */ + sealed abstract class MandatoryRegisterId(override val number: Byte, val purpose: String) extends RegisterId + + /** Represents id of optional registers of a box. */ + sealed abstract class NonMandatoryRegisterId(override val number: Byte) extends RegisterId type AdditionalRegisters = Map[NonMandatoryRegisterId, _ <: EvaluatedValue[_ <: SType]] diff --git a/sigmastate/src/main/scala/org/ergoplatform/ErgoBoxAssets.scala b/interpreter/src/main/scala/org/ergoplatform/ErgoBoxAssets.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/ErgoBoxAssets.scala rename to interpreter/src/main/scala/org/ergoplatform/ErgoBoxAssets.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala b/interpreter/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala rename to interpreter/src/main/scala/org/ergoplatform/ErgoBoxCandidate.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/ErgoLikeContext.scala b/interpreter/src/main/scala/org/ergoplatform/ErgoLikeContext.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/ErgoLikeContext.scala rename to interpreter/src/main/scala/org/ergoplatform/ErgoLikeContext.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala b/interpreter/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala rename to interpreter/src/main/scala/org/ergoplatform/ErgoLikeInterpreter.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala b/interpreter/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala rename to interpreter/src/main/scala/org/ergoplatform/ErgoLikeTransaction.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala b/interpreter/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala similarity index 98% rename from sigmastate/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala rename to interpreter/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala index d270df8449..8a6c2fe06f 100644 --- a/sigmastate/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala +++ b/interpreter/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala @@ -18,7 +18,7 @@ object ErgoScriptPredef { import sigmastate.interpreter.Interpreter._ /** Compiles the given ErgoScript `code` into ErgoTree expression. */ - private def compileWithCosting(env: ScriptEnv, code: String, networkPrefix: NetworkPrefix)(implicit IR: IRContext): Value[SType] = { + def compileWithCosting(env: ScriptEnv, code: String, networkPrefix: NetworkPrefix)(implicit IR: IRContext): Value[SType] = { val compiler = new SigmaCompiler(networkPrefix) val res = compiler.compile(env, code) res.buildTree diff --git a/sigmastate/src/main/scala/org/ergoplatform/Input.scala b/interpreter/src/main/scala/org/ergoplatform/Input.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/Input.scala rename to interpreter/src/main/scala/org/ergoplatform/Input.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/JsonCodecs.scala b/interpreter/src/main/scala/org/ergoplatform/JsonCodecs.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/JsonCodecs.scala rename to interpreter/src/main/scala/org/ergoplatform/JsonCodecs.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/SigmaConstants.scala b/interpreter/src/main/scala/org/ergoplatform/SigmaConstants.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/SigmaConstants.scala rename to interpreter/src/main/scala/org/ergoplatform/SigmaConstants.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/dsl/AvlTreeHelpers.scala b/interpreter/src/main/scala/org/ergoplatform/dsl/AvlTreeHelpers.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/dsl/AvlTreeHelpers.scala rename to interpreter/src/main/scala/org/ergoplatform/dsl/AvlTreeHelpers.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala b/interpreter/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala rename to interpreter/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala b/interpreter/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala rename to interpreter/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala b/interpreter/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala rename to interpreter/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/dsl/StdContracts.scala b/interpreter/src/main/scala/org/ergoplatform/dsl/StdContracts.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/dsl/StdContracts.scala rename to interpreter/src/main/scala/org/ergoplatform/dsl/StdContracts.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/mining/emission/EmissionRules.scala b/interpreter/src/main/scala/org/ergoplatform/mining/emission/EmissionRules.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/mining/emission/EmissionRules.scala rename to interpreter/src/main/scala/org/ergoplatform/mining/emission/EmissionRules.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/settings/ErgoAlgos.scala b/interpreter/src/main/scala/org/ergoplatform/settings/ErgoAlgos.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/settings/ErgoAlgos.scala rename to interpreter/src/main/scala/org/ergoplatform/settings/ErgoAlgos.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/settings/MonetarySettings.scala b/interpreter/src/main/scala/org/ergoplatform/settings/MonetarySettings.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/settings/MonetarySettings.scala rename to interpreter/src/main/scala/org/ergoplatform/settings/MonetarySettings.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/validation/RuleStatus.scala b/interpreter/src/main/scala/org/ergoplatform/validation/RuleStatus.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/validation/RuleStatus.scala rename to interpreter/src/main/scala/org/ergoplatform/validation/RuleStatus.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/validation/RuleStatusSerializer.scala b/interpreter/src/main/scala/org/ergoplatform/validation/RuleStatusSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/validation/RuleStatusSerializer.scala rename to interpreter/src/main/scala/org/ergoplatform/validation/RuleStatusSerializer.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/validation/SigmaValidationSettings.scala b/interpreter/src/main/scala/org/ergoplatform/validation/SigmaValidationSettings.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/validation/SigmaValidationSettings.scala rename to interpreter/src/main/scala/org/ergoplatform/validation/SigmaValidationSettings.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializer.scala b/interpreter/src/main/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializer.scala rename to interpreter/src/main/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializer.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/validation/SoftForkChecker.scala b/interpreter/src/main/scala/org/ergoplatform/validation/SoftForkChecker.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/validation/SoftForkChecker.scala rename to interpreter/src/main/scala/org/ergoplatform/validation/SoftForkChecker.scala diff --git a/sigmastate/src/main/scala/org/ergoplatform/validation/ValidationRules.scala b/interpreter/src/main/scala/org/ergoplatform/validation/ValidationRules.scala similarity index 100% rename from sigmastate/src/main/scala/org/ergoplatform/validation/ValidationRules.scala rename to interpreter/src/main/scala/org/ergoplatform/validation/ValidationRules.scala diff --git a/sigmastate/src/main/scala/sigmastate/AvlTreeData.scala b/interpreter/src/main/scala/sigmastate/AvlTreeData.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/AvlTreeData.scala rename to interpreter/src/main/scala/sigmastate/AvlTreeData.scala diff --git a/sigmastate/src/main/scala/sigmastate/CostKind.scala b/interpreter/src/main/scala/sigmastate/CostKind.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/CostKind.scala rename to interpreter/src/main/scala/sigmastate/CostKind.scala diff --git a/sigmastate/src/main/scala/sigmastate/DataValueComparer.scala b/interpreter/src/main/scala/sigmastate/DataValueComparer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/DataValueComparer.scala rename to interpreter/src/main/scala/sigmastate/DataValueComparer.scala diff --git a/interpreter/src/main/scala/sigmastate/InterpreterReflection.scala b/interpreter/src/main/scala/sigmastate/InterpreterReflection.scala new file mode 100644 index 0000000000..6691c10766 --- /dev/null +++ b/interpreter/src/main/scala/sigmastate/InterpreterReflection.scala @@ -0,0 +1,732 @@ +package sigmastate + +import org.ergoplatform.ErgoBox.RegisterId +import scalan.GraphIRReflection +import scalan.reflection.CommonReflection.registerClassEntry +import scalan.reflection.{SRConstructor, mkConstructor, mkMethod, SRMethod} +import sigmastate.SAvlTree.KeyValueColl +import sigmastate.SCollection.{SIntArray, SByteArray, SBooleanArray} +import sigmastate.Values._ +import sigmastate.basics.VerifierMessage.Challenge +import sigmastate.crypto.GF2_192_Poly +import sigmastate.interpreter.ErgoTreeEvaluator +import sigmastate.lang.Terms._ +import sigmastate.lang.{CheckingSigmaBuilder, Terms} +import sigmastate.serialization.OpCodes.OpCode +import sigmastate.utxo._ +import special.CoreLibReflection +import special.collection.Coll +import special.sigma.{SigmaDslBuilder, AvlTree} + +/** Reflection metadata for `interpreter` module. + * For each class of this module that needs reflection metadata, + * we register a class entry with the necessary information. + * Only information that is needed at runtime is registered. + */ +object InterpreterReflection { + val reflection = (GraphIRReflection, CoreLibReflection) + + registerClassEntry(classOf[AND], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new AND(args(0).asInstanceOf[Value[SBooleanArray]]) + } + ) + ) + + registerClassEntry(classOf[ArithOp[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Byte])) { args => + new ArithOp(args(0).asInstanceOf[SValue], args(1).asInstanceOf[SValue], args(2).asInstanceOf[OpCode]) + } + ) + ) + + registerClassEntry(classOf[AtLeast], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new AtLeast(args(0).asInstanceOf[IntValue], args(1).asInstanceOf[CollectionValue[SSigmaProp.type]]) + } + ) + ) + + registerClassEntry(classOf[BinAnd], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new BinAnd(args(0).asInstanceOf[BoolValue], args(1).asInstanceOf[BoolValue]) + } + ) + ) + + registerClassEntry(classOf[BinOr], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new BinOr(args(0).asInstanceOf[BoolValue], args(1).asInstanceOf[BoolValue]) + } + ) + ) + + registerClassEntry(classOf[BinXor], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new BinXor(args(0).asInstanceOf[BoolValue], args(1).asInstanceOf[BoolValue]) + } + ) + ) + + registerClassEntry(classOf[BoolToSigmaProp], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new BoolToSigmaProp(args(0).asInstanceOf[BoolValue]) + } + ) + ) + + registerClassEntry(classOf[ByteArrayToBigInt], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new ByteArrayToBigInt(args(0).asInstanceOf[Value[SByteArray]]) + } + ) + ) + + registerClassEntry(classOf[CAndUncheckedNode], + constructors = Array( + mkConstructor(Array(classOf[Array[Byte]], classOf[Seq[_]])) { args => + new CAndUncheckedNode(args(0).asInstanceOf[Challenge], args(1).asInstanceOf[Seq[UncheckedSigmaTree]]) + } + ) + ) + + registerClassEntry(classOf[CAndUnproven], + constructors = Array( + mkConstructor(Array(classOf[CAND], classOf[Option[_]], classOf[Boolean], classOf[Seq[_]], classOf[NodePosition])) { args => + new CAndUnproven(args(0).asInstanceOf[CAND], + args(1).asInstanceOf[Option[Challenge]], + args(2).asInstanceOf[Boolean], + args(3).asInstanceOf[Seq[ProofTree]], + args(4).asInstanceOf[NodePosition]) + } + ) + ) + + registerClassEntry(classOf[COrUncheckedNode], + constructors = Array( + mkConstructor(Array(classOf[Array[Byte]], classOf[Seq[_]])) { args => + new COrUncheckedNode(args(0).asInstanceOf[Challenge], args(1).asInstanceOf[Seq[UncheckedSigmaTree]]) + } + ) + ) + + registerClassEntry(classOf[COrUnproven], + constructors = Array( + mkConstructor(Array(classOf[COR], classOf[Option[_]], classOf[Boolean], classOf[Seq[_]], classOf[NodePosition])) { args => + new COrUnproven(args(0).asInstanceOf[COR], + args(1).asInstanceOf[Option[Challenge]], + args(2).asInstanceOf[Boolean], + args(3).asInstanceOf[Seq[ProofTree]], + args(4).asInstanceOf[NodePosition]) + } + ) + ) + + registerClassEntry(classOf[CThresholdUncheckedNode], + constructors = Array( + mkConstructor(Array(classOf[Array[Byte]], classOf[Seq[_]], classOf[java.lang.Integer], classOf[Option[_]])) { args => + new CThresholdUncheckedNode(args(0).asInstanceOf[Challenge], + args(1).asInstanceOf[Seq[UncheckedSigmaTree]], + args(2).asInstanceOf[java.lang.Integer], + args(3).asInstanceOf[Option[GF2_192_Poly]]) + } + ) + ) + + registerClassEntry(classOf[CThresholdUnproven], + constructors = Array( + mkConstructor(Array(classOf[CTHRESHOLD], classOf[Option[_]], classOf[Boolean], classOf[java.lang.Integer], classOf[Seq[_]], classOf[Option[_]], classOf[NodePosition])) { args => + new CThresholdUnproven(args(0).asInstanceOf[CTHRESHOLD], + args(1).asInstanceOf[Option[Challenge]], + args(2).asInstanceOf[Boolean], + args(3).asInstanceOf[java.lang.Integer], + args(4).asInstanceOf[Seq[ProofTree]], + args(5).asInstanceOf[Option[GF2_192_Poly]], + args(6).asInstanceOf[NodePosition]) + } + ) + ) + + registerClassEntry(classOf[CalcBlake2b256], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new CalcBlake2b256(args(0).asInstanceOf[Value[SByteArray]]) + } + ) + ) + + registerClassEntry(classOf[CalcSha256], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new CalcSha256(args(0).asInstanceOf[Value[SByteArray]]) + } + ) + ) + + registerClassEntry(classOf[CreateProveDHTuple], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => + new CreateProveDHTuple(args(0).asInstanceOf[GroupElementValue], + args(1).asInstanceOf[GroupElementValue], + args(2).asInstanceOf[GroupElementValue], + args(3).asInstanceOf[GroupElementValue]) + } + ) + ) + + registerClassEntry(classOf[Downcast[_,_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[SNumericType])) { args => + new Downcast(args(0).asInstanceOf[Value[SNumericType]], args(1).asInstanceOf[SNumericType]) + } + ) + ) + + registerClassEntry(classOf[EQ[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new EQ(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[Exponentiate], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new Exponentiate(args(0).asInstanceOf[GroupElementValue], args(1).asInstanceOf[BigIntValue]) + } + ) + ) + + registerClassEntry(classOf[GE[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new GE(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[GT[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new GT(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[If[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => + new If(args(0).asInstanceOf[BoolValue], args(1).asInstanceOf[SAnyValue], args(2).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[LE[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new LE(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[LT[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new LT(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[LogicalNot], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new LogicalNot(args(0).asInstanceOf[BoolValue]) + } + ) + ) + + registerClassEntry(classOf[MultiplyGroup], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new MultiplyGroup(args(0).asInstanceOf[GroupElementValue], args(1).asInstanceOf[GroupElementValue]) + } + ) + ) + + registerClassEntry(classOf[NEQ[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new NEQ(args(0).asInstanceOf[SAnyValue], args(1).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[Negation[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new Negation(args(0).asInstanceOf[SAnyValue]) + } + ) + ) + + registerClassEntry(classOf[OR], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new OR(args(0).asInstanceOf[Value[SBooleanArray]]) + } + ) + ) + + { val clazz = SAvlTree.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], + 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], + 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], + 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], + 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], + 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], + args(1).asInstanceOf[AvlTree], + args(2).asInstanceOf[KeyValueColl], + args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) + } + ) + ) + } + + { val clazz = SCollection.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], + 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], + 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], + 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], + 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], + 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], + 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], + 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], + 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], + 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 + 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], + args(1).asInstanceOf[SigmaDslBuilder], + args(2).asInstanceOf[Coll[Byte]], + args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) + } + ) + ) + } + + 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 => + new SigmaAnd(args(0).asInstanceOf[Seq[SigmaPropValue]]) + } + ) + ) + + registerClassEntry(classOf[SigmaOr], + constructors = Array( + mkConstructor(Array(classOf[Seq[_]])) { args => + new SigmaOr(args(0).asInstanceOf[Seq[SigmaPropValue]]) + } + ) + ) + + registerClassEntry(classOf[SubstConstants[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => + new SubstConstants(args(0).asInstanceOf[Value[SByteArray]], + args(1).asInstanceOf[Value[SIntArray]], + args(2).asInstanceOf[CollectionValue[SType]]) + } + ) + ) + + registerClassEntry(classOf[Upcast[_,_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[SNumericType])) { args => + new Upcast(args(0).asInstanceOf[Value[SNumericType]], args(1).asInstanceOf[SNumericType]) + } + ) + ) + + registerClassEntry(classOf[BlockValue], + constructors = Array( + mkConstructor(Array(classOf[IndexedSeq[_]], classOf[Value[_]])) { args => + new BlockValue(args(0).asInstanceOf[IndexedSeq[BlockItem]], args(1).asInstanceOf[SValue]) + } + ) + ) + + registerClassEntry(classOf[ConcreteCollection[_]], + constructors = Array( + mkConstructor(Array(classOf[Seq[_]], classOf[SType])) { args => + new ConcreteCollection(args(0).asInstanceOf[Seq[SValue]], args(1).asInstanceOf[SType]) + } + ) + ) + + registerClassEntry(classOf[FuncValue], + constructors = Array( + mkConstructor(Array(classOf[IndexedSeq[_]], classOf[Value[_]])) { args => + new FuncValue(args(0).asInstanceOf[IndexedSeq[(Int, SType)]], args(1).asInstanceOf[SValue]) + } + ) + ) + + registerClassEntry(classOf[Tuple], + constructors = Array( + mkConstructor(Array(classOf[IndexedSeq[_]])) { args => + new Tuple(args(0).asInstanceOf[IndexedSeq[SValue]]) + } + ) + ) + + registerClassEntry(classOf[ValDef], + constructors = Array( + mkConstructor(Array(classOf[Int], classOf[Seq[_]], classOf[Value[_]])) { args => + new ValDef(args(0).asInstanceOf[Int], args(1).asInstanceOf[Seq[STypeVar]], args(2).asInstanceOf[SValue]) + } + ) + ) + + registerClassEntry(classOf[Apply], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[IndexedSeq[_]])) { args => + new Apply(args(0).asInstanceOf[SValue], args(1).asInstanceOf[IndexedSeq[SValue]]) + } + ) + ) + + registerClassEntry(classOf[ApplyTypes], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Seq[_]])) { args => + new ApplyTypes(args(0).asInstanceOf[SValue], args(1).asInstanceOf[Seq[SType]]) + } + ) + ) + + registerClassEntry(classOf[Block], + constructors = Array( + mkConstructor(Array(classOf[Seq[_]], classOf[Value[_]])) { args => + new Block(args(0).asInstanceOf[Seq[Val]], args(1).asInstanceOf[SValue]) + } + ) + ) + + registerClassEntry(classOf[Lambda], + constructors = Array( + mkConstructor(Array(classOf[Seq[_]], classOf[IndexedSeq[_]], classOf[SType], classOf[Option[_]])) { args => + new Lambda(args(0).asInstanceOf[Seq[STypeParam]], + args(1).asInstanceOf[IndexedSeq[(String, SType)]], + args(2).asInstanceOf[SType], + args(3).asInstanceOf[Option[SValue]]) + } + ) + ) + + registerClassEntry(classOf[MethodCall], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[SMethod], classOf[IndexedSeq[_]], classOf[scala.collection.immutable.Map[_,_]])) { args => + new MethodCall(args(0).asInstanceOf[SValue], + args(1).asInstanceOf[SMethod], + args(2).asInstanceOf[IndexedSeq[SValue]], + args(3).asInstanceOf[Map[STypeVar,SType]]) + } + ) + ) + + registerClassEntry(classOf[MethodCallLike], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[java.lang.String], classOf[IndexedSeq[_]], classOf[SType])) { args => + new MethodCallLike(args(0).asInstanceOf[SValue], + args(1).asInstanceOf[String], + args(2).asInstanceOf[IndexedSeq[SValue]], + args(3).asInstanceOf[SType]) + } + ) + ) + + registerClassEntry(classOf[Select], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[java.lang.String], classOf[Option[_]])) { args => + new Select(args(0).asInstanceOf[SValue], args(1).asInstanceOf[String], args(2).asInstanceOf[Option[SType]]) + } + ) + ) + + registerClassEntry(classOf[ValNode], + constructors = Array( + mkConstructor(Array(classOf[java.lang.String], classOf[SType], classOf[Value[_]])) { args => + new ValNode(args(0).asInstanceOf[String], args(1).asInstanceOf[SType], args(2).asInstanceOf[SValue]) + } + ) + ) + + registerClassEntry(classOf[Append[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new Append(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[CollectionValue[SType]]) + } + ) + ) + + registerClassEntry(classOf[ByIndex[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Option[_]])) { args => + new ByIndex(args(0).asInstanceOf[CollectionValue[SType]], + args(1).asInstanceOf[IntValue], args(2).asInstanceOf[Option[SValue]]) + } + ) + ) + + registerClassEntry(classOf[Exists[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new Exists(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[Value[SFunc]]) + } + ) + ) + + registerClassEntry(classOf[ExtractAmount], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new ExtractAmount(args(0).asInstanceOf[BoxValue]) + } + ) + ) + + registerClassEntry(classOf[ExtractBytesWithNoRef], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new ExtractBytesWithNoRef(args(0).asInstanceOf[BoxValue]) + } + ) + ) + + registerClassEntry(classOf[ExtractCreationInfo], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new ExtractCreationInfo(args(0).asInstanceOf[BoxValue]) + } + ) + ) + + registerClassEntry(classOf[ExtractId], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new ExtractId(args(0).asInstanceOf[BoxValue]) + } + ) + ) + + registerClassEntry(classOf[ExtractRegisterAs[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[org.ergoplatform.ErgoBox.RegisterId], classOf[SOption[_]])) { args => + new ExtractRegisterAs(args(0).asInstanceOf[BoxValue], args(1).asInstanceOf[RegisterId], args(2).asInstanceOf[SOption[SAny.type]]) + } + ) + ) + + registerClassEntry(classOf[ExtractScriptBytes], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new ExtractScriptBytes(args(0).asInstanceOf[BoxValue]) + } + ) + ) + + registerClassEntry(classOf[Filter[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new Filter(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[Value[SFunc]]) + } + ) + ) + + registerClassEntry(classOf[Fold[_,_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => + new Fold(args(0).asInstanceOf[CollectionValue[SType]], + args(1).asInstanceOf[SValue], args(2).asInstanceOf[Value[SFunc]]) + } + ) + ) + + registerClassEntry(classOf[ForAll[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new ForAll(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[Value[SFunc]]) + } + ) + ) + + registerClassEntry(classOf[MapCollection[_,_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new MapCollection(args(0).asInstanceOf[CollectionValue[SType]], args(1).asInstanceOf[Value[SFunc]]) + } + ) + ) + + registerClassEntry(classOf[OptionGet[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new OptionGet(args(0).asInstanceOf[Value[SOption[SType]]]) + } + ) + ) + + registerClassEntry(classOf[OptionGetOrElse[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]])) { args => + new OptionGetOrElse(args(0).asInstanceOf[Value[SOption[SType]]], args(1).asInstanceOf[SValue]) + } + ) + ) + + registerClassEntry(classOf[OptionIsDefined[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new OptionIsDefined(args(0).asInstanceOf[Value[SOption[SType]]]) + } + ) + ) + + registerClassEntry(classOf[SelectField], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Byte])) { args => + new SelectField(args(0).asInstanceOf[Value[STuple]], args(1).asInstanceOf[Byte]) + } + ) + ) + + registerClassEntry(classOf[SigmaPropBytes], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new SigmaPropBytes(args(0).asInstanceOf[SigmaPropValue]) + } + ) + ) + + registerClassEntry(classOf[SizeOf[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]])) { args => + new SizeOf(args(0).asInstanceOf[CollectionValue[SType]]) + } + ) + ) + + registerClassEntry(classOf[Slice[_]], + constructors = Array( + mkConstructor(Array(classOf[Value[_]], classOf[Value[_]], classOf[Value[_]])) { args => + new Slice(args(0).asInstanceOf[CollectionValue[SType]], + args(1).asInstanceOf[IntValue], args(2).asInstanceOf[IntValue]) + } + ) + ) +} diff --git a/sigmastate/src/main/scala/sigmastate/Operations.scala b/interpreter/src/main/scala/sigmastate/Operations.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/Operations.scala rename to interpreter/src/main/scala/sigmastate/Operations.scala diff --git a/sigmastate/src/main/scala/sigmastate/SigSerializer.scala b/interpreter/src/main/scala/sigmastate/SigSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/SigSerializer.scala rename to interpreter/src/main/scala/sigmastate/SigSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/UncheckedTree.scala b/interpreter/src/main/scala/sigmastate/UncheckedTree.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/UncheckedTree.scala rename to interpreter/src/main/scala/sigmastate/UncheckedTree.scala diff --git a/sigmastate/src/main/scala/sigmastate/UnprovenTree.scala b/interpreter/src/main/scala/sigmastate/UnprovenTree.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/UnprovenTree.scala rename to interpreter/src/main/scala/sigmastate/UnprovenTree.scala diff --git a/sigmastate/src/main/scala/sigmastate/Values.scala b/interpreter/src/main/scala/sigmastate/Values.scala similarity index 99% rename from sigmastate/src/main/scala/sigmastate/Values.scala rename to interpreter/src/main/scala/sigmastate/Values.scala index 0a70c43783..f7eb2b10cd 100644 --- a/sigmastate/src/main/scala/sigmastate/Values.scala +++ b/interpreter/src/main/scala/sigmastate/Values.scala @@ -40,6 +40,8 @@ import scala.collection.compat.immutable.ArraySeq import scala.collection.mutable object Values { + /** Force initialization of reflection. */ + val reflection = InterpreterReflection type SValue = Value[SType] @@ -476,6 +478,7 @@ object Values { type GroupElementValue = Value[SGroupElement.type] type SigmaPropValue = Value[SSigmaProp.type] type AvlTreeValue = Value[SAvlTree.type] + type SAnyValue = Value[SAny.type] type ByteConstant = Constant[SByte.type] type ShortConstant = Constant[SShort.type] @@ -605,6 +608,7 @@ object Values { } type CollectionConstant[T <: SType] = Constant[SCollection[T]] + type CollectionValue[T <: SType] = Value[SCollection[T]] object CollectionConstant { def apply[T <: SType](value: Coll[T#WrappedType], elementType: T): Constant[SCollection[T]] = diff --git a/sigmastate/src/main/scala/sigmastate/basics/BcDlogGroup.scala b/interpreter/src/main/scala/sigmastate/basics/BcDlogGroup.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/basics/BcDlogGroup.scala rename to interpreter/src/main/scala/sigmastate/basics/BcDlogGroup.scala diff --git a/sigmastate/src/main/scala/sigmastate/basics/DLogProtocol.scala b/interpreter/src/main/scala/sigmastate/basics/DLogProtocol.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/basics/DLogProtocol.scala rename to interpreter/src/main/scala/sigmastate/basics/DLogProtocol.scala diff --git a/sigmastate/src/main/scala/sigmastate/basics/DiffieHellmanTupleProtocol.scala b/interpreter/src/main/scala/sigmastate/basics/DiffieHellmanTupleProtocol.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/basics/DiffieHellmanTupleProtocol.scala rename to interpreter/src/main/scala/sigmastate/basics/DiffieHellmanTupleProtocol.scala diff --git a/sigmastate/src/main/scala/sigmastate/basics/DlogGroup.scala b/interpreter/src/main/scala/sigmastate/basics/DlogGroup.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/basics/DlogGroup.scala rename to interpreter/src/main/scala/sigmastate/basics/DlogGroup.scala diff --git a/sigmastate/src/main/scala/sigmastate/basics/SigmaProtocolFunctions.scala b/interpreter/src/main/scala/sigmastate/basics/SigmaProtocolFunctions.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/basics/SigmaProtocolFunctions.scala rename to interpreter/src/main/scala/sigmastate/basics/SigmaProtocolFunctions.scala diff --git a/sigmastate/src/main/scala/sigmastate/crypto/BigIntegers.scala b/interpreter/src/main/scala/sigmastate/crypto/BigIntegers.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/crypto/BigIntegers.scala rename to interpreter/src/main/scala/sigmastate/crypto/BigIntegers.scala diff --git a/sigmastate/src/main/scala/sigmastate/crypto/CryptoContext.scala b/interpreter/src/main/scala/sigmastate/crypto/CryptoContext.scala similarity index 84% rename from sigmastate/src/main/scala/sigmastate/crypto/CryptoContext.scala rename to interpreter/src/main/scala/sigmastate/crypto/CryptoContext.scala index b5aceec849..c0190ba093 100644 --- a/sigmastate/src/main/scala/sigmastate/crypto/CryptoContext.scala +++ b/interpreter/src/main/scala/sigmastate/crypto/CryptoContext.scala @@ -2,8 +2,11 @@ package sigmastate.crypto import java.math.BigInteger -/** A context for cryptographic operations. */ +/** A context for cryptographic operations over elliptic curve group. */ abstract class CryptoContext { + /** The underlying elliptic curve descriptor. */ + def curve: Curve + /** The characteristics of the underlying finite field. */ def fieldCharacteristic: BigInteger diff --git a/sigmastate/src/main/scala/sigmastate/crypto/CryptoContextJvm.scala b/interpreter/src/main/scala/sigmastate/crypto/CryptoContextJvm.scala similarity index 64% rename from sigmastate/src/main/scala/sigmastate/crypto/CryptoContextJvm.scala rename to interpreter/src/main/scala/sigmastate/crypto/CryptoContextJvm.scala index 6a3420242f..7b789f1db6 100644 --- a/sigmastate/src/main/scala/sigmastate/crypto/CryptoContextJvm.scala +++ b/interpreter/src/main/scala/sigmastate/crypto/CryptoContextJvm.scala @@ -6,9 +6,11 @@ import java.math.BigInteger /** JVM implementation of context for cryptographic operations using Bouncycastle. */ class CryptoContextJvm(x9params: X9ECParameters) extends CryptoContext { - private lazy val curve = x9params.getCurve + private lazy val _curve = x9params.getCurve - override def fieldCharacteristic: BigInteger = curve.getField.getCharacteristic + override def curve: Curve = Platform.Curve(_curve) + + override def fieldCharacteristic: BigInteger = _curve.getField.getCharacteristic override def order: BigInteger = x9params.getN @@ -17,14 +19,14 @@ class CryptoContextJvm(x9params: X9ECParameters) extends CryptoContext { } override def validatePoint(x: BigInteger, y: BigInteger): Ecp = { - Platform.Ecp(curve.validatePoint(x, y)) + Platform.Ecp(_curve.validatePoint(x, y)) } override def infinity(): Ecp = { - Platform.Ecp(curve.getInfinity) + Platform.Ecp(_curve.getInfinity) } override def decodePoint(encoded: Array[Byte]): Ecp = { - Platform.Ecp(curve.decodePoint(encoded)) + Platform.Ecp(_curve.decodePoint(encoded)) } } diff --git a/sigmastate/src/main/scala/sigmastate/crypto/CryptoFacade.scala b/interpreter/src/main/scala/sigmastate/crypto/CryptoFacade.scala similarity index 88% rename from sigmastate/src/main/scala/sigmastate/crypto/CryptoFacade.scala rename to interpreter/src/main/scala/sigmastate/crypto/CryptoFacade.scala index 54ec07940c..3a53bdfa29 100644 --- a/sigmastate/src/main/scala/sigmastate/crypto/CryptoFacade.scala +++ b/interpreter/src/main/scala/sigmastate/crypto/CryptoFacade.scala @@ -48,6 +48,19 @@ object CryptoFacade { /** Returns byte representation of the given field element. */ def encodeFieldElem(p: ECFieldElem): Array[Byte] = Platform.encodeFieldElem(p) + /** Byte representation of the given point. + * + * @param p point to encode + * @param compressed if true, generates a compressed point encoding + */ + def encodePoint(p: Ecp, compressed: Boolean): Array[Byte] = Platform.encodePoint(p, compressed) + + /** A [[Curve]] instance describing the elliptic curve of the point p + * + * @param p the elliptic curve point + */ + def getCurve(p: Ecp): Curve = Platform.getCurve(p) + /** Returns the x-coordinate. * * Caution: depending on the curve's coordinate system, this may not be the same value as in an diff --git a/sigmastate/src/main/scala/sigmastate/crypto/GF2_192.scala b/interpreter/src/main/scala/sigmastate/crypto/GF2_192.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/crypto/GF2_192.scala rename to interpreter/src/main/scala/sigmastate/crypto/GF2_192.scala diff --git a/sigmastate/src/main/scala/sigmastate/crypto/GF2_192_Poly.scala b/interpreter/src/main/scala/sigmastate/crypto/GF2_192_Poly.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/crypto/GF2_192_Poly.scala rename to interpreter/src/main/scala/sigmastate/crypto/GF2_192_Poly.scala diff --git a/sigmastate/src/main/scala/sigmastate/crypto/Platform.scala b/interpreter/src/main/scala/sigmastate/crypto/Platform.scala similarity index 84% rename from sigmastate/src/main/scala/sigmastate/crypto/Platform.scala rename to interpreter/src/main/scala/sigmastate/crypto/Platform.scala index 5cb4a9f345..55bc179e54 100644 --- a/sigmastate/src/main/scala/sigmastate/crypto/Platform.scala +++ b/interpreter/src/main/scala/sigmastate/crypto/Platform.scala @@ -1,12 +1,17 @@ package sigmastate.crypto import org.bouncycastle.crypto.ec.CustomNamedCurves -import org.bouncycastle.math.ec.{ECFieldElement, ECPoint} +import org.bouncycastle.math.ec.{ECPoint, ECFieldElement, ECCurve} import java.math.BigInteger /** JVM specific implementation of crypto methods*/ object Platform { + /** Description of elliptic curve of point `p` which belongs to the curve. + * @param p the elliptic curve point + */ + def getCurve(p: Ecp): Curve = Curve(p.value.getCurve) + /** Returns the x-coordinate. * * Caution: depending on the curve's coordinate system, this may not be the same value as in an @@ -46,6 +51,12 @@ object Platform { /** Returns byte representation of the given field element. */ def encodeFieldElem(p: ECFieldElem): Array[Byte] = p.value.getEncoded + /** Byte representation of the given point. + * @param p point to encode + * @param compressed if true, generates a compressed point encoding + */ + def encodePoint(p: Ecp, compressed: Boolean): Array[Byte] = p.value.getEncoded(compressed) + /** Returns the value of bit 0 in BigInteger representation of this point. */ def signOf(p: ECFieldElem): Boolean = p.value.testBitZero() @@ -94,6 +105,11 @@ object Platform { /** Negate a point. */ def negatePoint(p: Ecp): Ecp = Ecp(p.value.negate()) + /** Wrapper for curve descriptor. Serves as the concrete implementation of the + * [[sigmastate.crypto.Curve]] type in JVM. + */ + case class Curve(private[crypto] val value: ECCurve) + /** Wrapper for point type. */ case class Ecp(private[crypto] val value: ECPoint) diff --git a/sigmastate/src/main/scala/sigmastate/crypto/package.scala b/interpreter/src/main/scala/sigmastate/crypto/package.scala similarity index 72% rename from sigmastate/src/main/scala/sigmastate/crypto/package.scala rename to interpreter/src/main/scala/sigmastate/crypto/package.scala index 24d797be6f..a0feb011f9 100644 --- a/sigmastate/src/main/scala/sigmastate/crypto/package.scala +++ b/interpreter/src/main/scala/sigmastate/crypto/package.scala @@ -1,8 +1,12 @@ package sigmastate package object crypto { + /** Instance of Elliptic Curve descriptor. */ + type Curve = Platform.Curve + /** Instance of Elliptic Curve point. */ type Ecp = Platform.Ecp + /** Instance of Elliptic Curve field element. */ type ECFieldElem = Platform.ECFieldElem } diff --git a/sigmastate/src/main/scala/sigmastate/eval/BigIntegerOps.scala b/interpreter/src/main/scala/sigmastate/eval/BigIntegerOps.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/eval/BigIntegerOps.scala rename to interpreter/src/main/scala/sigmastate/eval/BigIntegerOps.scala diff --git a/sigmastate/src/main/scala/sigmastate/eval/CostingDataContext.scala b/interpreter/src/main/scala/sigmastate/eval/CostingDataContext.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/eval/CostingDataContext.scala rename to interpreter/src/main/scala/sigmastate/eval/CostingDataContext.scala diff --git a/sigmastate/src/main/scala/sigmastate/eval/Evaluation.scala b/interpreter/src/main/scala/sigmastate/eval/Evaluation.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/eval/Evaluation.scala rename to interpreter/src/main/scala/sigmastate/eval/Evaluation.scala diff --git a/sigmastate/src/main/scala/sigmastate/eval/Exceptions.scala b/interpreter/src/main/scala/sigmastate/eval/Exceptions.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/eval/Exceptions.scala rename to interpreter/src/main/scala/sigmastate/eval/Exceptions.scala diff --git a/sigmastate/src/main/scala/sigmastate/eval/Extensions.scala b/interpreter/src/main/scala/sigmastate/eval/Extensions.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/eval/Extensions.scala rename to interpreter/src/main/scala/sigmastate/eval/Extensions.scala diff --git a/sigmastate/src/main/scala/sigmastate/eval/GraphBuilding.scala b/interpreter/src/main/scala/sigmastate/eval/GraphBuilding.scala similarity index 99% rename from sigmastate/src/main/scala/sigmastate/eval/GraphBuilding.scala rename to interpreter/src/main/scala/sigmastate/eval/GraphBuilding.scala index f4cd55969c..8afa48e0d2 100644 --- a/sigmastate/src/main/scala/sigmastate/eval/GraphBuilding.scala +++ b/interpreter/src/main/scala/sigmastate/eval/GraphBuilding.scala @@ -4,7 +4,6 @@ import org.ergoplatform._ import org.ergoplatform.validation.ValidationRules.CheckTupleType import scalan.ExactIntegral.{ByteIsExactIntegral, IntIsExactIntegral, LongIsExactIntegral, ShortIsExactIntegral} import scalan.ExactOrdering.{ByteIsExactOrdering, IntIsExactOrdering, LongIsExactOrdering, ShortIsExactOrdering} -import scalan.compilation.GraphVizConfig import scalan.util.Extensions.ByteOps import scalan.{ExactIntegral, ExactNumeric, ExactOrdering, Lazy, MutableLazy, Nullable, SigmaLibrary} import sigmastate.Values.Value.Typed @@ -15,12 +14,10 @@ import sigmastate.lang.Terms.{Ident, Select, Val, ValueOps} import sigmastate.serialization.OpCodes import sigmastate.utxo._ import sigmastate._ -import sigmastate.eval.Extensions.GroupElementOps import sigmastate.interpreter.CryptoConstants.EcPointType import sigmastate.lang.exceptions.CosterException import scala.collection.mutable.ArrayBuffer -import scala.collection.compat.immutable.ArraySeq /** Perform translation of typed expression given by [[Value]] to a graph in IRContext. * Which be than be translated to [[ErgoTree]] by using [[TreeBuilding]]. @@ -73,12 +70,6 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => /** To enable specific configuration uncomment one of the lines above and use it in the beginPass below. */ // beginPass(costPass) - override protected def formatDef(d: Def[_])(implicit config: GraphVizConfig): String = d match { - case GroupElementConst(p) => p.showToString - case SigmaPropConst(sp) => sp.toString - case _ => super.formatDef(d) - } - type RColl[T] = Ref[Coll[T]] type ROption[T] = Ref[WOption[T]] diff --git a/sigmastate/src/main/scala/sigmastate/eval/IRContext.scala b/interpreter/src/main/scala/sigmastate/eval/IRContext.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/eval/IRContext.scala rename to interpreter/src/main/scala/sigmastate/eval/IRContext.scala diff --git a/sigmastate/src/main/scala/sigmastate/eval/Profiler.scala b/interpreter/src/main/scala/sigmastate/eval/Profiler.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/eval/Profiler.scala rename to interpreter/src/main/scala/sigmastate/eval/Profiler.scala diff --git a/sigmastate/src/main/scala/sigmastate/eval/TreeBuilding.scala b/interpreter/src/main/scala/sigmastate/eval/TreeBuilding.scala similarity index 98% rename from sigmastate/src/main/scala/sigmastate/eval/TreeBuilding.scala rename to interpreter/src/main/scala/sigmastate/eval/TreeBuilding.scala index 25f909e8bc..f8f477dca3 100644 --- a/sigmastate/src/main/scala/sigmastate/eval/TreeBuilding.scala +++ b/interpreter/src/main/scala/sigmastate/eval/TreeBuilding.scala @@ -235,12 +235,6 @@ trait TreeBuilding extends SigmaLibrary { IR: IRContext => mkArith(x.asNumValue, y.asNumValue, MinCode) case BIM.max(In(x), In(y)) => mkArith(x.asNumValue, y.asNumValue, MaxCode) - case BIM.modQ(In(x)) => - mkModQ(x.asBigInt) - case BIM.plusModQ(In(l), In(r)) => - mkPlusModQ(l.asBigInt, r.asBigInt) - case BIM.minusModQ(In(l), In(r)) => - mkMinusModQ(l.asBigInt, r.asBigInt) case Def(ApplyUnOp(IsNumericUnOp(mkNode), xSym)) => mkNode(recurse(xSym)) diff --git a/sigmastate/src/main/scala/sigmastate/eval/package.scala b/interpreter/src/main/scala/sigmastate/eval/package.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/eval/package.scala rename to interpreter/src/main/scala/sigmastate/eval/package.scala diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/CostAccumulator.scala b/interpreter/src/main/scala/sigmastate/interpreter/CostAccumulator.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/interpreter/CostAccumulator.scala rename to interpreter/src/main/scala/sigmastate/interpreter/CostAccumulator.scala diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/CostDetails.scala b/interpreter/src/main/scala/sigmastate/interpreter/CostDetails.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/interpreter/CostDetails.scala rename to interpreter/src/main/scala/sigmastate/interpreter/CostDetails.scala diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/CostItem.scala b/interpreter/src/main/scala/sigmastate/interpreter/CostItem.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/interpreter/CostItem.scala rename to interpreter/src/main/scala/sigmastate/interpreter/CostItem.scala diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/CryptoConstants.scala b/interpreter/src/main/scala/sigmastate/interpreter/CryptoConstants.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/interpreter/CryptoConstants.scala rename to interpreter/src/main/scala/sigmastate/interpreter/CryptoConstants.scala diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/CryptoFunctions.scala b/interpreter/src/main/scala/sigmastate/interpreter/CryptoFunctions.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/interpreter/CryptoFunctions.scala rename to interpreter/src/main/scala/sigmastate/interpreter/CryptoFunctions.scala diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/ErgoTreeEvaluator.scala b/interpreter/src/main/scala/sigmastate/interpreter/ErgoTreeEvaluator.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/interpreter/ErgoTreeEvaluator.scala rename to interpreter/src/main/scala/sigmastate/interpreter/ErgoTreeEvaluator.scala diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/Hint.scala b/interpreter/src/main/scala/sigmastate/interpreter/Hint.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/interpreter/Hint.scala rename to interpreter/src/main/scala/sigmastate/interpreter/Hint.scala diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/Interpreter.scala b/interpreter/src/main/scala/sigmastate/interpreter/Interpreter.scala similarity index 99% rename from sigmastate/src/main/scala/sigmastate/interpreter/Interpreter.scala rename to interpreter/src/main/scala/sigmastate/interpreter/Interpreter.scala index 1276849e60..5366a4b2e0 100644 --- a/sigmastate/src/main/scala/sigmastate/interpreter/Interpreter.scala +++ b/interpreter/src/main/scala/sigmastate/interpreter/Interpreter.scala @@ -15,14 +15,12 @@ import sigmastate.interpreter.Interpreter._ import sigmastate.lang.exceptions.InterpreterException import sigmastate.serialization.{SigmaSerializer, ValueSerializer} import sigmastate.utxo.DeserializeContext -import sigmastate.{SType, eval, _} -import sigmastate.eval.{Evaluation, IRContext, Profiler, SigmaDsl} -import scalan.util.BenchmarkUtil +import sigmastate.{SType, _} +import sigmastate.eval.{Evaluation, Profiler, SigmaDsl} import sigmastate.FiatShamirTree._ import sigmastate.SigSerializer._ import sigmastate.eval.Evaluation.addCostChecked import sigmastate.interpreter.ErgoTreeEvaluator.fixedCostOp -import sigmastate.interpreter.EvalSettings._ import sigmastate.utils.Helpers._ import sigmastate.lang.Terms.ValueOps import debox.cfor diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/InterpreterContext.scala b/interpreter/src/main/scala/sigmastate/interpreter/InterpreterContext.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/interpreter/InterpreterContext.scala rename to interpreter/src/main/scala/sigmastate/interpreter/InterpreterContext.scala diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/OperationDesc.scala b/interpreter/src/main/scala/sigmastate/interpreter/OperationDesc.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/interpreter/OperationDesc.scala rename to interpreter/src/main/scala/sigmastate/interpreter/OperationDesc.scala diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala b/interpreter/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala rename to interpreter/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/ProverResult.scala b/interpreter/src/main/scala/sigmastate/interpreter/ProverResult.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/interpreter/ProverResult.scala rename to interpreter/src/main/scala/sigmastate/interpreter/ProverResult.scala diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/ProverUtils.scala b/interpreter/src/main/scala/sigmastate/interpreter/ProverUtils.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/interpreter/ProverUtils.scala rename to interpreter/src/main/scala/sigmastate/interpreter/ProverUtils.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/SigmaBinder.scala b/interpreter/src/main/scala/sigmastate/lang/SigmaBinder.scala similarity index 96% rename from sigmastate/src/main/scala/sigmastate/lang/SigmaBinder.scala rename to interpreter/src/main/scala/sigmastate/lang/SigmaBinder.scala index eac3794eda..74db3ce7e7 100644 --- a/sigmastate/src/main/scala/sigmastate/lang/SigmaBinder.scala +++ b/interpreter/src/main/scala/sigmastate/lang/SigmaBinder.scala @@ -1,7 +1,5 @@ package sigmastate.lang -import java.lang.reflect.InvocationTargetException - import sigmastate.kiama.rewriting.CallbackRewriter import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix import org.ergoplatform._ @@ -117,8 +115,7 @@ class SigmaBinder(env: ScriptEnv, builder: SigmaBuilder, })))(e) def bind(e: SValue): SValue = - try eval(e, env) - catch { case e: InvocationTargetException => throw e.getCause } + eval(e, env) } object SigmaBinder { diff --git a/sigmastate/src/main/scala/sigmastate/lang/SigmaBuilder.scala b/interpreter/src/main/scala/sigmastate/lang/SigmaBuilder.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/SigmaBuilder.scala rename to interpreter/src/main/scala/sigmastate/lang/SigmaBuilder.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/SigmaCompiler.scala b/interpreter/src/main/scala/sigmastate/lang/SigmaCompiler.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/SigmaCompiler.scala rename to interpreter/src/main/scala/sigmastate/lang/SigmaCompiler.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/SigmaParser.scala b/interpreter/src/main/scala/sigmastate/lang/SigmaParser.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/SigmaParser.scala rename to interpreter/src/main/scala/sigmastate/lang/SigmaParser.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/SigmaPredef.scala b/interpreter/src/main/scala/sigmastate/lang/SigmaPredef.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/SigmaPredef.scala rename to interpreter/src/main/scala/sigmastate/lang/SigmaPredef.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/SigmaTyper.scala b/interpreter/src/main/scala/sigmastate/lang/SigmaTyper.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/SigmaTyper.scala rename to interpreter/src/main/scala/sigmastate/lang/SigmaTyper.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/SourceContext.scala b/interpreter/src/main/scala/sigmastate/lang/SourceContext.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/SourceContext.scala rename to interpreter/src/main/scala/sigmastate/lang/SourceContext.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/Terms.scala b/interpreter/src/main/scala/sigmastate/lang/Terms.scala similarity index 99% rename from sigmastate/src/main/scala/sigmastate/lang/Terms.scala rename to interpreter/src/main/scala/sigmastate/lang/Terms.scala index 9b90d62577..97eb26e850 100644 --- a/sigmastate/src/main/scala/sigmastate/lang/Terms.scala +++ b/interpreter/src/main/scala/sigmastate/lang/Terms.scala @@ -251,7 +251,7 @@ object Terms { object MethodCall extends FixedCostValueCompanion { override def opCode: OpCode = OpCodes.MethodCallCode - /** Cost of: 1) packing args into Array 2) java.lang.reflect.Method.invoke */ + /** Cost of: 1) packing args into Array 2) RMethod.invoke */ override val costKind = FixedCost(JitCost(4)) /** Helper constructor which allows to cast the resulting node to the specified @@ -267,7 +267,7 @@ object Terms { } object PropertyCall extends FixedCostValueCompanion { override def opCode: OpCode = OpCodes.PropertyCallCode - /** Cost of: 1) packing args into Array 2) java.lang.reflect.Method.invoke */ + /** Cost of: 1) packing args into Array 2) RMethod.invoke */ override val costKind = FixedCost(JitCost(4)) } diff --git a/sigmastate/src/main/scala/sigmastate/lang/Types.scala b/interpreter/src/main/scala/sigmastate/lang/Types.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/Types.scala rename to interpreter/src/main/scala/sigmastate/lang/Types.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/exceptions/ConstraintFailed.scala b/interpreter/src/main/scala/sigmastate/lang/exceptions/ConstraintFailed.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/exceptions/ConstraintFailed.scala rename to interpreter/src/main/scala/sigmastate/lang/exceptions/ConstraintFailed.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/exceptions/Exceptions.scala b/interpreter/src/main/scala/sigmastate/lang/exceptions/Exceptions.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/exceptions/Exceptions.scala rename to interpreter/src/main/scala/sigmastate/lang/exceptions/Exceptions.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/exceptions/InvalidArguments.scala b/interpreter/src/main/scala/sigmastate/lang/exceptions/InvalidArguments.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/exceptions/InvalidArguments.scala rename to interpreter/src/main/scala/sigmastate/lang/exceptions/InvalidArguments.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/exceptions/SigmaSerializerExceptions.scala b/interpreter/src/main/scala/sigmastate/lang/exceptions/SigmaSerializerExceptions.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/exceptions/SigmaSerializerExceptions.scala rename to interpreter/src/main/scala/sigmastate/lang/exceptions/SigmaSerializerExceptions.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/exceptions/SigmaTyperExceptions.scala b/interpreter/src/main/scala/sigmastate/lang/exceptions/SigmaTyperExceptions.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/exceptions/SigmaTyperExceptions.scala rename to interpreter/src/main/scala/sigmastate/lang/exceptions/SigmaTyperExceptions.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/syntax/Basic.scala b/interpreter/src/main/scala/sigmastate/lang/syntax/Basic.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/syntax/Basic.scala rename to interpreter/src/main/scala/sigmastate/lang/syntax/Basic.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/syntax/Core.scala b/interpreter/src/main/scala/sigmastate/lang/syntax/Core.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/syntax/Core.scala rename to interpreter/src/main/scala/sigmastate/lang/syntax/Core.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/syntax/Exprs.scala b/interpreter/src/main/scala/sigmastate/lang/syntax/Exprs.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/syntax/Exprs.scala rename to interpreter/src/main/scala/sigmastate/lang/syntax/Exprs.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/syntax/Identifiers.scala b/interpreter/src/main/scala/sigmastate/lang/syntax/Identifiers.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/syntax/Identifiers.scala rename to interpreter/src/main/scala/sigmastate/lang/syntax/Identifiers.scala diff --git a/sigmastate/src/main/scala/sigmastate/lang/syntax/Literals.scala b/interpreter/src/main/scala/sigmastate/lang/syntax/Literals.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/lang/syntax/Literals.scala rename to interpreter/src/main/scala/sigmastate/lang/syntax/Literals.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ApplySerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/ApplySerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ApplySerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/ApplySerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/BlockValueSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/BlockValueSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/BlockValueSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/BlockValueSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/BoolToSigmaPropSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/BoolToSigmaPropSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/BoolToSigmaPropSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/BoolToSigmaPropSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/CaseObjectSerialization.scala b/interpreter/src/main/scala/sigmastate/serialization/CaseObjectSerialization.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/CaseObjectSerialization.scala rename to interpreter/src/main/scala/sigmastate/serialization/CaseObjectSerialization.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ConcreteCollectionBooleanConstantSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/ConcreteCollectionBooleanConstantSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ConcreteCollectionBooleanConstantSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/ConcreteCollectionBooleanConstantSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ConcreteCollectionSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/ConcreteCollectionSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ConcreteCollectionSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/ConcreteCollectionSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ConstantPlaceholderSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/ConstantPlaceholderSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ConstantPlaceholderSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/ConstantPlaceholderSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ConstantSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/ConstantSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ConstantSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/ConstantSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ConstantStore.scala b/interpreter/src/main/scala/sigmastate/serialization/ConstantStore.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ConstantStore.scala rename to interpreter/src/main/scala/sigmastate/serialization/ConstantStore.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/CreateAvlTreeSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/CreateAvlTreeSerializer.scala similarity index 97% rename from sigmastate/src/main/scala/sigmastate/serialization/CreateAvlTreeSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/CreateAvlTreeSerializer.scala index ecbb37040e..efd84f38b6 100644 --- a/sigmastate/src/main/scala/sigmastate/serialization/CreateAvlTreeSerializer.scala +++ b/interpreter/src/main/scala/sigmastate/serialization/CreateAvlTreeSerializer.scala @@ -8,7 +8,6 @@ import sigmastate.Values._ import sigmastate.lang.Terms.ValueOps import sigmastate.utils.SigmaByteWriter.DataInfo -// TODO refactor: remove not used case class CreateAvlTreeSerializer( cons: (ByteValue, Value[SByteArray], IntValue, Value[SIntOption]) => AvlTreeValue ) diff --git a/sigmastate/src/main/scala/sigmastate/serialization/DataJsonEncoder.scala b/interpreter/src/main/scala/sigmastate/serialization/DataJsonEncoder.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/DataJsonEncoder.scala rename to interpreter/src/main/scala/sigmastate/serialization/DataJsonEncoder.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/DataSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/DataSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/DataSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/DataSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ErgoTreeSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/ErgoTreeSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ErgoTreeSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/ErgoTreeSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/FuncValueSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/FuncValueSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/FuncValueSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/FuncValueSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/GetVarSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/GetVarSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/GetVarSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/GetVarSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/GroupElementSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/GroupElementSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/GroupElementSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/GroupElementSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/LogicalNotSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/LogicalNotSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/LogicalNotSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/LogicalNotSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/MethodCallSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/MethodCallSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/MethodCallSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/MethodCallSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ModQArithOpSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/ModQArithOpSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ModQArithOpSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/ModQArithOpSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ModQSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/ModQSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ModQSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/ModQSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/OneArgumentOperationSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/OneArgumentOperationSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/OneArgumentOperationSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/OneArgumentOperationSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/OpCodes.scala b/interpreter/src/main/scala/sigmastate/serialization/OpCodes.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/OpCodes.scala rename to interpreter/src/main/scala/sigmastate/serialization/OpCodes.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/OptionGetOrElseSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/OptionGetOrElseSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/OptionGetOrElseSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/OptionGetOrElseSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/PropertyCallSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/PropertyCallSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/PropertyCallSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/PropertyCallSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ProveDlogSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/ProveDlogSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ProveDlogSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/ProveDlogSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/SelectFieldSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/SelectFieldSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/SelectFieldSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/SelectFieldSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/SigmaPropBytesSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/SigmaPropBytesSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/SigmaPropBytesSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/SigmaPropBytesSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/SigmaPropIsProvenSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/SigmaPropIsProvenSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/SigmaPropIsProvenSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/SigmaPropIsProvenSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/SigmaSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/SigmaSerializer.scala similarity index 80% rename from sigmastate/src/main/scala/sigmastate/serialization/SigmaSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/SigmaSerializer.scala index 5af0082333..38c96f8636 100644 --- a/sigmastate/src/main/scala/sigmastate/serialization/SigmaSerializer.scala +++ b/interpreter/src/main/scala/sigmastate/serialization/SigmaSerializer.scala @@ -10,11 +10,8 @@ import sigmastate.utils._ import scorex.util.serialization._ import sigmastate.serialization.OpCodes.OpCode -import scala.reflect.ClassTag - object SigmaSerializer { type Position = Int - type Consumed = Int val MaxPropositionSize: Int = SigmaConstants.MaxPropositionBytes.value val MaxTreeDepth: Int = SigmaConstants.MaxTreeDepth.value @@ -73,24 +70,6 @@ object SigmaSerializer { abstract class SigmaSerializer[TFamily, T <: TFamily] extends Serializer[TFamily, T, SigmaByteReader, SigmaByteWriter] { - /** Wraps the given writer in SigmaByteWriter and delegates to [[serialize]]. - * NOTE: it is used in spam tests. - */ - def serializeWithGenericWriter(obj: T, w: Writer): Unit = { - serialize(obj, new SigmaByteWriter(w, None)) - } - - /** Wraps the given reader in SigmaByteReader and delegates to [[parse]]. - * NOTE: it is used in spam tests. - */ - def parseWithGenericReader(r: Reader)(implicit vs: SigmaValidationSettings): TFamily = { - val sigmaByteReader = new SigmaByteReader(r, - new ConstantStore(), - resolvePlaceholdersToConstants = false, - maxTreeDepth = SigmaSerializer.MaxTreeDepth) - parse(sigmaByteReader) - } - def error(msg: String) = throw new SerializerException(msg, None) final def toBytes(obj: T): Array[Byte] = { diff --git a/sigmastate/src/main/scala/sigmastate/serialization/SubstConstantsSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/SubstConstantsSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/SubstConstantsSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/SubstConstantsSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/TaggedVariableSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/TaggedVariableSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/TaggedVariableSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/TaggedVariableSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/TupleSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/TupleSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/TupleSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/TupleSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/TwoArgumentsSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/TwoArgumentsSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/TwoArgumentsSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/TwoArgumentsSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/TypeSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/TypeSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/TypeSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/TypeSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ValDefSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/ValDefSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ValDefSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/ValDefSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ValDefTypeStore.scala b/interpreter/src/main/scala/sigmastate/serialization/ValDefTypeStore.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ValDefTypeStore.scala rename to interpreter/src/main/scala/sigmastate/serialization/ValDefTypeStore.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ValUseSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/ValUseSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ValUseSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/ValUseSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ValueSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/ValueSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/ValueSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/ValueSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/AppendSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/AppendSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/AppendSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/AppendSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/AtLeastSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/AtLeastSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/AtLeastSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/AtLeastSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/BooleanTransformerSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/BooleanTransformerSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/BooleanTransformerSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/BooleanTransformerSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/ByIndexSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/ByIndexSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/ByIndexSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/ByIndexSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/DeserializeContextSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/DeserializeContextSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/DeserializeContextSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/DeserializeContextSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/DeserializeRegisterSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/DeserializeRegisterSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/DeserializeRegisterSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/DeserializeRegisterSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/ExtractRegisterAsSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/ExtractRegisterAsSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/ExtractRegisterAsSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/ExtractRegisterAsSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/FilterSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/FilterSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/FilterSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/FilterSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/FoldSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/FoldSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/FoldSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/FoldSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/LogicalTransformerSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/LogicalTransformerSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/LogicalTransformerSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/LogicalTransformerSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/MapCollectionSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/MapCollectionSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/MapCollectionSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/MapCollectionSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/NumericCastSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/NumericCastSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/NumericCastSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/NumericCastSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/ProveDHTupleSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/ProveDHTupleSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/ProveDHTupleSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/ProveDHTupleSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/SigmaTransformerSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/SigmaTransformerSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/SigmaTransformerSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/SigmaTransformerSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/SimpleTransformerSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/SimpleTransformerSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/SimpleTransformerSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/SimpleTransformerSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/transformers/SliceSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/transformers/SliceSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/transformers/SliceSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/transformers/SliceSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/trees/QuadrupleSerializer.scala b/interpreter/src/main/scala/sigmastate/serialization/trees/QuadrupleSerializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/trees/QuadrupleSerializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/trees/QuadrupleSerializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/serialization/trees/Relation2Serializer.scala b/interpreter/src/main/scala/sigmastate/serialization/trees/Relation2Serializer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/serialization/trees/Relation2Serializer.scala rename to interpreter/src/main/scala/sigmastate/serialization/trees/Relation2Serializer.scala diff --git a/sigmastate/src/main/scala/sigmastate/sigmastate.scala b/interpreter/src/main/scala/sigmastate/sigmastate.scala similarity index 98% rename from sigmastate/src/main/scala/sigmastate/sigmastate.scala rename to interpreter/src/main/scala/sigmastate/sigmastate.scala index 32d3600cd4..a8c2bb1a3e 100644 --- a/sigmastate/src/main/scala/sigmastate/sigmastate.scala +++ b/interpreter/src/main/scala/sigmastate/sigmastate.scala @@ -1,4 +1,4 @@ -import sigmastate.Values.Value +import sigmastate.Values._ import sigmastate.lang.CheckingSigmaBuilder package object sigmastate { @@ -77,4 +77,5 @@ package object sigmastate { def MinusModQ(left: Value[SBigInt.type], right: Value[SBigInt.type]): Value[SBigInt.type] = mkMinusModQ(left, right) + } diff --git a/sigmastate/src/main/scala/sigmastate/trees.scala b/interpreter/src/main/scala/sigmastate/trees.scala similarity index 99% rename from sigmastate/src/main/scala/sigmastate/trees.scala rename to interpreter/src/main/scala/sigmastate/trees.scala index 841b63610f..432b65762f 100644 --- a/sigmastate/src/main/scala/sigmastate/trees.scala +++ b/interpreter/src/main/scala/sigmastate/trees.scala @@ -204,7 +204,7 @@ object CreateProveDlog extends FixedCostValueCompanion { val OpType = SFunc(SGroupElement, SSigmaProp) } -// TODO refactor: remove not used class +// TODO v6.0: implement `eval` method and add support in GraphBuilding /** Construct a new authenticated dictionary with given parameters and tree root digest.*/ case class CreateAvlTree(operationFlags: ByteValue, digest: Value[SByteArray], diff --git a/sigmastate/src/main/scala/sigmastate/types.scala b/interpreter/src/main/scala/sigmastate/types.scala similarity index 97% rename from sigmastate/src/main/scala/sigmastate/types.scala rename to interpreter/src/main/scala/sigmastate/types.scala index 1b49ba0dbd..384f1b3b89 100644 --- a/sigmastate/src/main/scala/sigmastate/types.scala +++ b/interpreter/src/main/scala/sigmastate/types.scala @@ -1,19 +1,17 @@ package sigmastate -import java.lang.reflect.Method import java.math.BigInteger - import org.ergoplatform._ import org.ergoplatform.validation._ import scalan.{Nullable, RType} import scalan.RType.GeneralType -import sigmastate.SType.{TypeCode, AnyOps} +import sigmastate.SType.{AnyOps, TypeCode} import sigmastate.interpreter._ import sigmastate.utils.Overloading.Overload1 import sigmastate.utils.SparseArrayContainer import scalan.util.Extensions._ import scorex.crypto.authds.{ADKey, ADValue} -import scorex.crypto.authds.avltree.batch.{Lookup, Insert, Update, Remove} +import scorex.crypto.authds.avltree.batch.{Insert, Lookup, Remove, Update} import scorex.crypto.hash.Blake2b256 import sigmastate.Values._ import sigmastate.lang.Terms._ @@ -23,22 +21,21 @@ import sigmastate.interpreter.CryptoConstants.{EcPointType, hashLength} import sigmastate.serialization.OpCodes import special.collection.Coll import special.sigma._ + import scala.language.implicitConversions import scala.reflect.{ClassTag, classTag} import scala.collection.compat.immutable.ArraySeq -import sigmastate.SMethod.{InvokeDescBuilder, MethodCostFunc, givenCost, javaMethodOf, MethodCallIrBuilder} -import sigmastate.utxo.ByIndex -import sigmastate.utxo.ExtractCreationInfo +import sigmastate.SMethod.{InvokeDescBuilder, MethodCallIrBuilder, MethodCostFunc, givenCost, javaMethodOf} import sigmastate.utxo._ -import special.sigma.{Header, Box, SigmaProp, AvlTree, SigmaDslBuilder, PreHeader} import sigmastate.lang.SigmaTyper.STypeSubst import sigmastate.eval.Evaluation.stypeToRType import sigmastate.eval._ import sigmastate.lang.exceptions.MethodNotFound import debox.cfor +import scalan.reflection.{RClass, RMethod, CommonReflection} import scala.collection.mutable -import scala.util.{Success, Failure} +import scala.util.{Failure, Success} /** Base type for all AST nodes of sigma lang. */ trait SigmaNode extends Product @@ -301,6 +298,8 @@ object SType { * @see SInt, SGroupElement, SType */ trait STypeCompanion { + /** Force initialization of reflection. */ + val reflection = InterpreterReflection /** Type identifier to use in method serialization */ def typeId: Byte @@ -345,8 +344,11 @@ trait STypeCompanion { 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 reflection [[java.lang.reflect.Method]].invoke(). */ - def reprClass: Class[_] + * 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 @@ -425,9 +427,9 @@ object OperationInfo { * @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[Method], - invokeDescsBuilder: Option[InvokeDescBuilder] + irBuilder: Option[PartialFunction[(SigmaBuilder, SValue, SMethod, Seq[SValue], STypeSubst), SValue]], + javaMethod: Option[RMethod], + invokeDescsBuilder: Option[InvokeDescBuilder] ) /** Represents method descriptor. @@ -457,10 +459,10 @@ case class SMethod( /** Operation descriptor of this method. */ lazy val opDesc = MethodDesc(this) - /** Finds and keeps the [[Method]] instance which corresponds to this method descriptor. + /** 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: Method = { + lazy val javaMethod: RMethod = { irInfo.javaMethod.getOrElse { val paramTypes = stype.tDom.drop(1).map(t => t match { case _: STypeVar => classOf[AnyRef] @@ -487,7 +489,7 @@ case class SMethod( /** 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): AnyRef = { + def invokeFixed(obj: Any, args: Array[Any])(implicit E: ErgoTreeEvaluator): Any = { javaMethod.invoke(obj, args.asInstanceOf[Array[AnyRef]]:_*) } @@ -497,11 +499,11 @@ case class SMethod( objType.getMethodById(methodId).get } - /** Returns Java refection [[Method]] which must be invoked to evaluate this method. + /** 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: Method = { + lazy val evalMethod: RMethod = { val argTypes = stype.tDom val nArgs = argTypes.length val paramTypes = new Array[Class[_]](nArgs + 2) @@ -520,9 +522,9 @@ case class SMethod( val methodName = name + "_eval" val m = try { - objType.getClass().getMethod(methodName, paramTypes:_*) + objType.thisRClass.getMethod(methodName, paramTypes:_*) } - catch { case e: MethodNotFound => + catch { case e: NoSuchMethodException => throw new RuntimeException(s"Cannot find eval method def $methodName(${Seq(paramTypes:_*)})", e) } m @@ -580,7 +582,7 @@ case class SMethod( /** 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: Method = null, + javaMethod: RMethod = null, invokeHandler: InvokeDescBuilder = null): SMethod = { this.copy(irInfo = MethodIRInfo(Some(irBuilder), Option(javaMethod), Option(invokeHandler))) } @@ -648,8 +650,8 @@ object SMethod { * @param cA1 the class of the method argument */ def javaMethodOf[T, A1](methodName: String) - (implicit cT: ClassTag[T], cA1: ClassTag[A1]): Method = - cT.runtimeClass.getMethod(methodName, cA1.runtimeClass) + (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 @@ -659,8 +661,8 @@ object SMethod { */ def javaMethodOf[T, A1, A2] (methodName: String) - (implicit cT: ClassTag[T], cA1: ClassTag[A1], cA2: ClassTag[A2]): Method = - cT.runtimeClass.getMethod(methodName, cA1.runtimeClass, cA2.runtimeClass) + (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] = { @@ -791,7 +793,7 @@ object SNumericType extends STypeCompanion { override def typeId: TypeCode = 106: Byte /** Since this object is not used in SMethod instances. */ - override def reprClass: Class[_] = sys.error(s"Shouldn't be called.") + override def reprClass: RClass[_] = sys.error(s"Shouldn't be called.") /** Type variable used in generic signatures of method descriptors. */ val tNum = STypeVar("TNum") @@ -908,7 +910,7 @@ case object SBoolean extends SPrimType with SEmbeddable with SLogical with SProd override type WrappedType = Boolean override val typeCode: TypeCode = 1: Byte override def typeId = typeCode - override val reprClass: Class[_] = classOf[Boolean] + override val reprClass: RClass[_] = RClass(classOf[Boolean]) val ToByte = "toByte" protected override def getMethods() = super.getMethods() @@ -924,7 +926,7 @@ case object SBoolean extends SPrimType with SEmbeddable with SLogical with SProd case object SByte extends SPrimType with SEmbeddable with SNumericType with SMonoType { override type WrappedType = Byte override val typeCode: TypeCode = 2: Byte - override val reprClass: Class[_] = classOf[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 { @@ -944,7 +946,7 @@ case object SByte extends SPrimType with SEmbeddable with SNumericType with SMon case object SShort extends SPrimType with SEmbeddable with SNumericType with SMonoType { override type WrappedType = Short override val typeCode: TypeCode = 3: Byte - override val reprClass: Class[_] = classOf[Short] + override val reprClass: RClass[_] = RClass(classOf[Short]) override def typeId = typeCode override def numericTypeIndex: Int = 1 override def upcast(v: AnyVal): Short = v match { @@ -964,7 +966,7 @@ case object SShort extends SPrimType with SEmbeddable with SNumericType with SMo case object SInt extends SPrimType with SEmbeddable with SNumericType with SMonoType { override type WrappedType = Int override val typeCode: TypeCode = 4: Byte - override val reprClass: Class[_] = classOf[Int] + override val reprClass: RClass[_] = RClass(classOf[Int]) override def typeId = typeCode override def numericTypeIndex: Int = 2 override def upcast(v: AnyVal): Int = v match { @@ -986,7 +988,7 @@ case object SInt extends SPrimType with SEmbeddable with SNumericType with SMono case object SLong extends SPrimType with SEmbeddable with SNumericType with SMonoType { override type WrappedType = Long override val typeCode: TypeCode = 5: Byte - override val reprClass: Class[_] = classOf[Long] + override val reprClass: RClass[_] = RClass(classOf[Long]) override def typeId = typeCode override def numericTypeIndex: Int = 3 override def upcast(v: AnyVal): Long = v match { @@ -1009,7 +1011,7 @@ case object SLong extends SPrimType with SEmbeddable with SNumericType with SMon case object SBigInt extends SPrimType with SEmbeddable with SNumericType with SMonoType { override type WrappedType = BigInt override val typeCode: TypeCode = 6: Byte - override val reprClass: Class[_] = classOf[BigInt] + override val reprClass: RClass[_] = RClass(classOf[BigInt]) override def typeId = typeCode @@ -1072,7 +1074,7 @@ case object SString extends SProduct with SMonoType { override type WrappedType = String override val typeCode: TypeCode = 102: Byte override def typeId = typeCode - override def reprClass: Class[_] = classOf[String] + override def reprClass: RClass[_] = RClass(classOf[String]) } /** Descriptor of ErgoTree type `GroupElement`. @@ -1080,7 +1082,7 @@ case object SString extends SProduct with SMonoType { case object SGroupElement extends SProduct with SPrimType with SEmbeddable with SMonoType { override type WrappedType = GroupElement override val typeCode: TypeCode = 7: Byte - override val reprClass: Class[_] = classOf[GroupElement] + override val reprClass: RClass[_] = RClass(classOf[GroupElement]) override def typeId = typeCode @@ -1134,7 +1136,7 @@ case object SSigmaProp extends SProduct with SPrimType with SEmbeddable with SLo import SType._ override type WrappedType = SigmaProp override val typeCode: TypeCode = 8: Byte - override val reprClass: Class[_] = classOf[SigmaProp] + override val reprClass: RClass[_] = RClass(classOf[SigmaProp]) override def typeId = typeCode /** The maximum size of SigmaProp value in serialized byte array representation. */ @@ -1191,7 +1193,7 @@ object SOption extends STypeCompanion { override def typeId = OptionTypeCode - override val reprClass: Class[_] = classOf[Option[_]] + override val reprClass: RClass[_] = RClass(classOf[Option[_]]) type SBooleanOption = SOption[SBoolean.type] type SByteOption = SOption[SByte.type] @@ -1219,7 +1221,6 @@ object SOption extends STypeCompanion { val IsDefined = "isDefined" val Get = "get" val GetOrElse = "getOrElse" - val Fold = "fold" import SType.{tT, tR, paramT, paramR} @@ -1327,7 +1328,7 @@ object SCollectionType { } object SCollection extends STypeCompanion with MethodByNameUnapply { - override val reprClass: Class[_] = classOf[Coll[_]] + override val reprClass: RClass[_] = RClass(classOf[Coll[_]]) override def typeId = SCollectionType.CollectionTypeCode import SType.{tK, tV, paramIV, paramIVSeq, paramOV} @@ -1829,7 +1830,7 @@ object STuple extends STypeCompanion { override def typeId = TupleTypeCode - override val reprClass: Class[_] = classOf[Product2[_,_]] + override val reprClass: RClass[_] = RClass(classOf[Product2[_,_]]) /** A list of Coll methods inherited from Coll type and available as method of tuple. */ lazy val colMethods: Seq[SMethod] = { @@ -1943,7 +1944,7 @@ case object SBox extends SProduct with SPredefType with SMonoType { import ErgoBox._ override type WrappedType = Box override val typeCode: TypeCode = 99: Byte - override val reprClass: Class[_] = classOf[Box] + override val reprClass: RClass[_] = RClass(classOf[Box]) override def typeId = typeCode import SType.{tT, paramT} @@ -2040,13 +2041,15 @@ case object SBox extends SProduct with SPredefType with SMonoType { case object SAvlTree extends SProduct with SPredefType with SMonoType { override type WrappedType = AvlTree override val typeCode: TypeCode = 100: Byte - override val reprClass: Class[_] = classOf[AvlTree] + override val reprClass: RClass[_] = RClass(classOf[AvlTree]) override def typeId = typeCode import SOption._ 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))) .withIRInfo(MethodCallIrBuilder) .withInfo(PropertyCall, @@ -2301,7 +2304,7 @@ case object SAvlTree extends SProduct with SPredefType with SMonoType { * Called via reflection based on naming convention. * @see SMethod.evalMethod */ - def insert_eval(mc: MethodCall, tree: AvlTree, entries: Coll[(Coll[Byte], Coll[Byte])], proof: Coll[Byte]) + def insert_eval(mc: MethodCall, tree: AvlTree, entries: KeyValueColl, proof: Coll[Byte]) (implicit E: ErgoTreeEvaluator): Option[AvlTree] = { E.addCost(isInsertAllowed_Info) if (!tree.isInsertAllowed) { @@ -2357,7 +2360,7 @@ case object SAvlTree extends SProduct with SPredefType with SMonoType { * @see SMethod.evalMethod */ def update_eval(mc: MethodCall, tree: AvlTree, - operations: Coll[(Coll[Byte], Coll[Byte])], proof: Coll[Byte]) + operations: KeyValueColl, proof: Coll[Byte]) (implicit E: ErgoTreeEvaluator): Option[AvlTree] = { E.addCost(isUpdateAllowed_Info) if (!tree.isUpdateAllowed) { @@ -2472,7 +2475,7 @@ case object SAvlTree extends SProduct with SPredefType with SMonoType { case object SContext extends SProduct with SPredefType with SMonoType { override type WrappedType = Context override val typeCode: TypeCode = 101: Byte - override def reprClass: Class[_] = classOf[Context] + override def reprClass: RClass[_] = RClass(classOf[Context]) override def typeId = typeCode /** Arguments on context operation such as getVar, DeserializeContext etc. @@ -2506,7 +2509,7 @@ case object SContext extends SProduct with SPredefType with SMonoType { case object SHeader extends SProduct with SPredefType with SMonoType { override type WrappedType = Header override val typeCode: TypeCode = 104: Byte - override val reprClass: Class[_] = classOf[Header] + override val reprClass: RClass[_] = RClass(classOf[Header]) override def typeId = typeCode lazy val idMethod = propertyCall("id", SByteArray, 1, FixedCost(JitCost(10))) @@ -2536,7 +2539,7 @@ case object SHeader extends SProduct with SPredefType with SMonoType { case object SPreHeader extends SProduct with SPredefType with SMonoType { override type WrappedType = PreHeader override val typeCode: TypeCode = 105: Byte - override val reprClass: Class[_] = classOf[PreHeader] + override val reprClass: RClass[_] = RClass(classOf[PreHeader]) override def typeId = typeCode lazy val versionMethod = propertyCall("version", SByte, 1, FixedCost(JitCost(10))) @@ -2569,7 +2572,7 @@ case object SPreHeader extends SProduct with SPredefType with SMonoType { case object SGlobal extends SProduct with SPredefType with SMonoType { override type WrappedType = SigmaDslBuilder override val typeCode: TypeCode = 106: Byte - override val reprClass: Class[_] = classOf[SigmaDslBuilder] + override val reprClass: RClass[_] = RClass(classOf[SigmaDslBuilder]) override def typeId = typeCode import SType.tT diff --git a/sigmastate/src/main/scala/sigmastate/utils/Extensions.scala b/interpreter/src/main/scala/sigmastate/utils/Extensions.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/utils/Extensions.scala rename to interpreter/src/main/scala/sigmastate/utils/Extensions.scala diff --git a/sigmastate/src/main/scala/sigmastate/utils/Helpers.scala b/interpreter/src/main/scala/sigmastate/utils/Helpers.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/utils/Helpers.scala rename to interpreter/src/main/scala/sigmastate/utils/Helpers.scala diff --git a/sigmastate/src/main/scala/sigmastate/utils/SigmaByteReader.scala b/interpreter/src/main/scala/sigmastate/utils/SigmaByteReader.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/utils/SigmaByteReader.scala rename to interpreter/src/main/scala/sigmastate/utils/SigmaByteReader.scala diff --git a/sigmastate/src/main/scala/sigmastate/utils/SigmaByteWriter.scala b/interpreter/src/main/scala/sigmastate/utils/SigmaByteWriter.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/utils/SigmaByteWriter.scala rename to interpreter/src/main/scala/sigmastate/utils/SigmaByteWriter.scala diff --git a/sigmastate/src/main/scala/sigmastate/utils/SparseArrayContainer.scala b/interpreter/src/main/scala/sigmastate/utils/SparseArrayContainer.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/utils/SparseArrayContainer.scala rename to interpreter/src/main/scala/sigmastate/utils/SparseArrayContainer.scala diff --git a/sigmastate/src/main/scala/sigmastate/utxo/ComplexityTable.scala b/interpreter/src/main/scala/sigmastate/utxo/ComplexityTable.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/utxo/ComplexityTable.scala rename to interpreter/src/main/scala/sigmastate/utxo/ComplexityTable.scala diff --git a/sigmastate/src/main/scala/sigmastate/utxo/ComplexityTableStat.scala b/interpreter/src/main/scala/sigmastate/utxo/ComplexityTableStat.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/utxo/ComplexityTableStat.scala rename to interpreter/src/main/scala/sigmastate/utxo/ComplexityTableStat.scala diff --git a/sigmastate/src/main/scala/sigmastate/utxo/transformers.scala b/interpreter/src/main/scala/sigmastate/utxo/transformers.scala similarity index 100% rename from sigmastate/src/main/scala/sigmastate/utxo/transformers.scala rename to interpreter/src/main/scala/sigmastate/utxo/transformers.scala diff --git a/sigmastate/src/test/scala/org/ergoplatform/EmissionSpec.scala b/interpreter/src/test/scala/org/ergoplatform/EmissionSpec.scala similarity index 100% rename from sigmastate/src/test/scala/org/ergoplatform/EmissionSpec.scala rename to interpreter/src/test/scala/org/ergoplatform/EmissionSpec.scala diff --git a/sigmastate/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala b/interpreter/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala rename to interpreter/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala diff --git a/sigmastate/src/test/scala/org/ergoplatform/ErgoLikeTransactionSpec.scala b/interpreter/src/test/scala/org/ergoplatform/ErgoLikeTransactionSpec.scala similarity index 100% rename from sigmastate/src/test/scala/org/ergoplatform/ErgoLikeTransactionSpec.scala rename to interpreter/src/test/scala/org/ergoplatform/ErgoLikeTransactionSpec.scala diff --git a/sigmastate/src/test/scala/org/ergoplatform/ErgoScriptPredefSpec.scala b/interpreter/src/test/scala/org/ergoplatform/ErgoScriptPredefSpec.scala similarity index 100% rename from sigmastate/src/test/scala/org/ergoplatform/ErgoScriptPredefSpec.scala rename to interpreter/src/test/scala/org/ergoplatform/ErgoScriptPredefSpec.scala diff --git a/sigmastate/src/test/scala/org/ergoplatform/JsonSerializationSpec.scala b/interpreter/src/test/scala/org/ergoplatform/JsonSerializationSpec.scala similarity index 100% rename from sigmastate/src/test/scala/org/ergoplatform/JsonSerializationSpec.scala rename to interpreter/src/test/scala/org/ergoplatform/JsonSerializationSpec.scala diff --git a/sigmastate/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala b/interpreter/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala similarity index 100% rename from sigmastate/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala rename to interpreter/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala diff --git a/sigmastate/src/test/scala/org/ergoplatform/validation/RuleStatusSerializerSpec.scala b/interpreter/src/test/scala/org/ergoplatform/validation/RuleStatusSerializerSpec.scala similarity index 100% rename from sigmastate/src/test/scala/org/ergoplatform/validation/RuleStatusSerializerSpec.scala rename to interpreter/src/test/scala/org/ergoplatform/validation/RuleStatusSerializerSpec.scala diff --git a/sigmastate/src/test/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializerSpec.scala b/interpreter/src/test/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializerSpec.scala similarity index 100% rename from sigmastate/src/test/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializerSpec.scala rename to interpreter/src/test/scala/org/ergoplatform/validation/SigmaValidationSettingsSerializerSpec.scala diff --git a/sigmastate/src/test/scala/org/ergoplatform/validation/ValidationSpecification.scala b/interpreter/src/test/scala/org/ergoplatform/validation/ValidationSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/org/ergoplatform/validation/ValidationSpecification.scala rename to interpreter/src/test/scala/org/ergoplatform/validation/ValidationSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/CalcSha256Specification.scala b/interpreter/src/test/scala/sigmastate/CalcSha256Specification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/CalcSha256Specification.scala rename to interpreter/src/test/scala/sigmastate/CalcSha256Specification.scala diff --git a/sigmastate/src/test/scala/sigmastate/CrossVersionProps.scala b/interpreter/src/test/scala/sigmastate/CrossVersionProps.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/CrossVersionProps.scala rename to interpreter/src/test/scala/sigmastate/CrossVersionProps.scala diff --git a/sigmastate/src/test/scala/sigmastate/ErgoTreeBenchmarks.scala b/interpreter/src/test/scala/sigmastate/ErgoTreeBenchmarks.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/ErgoTreeBenchmarks.scala rename to interpreter/src/test/scala/sigmastate/ErgoTreeBenchmarks.scala diff --git a/sigmastate/src/test/scala/sigmastate/ErgoTreeSpecification.scala b/interpreter/src/test/scala/sigmastate/ErgoTreeSpecification.scala similarity index 99% rename from sigmastate/src/test/scala/sigmastate/ErgoTreeSpecification.scala rename to interpreter/src/test/scala/sigmastate/ErgoTreeSpecification.scala index 38e89b1212..5d7bdad31b 100644 --- a/sigmastate/src/test/scala/sigmastate/ErgoTreeSpecification.scala +++ b/interpreter/src/test/scala/sigmastate/ErgoTreeSpecification.scala @@ -758,7 +758,10 @@ class ErgoTreeSpecification extends SigmaDslTesting with ContractsTestkit { tree match { case ErgoTree(_, _, Right(BlockValueWithInvalidBoolToSigmaProp(_)), _, _, _) => } - SigmaPPrint.pprintln(tree, 150, 300) + val lines = SigmaPPrint.tokenize(tree, 150, 300) + if (printDebugInfo) { + lines.foreach(print); println() + } } } diff --git a/sigmastate/src/test/scala/sigmastate/FailingToProveSpec.scala b/interpreter/src/test/scala/sigmastate/FailingToProveSpec.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/FailingToProveSpec.scala rename to interpreter/src/test/scala/sigmastate/FailingToProveSpec.scala diff --git a/interpreter/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala b/interpreter/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala new file mode 100644 index 0000000000..0487b7c324 --- /dev/null +++ b/interpreter/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala @@ -0,0 +1,54 @@ +package sigmastate + +import org.scalatest.matchers.should.Matchers +import org.scalatest.propspec.AnyPropSpec +import scalan.TypeDescs +import scalan.reflection.CommonReflection.registerClassEntry +import scalan.reflection.SRConstructor + +object ObjA { + class A + object ObjB +} + +class InterpreterReflectionGeneratorTests extends AnyPropSpec with Matchers { + import ReflectionGenerator._ + class ObjB { + class B + } + + def test(name: String, exp: String) = { + val normalized = normalizeName(name) + normalized shouldBe exp + } + + property("sigmastate.ReflectionGenerator") { + test("", "") + test("A", "A") + test("A$", "A$") + test("A$B", "A#B") + test("A$B$", "A#B$") + test("scala.A$B$", "scala.A#B$") + test("sigmastate.ObjA$A", "sigmastate.ObjA.A"); + classOf[ObjA.A] + test("sigmastate.ReflectionGeneratorTests$ObjB$B", "sigmastate.ReflectionGeneratorTests#ObjB#B"); + classOf[InterpreterReflectionGeneratorTests#ObjB#B] + Class.forName("sigmastate.ObjA$") shouldNot be (null) + Class.forName("sigmastate.ObjA$ObjB$") shouldNot be (null) + } + + property("inner class") { + val ctx = null.asInstanceOf[scalan.Library] // ok! type level only + val clazz = classOf[ctx.Coll.CollElem[_, _]] + registerClassEntry(clazz, + constructors = Array( + new SRConstructor[Any](Array(clazz.getDeclaringClass, classOf[TypeDescs#Elem[_]])) { + override def newInstance(args: AnyRef*): Any = { + val cake = args(0).asInstanceOf[ctx.Coll.type] + new cake.CollElem()(args(1).asInstanceOf[ctx.Elem[_]]) + } + } + ) + ) + } +} diff --git a/sigmastate/src/test/scala/sigmastate/JitCostSpecification.scala b/interpreter/src/test/scala/sigmastate/JitCostSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/JitCostSpecification.scala rename to interpreter/src/test/scala/sigmastate/JitCostSpecification.scala diff --git a/interpreter/src/test/scala/sigmastate/ReflectionGenerator.scala b/interpreter/src/test/scala/sigmastate/ReflectionGenerator.scala new file mode 100644 index 0000000000..18a4de53e0 --- /dev/null +++ b/interpreter/src/test/scala/sigmastate/ReflectionGenerator.scala @@ -0,0 +1,189 @@ +package sigmastate + +import scalan.{Base, TypeDescs} + +import scala.collection.mutable +import scalan.reflection._ + +object ReflectionGenerator { + + def normalizeName(name: String): String = { + val len = name.length + val res = new mutable.StringBuilder(len) + var i = 0 + while (i < len) { + var ch = name(i) + if (ch == '$' && i < len - 1) { + val prefix = name.substring(0, i + 1) + ch = try { + Class.forName(prefix) + '.' // prefix is object + } catch { + case t => + '#' // prefix is not object + } + } + res += ch + i += 1 + } + res.result() + } + + val knownPackages = Array( + "scalan.primitives.", + "special.collection.", + "special.sigma.", + "special.wrappers.", + "sigmastate.Values.", + "sigmastate.lang.Terms.", + "sigmastate.interpreter.", + "sigmastate.utxo.", + "sigmastate.", + "wrappers.scala.", + "scalan.", + "scala.collection.", + "scala." + ) + + def stripKnownPackages(name: String): String = { + knownPackages.find(p => name.startsWith(p)) match { + case Some(p) => name.stripPrefix(p) + case None => name + } + } + + def className(c: Class[_], inBody: Boolean): String = { + val name = c match { + case _ if c == classOf[Base#Ref[_]] && inBody => "ctx.Ref" + case _ if c == classOf[TypeDescs#Elem[_]] && inBody => "ctx.Elem" + case _ if c == classOf[scala.Function1[_,_]] && inBody => "Any => Any" + case _ => stripKnownPackages(normalizeName(c.getName)) + } + name + } + + def classExpr(c: Class[_], inBody: Boolean): String = { + if (c.isArray) + s"Array[${classExpr(c.getComponentType, inBody)}]" + else if (c == classOf[Boolean]) "Boolean" + else if (c == classOf[Byte]) "Byte" + else if (c == classOf[Short]) "Short" + else if (c == classOf[Int]) "Int" + else if (c == classOf[Long]) "Long" + else if (!c.getTypeParameters.isEmpty) + s"${className(c, inBody)}[${c.getTypeParameters.map(_ => "_").mkString(",")}]" + else + className(c, inBody) + } + + def genEmptyClass(c: JRClass[_]): String = { + val name = classExpr(c.value, false) + s"registerClassEntry(classOf[$name])\n" + } + + def genConstructor(c: JRClass[_], ctor: JRConstructor[_]): String = { + val params = ctor.getParameterTypes() + .map(p => s"classOf[${classExpr(p, false)}]") + .mkString(", ") + val clsName = stripKnownPackages(c.getName) + val args = ctor.getParameterTypes() + .zipWithIndex + .map { case (p, i) => s"args($i).asInstanceOf[${classExpr(p, true)}]" } + .mkString(", ") + s""" mkConstructor(Array($params)) { args => + | new $clsName($args) + | }""".stripMargin + } + + def genField(c: JRClass[_], f: JRField): String = { + f.toString + } + + def genMethod(c: JRClass[_], m: JRMethod): String = { + val name = m.getName + val params = m.getParameterTypes() + .map(p => s"classOf[${classExpr(p, false)}]") + .mkString(", ") + val args = m.getParameterTypes() + .zipWithIndex + .map { case (p, i) => s"args($i).asInstanceOf[${classExpr(p, true)}]" } + .mkString(", ") + s""" mkMethod(clazz, "$name", Array[Class[_]]($params)) { (obj, args) => + | obj.asInstanceOf[${classExpr(c.value, true)}].$name($args) + | }""".stripMargin + } + + def genClassRegistrationEntry(c: JRClass[_]): String = { + val name = classExpr(c.value, false) + val cs = c.getUsedConstructors() + val constructors = if (cs.isEmpty) "" + else { + s""", + | constructors = Array( + |${cs.map(genConstructor(c, _)).mkString(",\n")} + | )""".stripMargin + } + val fields = if (c.fields.isEmpty) "" + else { + s""", + | fields = Map( + | ${c.fields.map { case (_, f: JRField) => genField(c, f) }.mkString(",\n")} + | )""".stripMargin + } + val methods = if (c.methods.isEmpty) "" + else { + s""", + | methods = Map( + | ${c.methods.map { case (_, m: JRMethod) => genMethod(c, m) }.mkString(",\n")} + | )""".stripMargin + } + if (c.fields.isEmpty && c.methods.isEmpty) { + s""" + |registerClassEntry(classOf[$name]${constructors}${fields}${methods} + |) + |""".stripMargin + } else { + s""" + |{ val clazz = classOf[$name] + | registerClassEntry(clazz${constructors}${fields}${methods} + | ) + |} + |""".stripMargin + } + } + + def isEmpty(rcls: JRClass[_]): Boolean = + (rcls.constructors == null || rcls.constructors.isEmpty) && rcls.fields.isEmpty && rcls.methods.isEmpty + + def genClass(cls: Class[_], rcls: JRClass[_], b: mutable.StringBuilder) = { + if (isEmpty(rcls)) { + b.append(genEmptyClass(rcls)) + } + else { + b.append(genClassRegistrationEntry(rcls)) + } + } + + def generateReport(): String = { + val b = new mutable.StringBuilder(100) + for ( (cls, rcls) <- collectEmptyClasses.sortBy(_._1.getName) ) { + genClass(cls, rcls, b) + } + for ( (cls, rcls) <- collectNonEmptyClasses.sortBy(_._1.getName) ) { + genClass(cls, rcls, b) + } + b.result() + } + + private def collectEmptyClasses = { + Platform.unknownClasses.toSeq.filter(e => + isEmpty(e._2) && // don't contain constructors, fields or methods + !CommonReflection.classes.contains(e._1)) // not already registered + } + + private def collectNonEmptyClasses = { + Platform.unknownClasses.toSeq.filter(e => + !isEmpty(e._2) && + !CommonReflection.classes.contains(e._1)) + } +} diff --git a/sigmastate/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala b/interpreter/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala rename to interpreter/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/SigmaProtocolSpecification.scala b/interpreter/src/test/scala/sigmastate/SigmaProtocolSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/SigmaProtocolSpecification.scala rename to interpreter/src/test/scala/sigmastate/SigmaProtocolSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/SoftForkabilitySpecification.scala b/interpreter/src/test/scala/sigmastate/SoftForkabilitySpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/SoftForkabilitySpecification.scala rename to interpreter/src/test/scala/sigmastate/SoftForkabilitySpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/TestingInterpreterSpecification.scala b/interpreter/src/test/scala/sigmastate/TestingInterpreterSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/TestingInterpreterSpecification.scala rename to interpreter/src/test/scala/sigmastate/TestingInterpreterSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/TestsBase.scala b/interpreter/src/test/scala/sigmastate/TestsBase.scala similarity index 94% rename from sigmastate/src/test/scala/sigmastate/TestsBase.scala rename to interpreter/src/test/scala/sigmastate/TestsBase.scala index 8e7425cd1f..5d2f28e074 100644 --- a/sigmastate/src/test/scala/sigmastate/TestsBase.scala +++ b/interpreter/src/test/scala/sigmastate/TestsBase.scala @@ -14,6 +14,11 @@ import sigmastate.serialization.ValueSerializer import scala.util.DynamicVariable trait TestsBase extends Matchers with VersionTesting { + /** Set this to true to enable debug console output in tests */ + val printDebugInfo: Boolean = false + + /** Print debug message if printDebugInfo is true */ + def printDebug(msg: Any): Unit = if (printDebugInfo) println(msg) /** Current ErgoTree header flags assigned dynamically using [[CrossVersionProps]] and * ergoTreeVersionInTests. diff --git a/sigmastate/src/test/scala/sigmastate/TypesSpecification.scala b/interpreter/src/test/scala/sigmastate/TypesSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/TypesSpecification.scala rename to interpreter/src/test/scala/sigmastate/TypesSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/crypto/GF2_192_Specification.scala b/interpreter/src/test/scala/sigmastate/crypto/GF2_192_Specification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/crypto/GF2_192_Specification.scala rename to interpreter/src/test/scala/sigmastate/crypto/GF2_192_Specification.scala diff --git a/sigmastate/src/test/scala/sigmastate/crypto/GroupLawsSpecification.scala b/interpreter/src/test/scala/sigmastate/crypto/GroupLawsSpecification.scala similarity index 98% rename from sigmastate/src/test/scala/sigmastate/crypto/GroupLawsSpecification.scala rename to interpreter/src/test/scala/sigmastate/crypto/GroupLawsSpecification.scala index b5b0b8b33b..7b998a22ac 100644 --- a/sigmastate/src/test/scala/sigmastate/crypto/GroupLawsSpecification.scala +++ b/interpreter/src/test/scala/sigmastate/crypto/GroupLawsSpecification.scala @@ -56,7 +56,7 @@ class GroupLawsSpecification extends SigmaTestingCommons { private def printPoints(points: Seq[(String, Any)]) = { points.foreach { case (name, p) => - println(s"val $name = ${SigmaPPrint.apply(p).plainText}") + printDebug(s"val $name = ${SigmaPPrint.apply(p).plainText}") } } diff --git a/sigmastate/src/test/scala/sigmastate/crypto/SigningSpecification.scala b/interpreter/src/test/scala/sigmastate/crypto/SigningSpecification.scala similarity index 96% rename from sigmastate/src/test/scala/sigmastate/crypto/SigningSpecification.scala rename to interpreter/src/test/scala/sigmastate/crypto/SigningSpecification.scala index 8550d64cb3..7a49eeeae5 100644 --- a/sigmastate/src/test/scala/sigmastate/crypto/SigningSpecification.scala +++ b/interpreter/src/test/scala/sigmastate/crypto/SigningSpecification.scala @@ -184,12 +184,12 @@ class SigningSpecification extends SigmaTestingCommons { val tree = mkTestErgoTree(prop) val prove = proverA.prove(tree, fakeContext, msg).get - println(s"Message: ${Base16.encode(msg)}") - println(s"sk: ${sk.w}") - println(s"sk(Base16): ${Base16.encode(sk.w.toByteArray)}") - println(s"pkBytes: ${Base16.encode(prop.pkBytes)}") - println(s"treeBytes: ${Base16.encode(tree.bytes)}") - println(s"Signature: ${Base16.encode(prove.proof)}") + printDebug(s"Message: ${Base16.encode(msg)}") + printDebug(s"sk: ${sk.w}") + printDebug(s"sk(Base16): ${Base16.encode(sk.w.toByteArray)}") + printDebug(s"pkBytes: ${Base16.encode(prop.pkBytes)}") + printDebug(s"treeBytes: ${Base16.encode(tree.bytes)}") + printDebug(s"Signature: ${Base16.encode(prove.proof)}") } private def printThresholdSignature(msg: Array[Byte]) { @@ -203,11 +203,11 @@ class SigningSpecification extends SigmaTestingCommons { val prop = AtLeast(2, sk1.publicImage, sk2.publicImage, sk3.publicImage) val prove = proverA.prove(mkTestErgoTree(prop), fakeContext, msg).get - println(s"Message: ${Base16.encode(msg)}") - println(s"sk1: ${sk1.w}") - println(s"sk2: ${sk2.w}") - println(s"sk3: ${sk3.w}") - println(s"Signature: ${Base16.encode(prove.proof)}") + printDebug(s"Message: ${Base16.encode(msg)}") + printDebug(s"sk1: ${sk1.w}") + printDebug(s"sk2: ${sk2.w}") + printDebug(s"sk3: ${sk3.w}") + printDebug(s"Signature: ${Base16.encode(prove.proof)}") } } diff --git a/sigmastate/src/test/scala/sigmastate/eval/BasicOpsTests.scala b/interpreter/src/test/scala/sigmastate/eval/BasicOpsTests.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/eval/BasicOpsTests.scala rename to interpreter/src/test/scala/sigmastate/eval/BasicOpsTests.scala diff --git a/sigmastate/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala b/interpreter/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala rename to interpreter/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala diff --git a/sigmastate/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala b/interpreter/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala rename to interpreter/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala diff --git a/sigmastate/src/test/scala/sigmastate/eval/EvaluationTest.scala b/interpreter/src/test/scala/sigmastate/eval/EvaluationTest.scala similarity index 97% rename from sigmastate/src/test/scala/sigmastate/eval/EvaluationTest.scala rename to interpreter/src/test/scala/sigmastate/eval/EvaluationTest.scala index 9edc4a33d6..fa87615de7 100644 --- a/sigmastate/src/test/scala/sigmastate/eval/EvaluationTest.scala +++ b/interpreter/src/test/scala/sigmastate/eval/EvaluationTest.scala @@ -80,10 +80,10 @@ class EvaluationTest extends BaseCtxTests test("Measure IRContext creation speed") { var ctx: RuntimeIRContext = new RuntimeIRContext - measure(100) { i => + measure(100, okShowIterTime = printDebugInfo, okShowTotalTime = printDebugInfo) { i => ctx = new RuntimeIRContext } - println(s"Def count: ${ctx.defCount}") + printDebug(s"Def count: ${ctx.defCount}") /* Iter 0: 4 ms ... diff --git a/sigmastate/src/test/scala/sigmastate/eval/ExampleContracts.scala b/interpreter/src/test/scala/sigmastate/eval/ExampleContracts.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/eval/ExampleContracts.scala rename to interpreter/src/test/scala/sigmastate/eval/ExampleContracts.scala diff --git a/sigmastate/src/test/scala/sigmastate/eval/MeasureIRContext.scala b/interpreter/src/test/scala/sigmastate/eval/MeasureIRContext.scala similarity index 94% rename from sigmastate/src/test/scala/sigmastate/eval/MeasureIRContext.scala rename to interpreter/src/test/scala/sigmastate/eval/MeasureIRContext.scala index 2308fa252a..267fee8eff 100644 --- a/sigmastate/src/test/scala/sigmastate/eval/MeasureIRContext.scala +++ b/interpreter/src/test/scala/sigmastate/eval/MeasureIRContext.scala @@ -11,7 +11,7 @@ object MeasureIRContext extends App { measure(10000, false) { i => ctx = new RuntimeIRContext } - println(s"Def count: ${ctx.defCount}") + print(s"Def count: ${ctx.defCount}") /* Total time: 2485 ms Total time: 2714 ms diff --git a/sigmastate/src/test/scala/sigmastate/helpers/ContextEnrichingProverInterpreter.scala b/interpreter/src/test/scala/sigmastate/helpers/ContextEnrichingProverInterpreter.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/helpers/ContextEnrichingProverInterpreter.scala rename to interpreter/src/test/scala/sigmastate/helpers/ContextEnrichingProverInterpreter.scala diff --git a/sigmastate/src/test/scala/sigmastate/helpers/ContextEnrichingTestProvingInterpreter.scala b/interpreter/src/test/scala/sigmastate/helpers/ContextEnrichingTestProvingInterpreter.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/helpers/ContextEnrichingTestProvingInterpreter.scala rename to interpreter/src/test/scala/sigmastate/helpers/ContextEnrichingTestProvingInterpreter.scala diff --git a/sigmastate/src/test/scala/sigmastate/helpers/ErgoLikeContextTesting.scala b/interpreter/src/test/scala/sigmastate/helpers/ErgoLikeContextTesting.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/helpers/ErgoLikeContextTesting.scala rename to interpreter/src/test/scala/sigmastate/helpers/ErgoLikeContextTesting.scala diff --git a/sigmastate/src/test/scala/sigmastate/helpers/ErgoLikeTestProvingInterpreter.scala b/interpreter/src/test/scala/sigmastate/helpers/ErgoLikeTestProvingInterpreter.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/helpers/ErgoLikeTestProvingInterpreter.scala rename to interpreter/src/test/scala/sigmastate/helpers/ErgoLikeTestProvingInterpreter.scala diff --git a/sigmastate/src/test/scala/sigmastate/helpers/ErgoLikeTransactionTesting.scala b/interpreter/src/test/scala/sigmastate/helpers/ErgoLikeTransactionTesting.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/helpers/ErgoLikeTransactionTesting.scala rename to interpreter/src/test/scala/sigmastate/helpers/ErgoLikeTransactionTesting.scala diff --git a/sigmastate/src/test/scala/sigmastate/helpers/ErgoTransactionValidator.scala b/interpreter/src/test/scala/sigmastate/helpers/ErgoTransactionValidator.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/helpers/ErgoTransactionValidator.scala rename to interpreter/src/test/scala/sigmastate/helpers/ErgoTransactionValidator.scala diff --git a/sigmastate/src/test/scala/sigmastate/helpers/NegativeTesting.scala b/interpreter/src/test/scala/sigmastate/helpers/NegativeTesting.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/helpers/NegativeTesting.scala rename to interpreter/src/test/scala/sigmastate/helpers/NegativeTesting.scala diff --git a/sigmastate/src/test/scala/sigmastate/helpers/SigmaPPrint.scala b/interpreter/src/test/scala/sigmastate/helpers/SigmaPPrint.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/helpers/SigmaPPrint.scala rename to interpreter/src/test/scala/sigmastate/helpers/SigmaPPrint.scala diff --git a/sigmastate/src/test/scala/sigmastate/helpers/SigmaPPrintSpec.scala b/interpreter/src/test/scala/sigmastate/helpers/SigmaPPrintSpec.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/helpers/SigmaPPrintSpec.scala rename to interpreter/src/test/scala/sigmastate/helpers/SigmaPPrintSpec.scala diff --git a/sigmastate/src/test/scala/sigmastate/helpers/SigmaTestingCommons.scala b/interpreter/src/test/scala/sigmastate/helpers/SigmaTestingCommons.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/helpers/SigmaTestingCommons.scala rename to interpreter/src/test/scala/sigmastate/helpers/SigmaTestingCommons.scala diff --git a/sigmastate/src/test/scala/sigmastate/helpers/TestingHelpers.scala b/interpreter/src/test/scala/sigmastate/helpers/TestingHelpers.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/helpers/TestingHelpers.scala rename to interpreter/src/test/scala/sigmastate/helpers/TestingHelpers.scala diff --git a/sigmastate/src/test/scala/sigmastate/lang/LangTests.scala b/interpreter/src/test/scala/sigmastate/lang/LangTests.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/lang/LangTests.scala rename to interpreter/src/test/scala/sigmastate/lang/LangTests.scala diff --git a/sigmastate/src/test/scala/sigmastate/lang/SigmaBinderTest.scala b/interpreter/src/test/scala/sigmastate/lang/SigmaBinderTest.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/lang/SigmaBinderTest.scala rename to interpreter/src/test/scala/sigmastate/lang/SigmaBinderTest.scala diff --git a/sigmastate/src/test/scala/sigmastate/lang/SigmaBuilderTest.scala b/interpreter/src/test/scala/sigmastate/lang/SigmaBuilderTest.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/lang/SigmaBuilderTest.scala rename to interpreter/src/test/scala/sigmastate/lang/SigmaBuilderTest.scala diff --git a/sigmastate/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala b/interpreter/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala rename to interpreter/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala diff --git a/sigmastate/src/test/scala/sigmastate/lang/SigmaParserTest.scala b/interpreter/src/test/scala/sigmastate/lang/SigmaParserTest.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/lang/SigmaParserTest.scala rename to interpreter/src/test/scala/sigmastate/lang/SigmaParserTest.scala diff --git a/sigmastate/src/test/scala/sigmastate/lang/SigmaTyperTest.scala b/interpreter/src/test/scala/sigmastate/lang/SigmaTyperTest.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/lang/SigmaTyperTest.scala rename to interpreter/src/test/scala/sigmastate/lang/SigmaTyperTest.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/AvlTreeSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/AvlTreeSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/AvlTreeSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/AvlTreeSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/BlockSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/BlockSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/BlockSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/BlockSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/ConcreteCollectionSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/ConcreteCollectionSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/ConcreteCollectionSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/ConcreteCollectionSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/ConstantSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/ConstantSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/ConstantSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/ConstantSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/ConstantStoreSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/ConstantStoreSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/ConstantStoreSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/ConstantStoreSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/DataJsonEncoderSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/DataJsonEncoderSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/DataJsonEncoderSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/DataJsonEncoderSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/DataSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/DataSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/DataSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/DataSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/DeserializationResilience.scala b/interpreter/src/test/scala/sigmastate/serialization/DeserializationResilience.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/DeserializationResilience.scala rename to interpreter/src/test/scala/sigmastate/serialization/DeserializationResilience.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/GroupElementSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/GroupElementSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/GroupElementSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/GroupElementSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/MethodCallSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/MethodCallSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/MethodCallSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/MethodCallSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/ModQSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/ModQSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/ModQSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/ModQSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/PDHTSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/PDHTSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/PDHTSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/PDHTSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/ProveDlogSerializerSpec.scala b/interpreter/src/test/scala/sigmastate/serialization/ProveDlogSerializerSpec.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/ProveDlogSerializerSpec.scala rename to interpreter/src/test/scala/sigmastate/serialization/ProveDlogSerializerSpec.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/RelationsSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/RelationsSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/RelationsSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/RelationsSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/SelectFieldSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/SelectFieldSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/SelectFieldSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/SelectFieldSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/SerializationSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/SerializationSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/SerializationSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/SerializationSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/SigSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/SubstConstantsSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/SubstConstantsSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/SubstConstantsSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/SubstConstantsSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/TableSerializationSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/TableSerializationSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/TableSerializationSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/TableSerializationSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/TaggedVariableSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/TaggedVariableSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/TaggedVariableSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/TaggedVariableSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/TransformersSerializationSpec.scala b/interpreter/src/test/scala/sigmastate/serialization/TransformersSerializationSpec.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/TransformersSerializationSpec.scala rename to interpreter/src/test/scala/sigmastate/serialization/TransformersSerializationSpec.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/TupleSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/TupleSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/TupleSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/TupleSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/TwoArgumentSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/TwoArgumentSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/TwoArgumentSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/TwoArgumentSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/TypeSerializerSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/TypeSerializerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/TypeSerializerSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/TypeSerializerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/UpcastOnDeserializationSpecification.scala b/interpreter/src/test/scala/sigmastate/serialization/UpcastOnDeserializationSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/UpcastOnDeserializationSpecification.scala rename to interpreter/src/test/scala/sigmastate/serialization/UpcastOnDeserializationSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/generators/ConcreteCollectionGenerators.scala b/interpreter/src/test/scala/sigmastate/serialization/generators/ConcreteCollectionGenerators.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/generators/ConcreteCollectionGenerators.scala rename to interpreter/src/test/scala/sigmastate/serialization/generators/ConcreteCollectionGenerators.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala b/interpreter/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala rename to interpreter/src/test/scala/sigmastate/serialization/generators/ObjectGenerators.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/generators/OpcodesGen.scala b/interpreter/src/test/scala/sigmastate/serialization/generators/OpcodesGen.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/generators/OpcodesGen.scala rename to interpreter/src/test/scala/sigmastate/serialization/generators/OpcodesGen.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/generators/RelationGenerators.scala b/interpreter/src/test/scala/sigmastate/serialization/generators/RelationGenerators.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/generators/RelationGenerators.scala rename to interpreter/src/test/scala/sigmastate/serialization/generators/RelationGenerators.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/generators/TransformerGenerators.scala b/interpreter/src/test/scala/sigmastate/serialization/generators/TransformerGenerators.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/generators/TransformerGenerators.scala rename to interpreter/src/test/scala/sigmastate/serialization/generators/TransformerGenerators.scala diff --git a/sigmastate/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala b/interpreter/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala rename to interpreter/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala diff --git a/sigmastate/src/test/scala/sigmastate/utils/GenInfoObjects.scala b/interpreter/src/test/scala/sigmastate/utils/GenInfoObjects.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utils/GenInfoObjects.scala rename to interpreter/src/test/scala/sigmastate/utils/GenInfoObjects.scala diff --git a/sigmastate/src/test/scala/sigmastate/utils/GenPredefFuncsApp.scala b/interpreter/src/test/scala/sigmastate/utils/GenPredefFuncsApp.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utils/GenPredefFuncsApp.scala rename to interpreter/src/test/scala/sigmastate/utils/GenPredefFuncsApp.scala diff --git a/sigmastate/src/test/scala/sigmastate/utils/GenPredefTypesApp.scala b/interpreter/src/test/scala/sigmastate/utils/GenPredefTypesApp.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utils/GenPredefTypesApp.scala rename to interpreter/src/test/scala/sigmastate/utils/GenPredefTypesApp.scala diff --git a/sigmastate/src/test/scala/sigmastate/utils/GenSerializers.scala b/interpreter/src/test/scala/sigmastate/utils/GenSerializers.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utils/GenSerializers.scala rename to interpreter/src/test/scala/sigmastate/utils/GenSerializers.scala diff --git a/sigmastate/src/test/scala/sigmastate/utils/HelpersTests.scala b/interpreter/src/test/scala/sigmastate/utils/HelpersTests.scala similarity index 96% rename from sigmastate/src/test/scala/sigmastate/utils/HelpersTests.scala rename to interpreter/src/test/scala/sigmastate/utils/HelpersTests.scala index 2578553c9f..c1accad043 100644 --- a/sigmastate/src/test/scala/sigmastate/utils/HelpersTests.scala +++ b/interpreter/src/test/scala/sigmastate/utils/HelpersTests.scala @@ -23,7 +23,7 @@ class HelpersTests extends AnyPropSpec with ScalaCheckPropertyChecks with Matche xorU(res2, Seq(arr1, arr2, arr3)) res1 shouldBe res2 - println(arr.length) + printDebug(arr.length) } } } diff --git a/sigmastate/src/test/scala/sigmastate/utils/SparseArrayContainerSpecification.scala b/interpreter/src/test/scala/sigmastate/utils/SparseArrayContainerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utils/SparseArrayContainerSpecification.scala rename to interpreter/src/test/scala/sigmastate/utils/SparseArrayContainerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utils/SpecGen.scala b/interpreter/src/test/scala/sigmastate/utils/SpecGen.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utils/SpecGen.scala rename to interpreter/src/test/scala/sigmastate/utils/SpecGen.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/BlockchainSimulationSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/BlockchainSimulationSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/BlockchainSimulationSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/BlockchainSimulationSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala similarity index 99% rename from sigmastate/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala index 41f9a28535..10aea07d97 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala +++ b/interpreter/src/test/scala/sigmastate/utxo/ComplexSigSpecification.scala @@ -304,7 +304,7 @@ class ComplexSigSpecification extends SigmaTestingCommons val proverAB = proverA.withSecrets(Seq(proverB.dlogSecrets.head)) val pr = proverAB.prove(propTree, ctx, fakeMessage).get - println("proof size: " + pr.proof.length) + printDebug("proof size: " + pr.proof.length) verifier.verify(propTree, ctx, pr, fakeMessage).get._1 shouldBe true val pr2 = proverC.prove(propTree, ctx, fakeMessage).get diff --git a/sigmastate/src/test/scala/sigmastate/utxo/ContextEnrichingSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/ContextEnrichingSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/ContextEnrichingSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/ContextEnrichingSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/DistributedSigSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/DistributedSigSpecification.scala similarity index 99% rename from sigmastate/src/test/scala/sigmastate/utxo/DistributedSigSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/DistributedSigSpecification.scala index 0972a3c5f0..51820e7ac5 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/DistributedSigSpecification.scala +++ b/interpreter/src/test/scala/sigmastate/utxo/DistributedSigSpecification.scala @@ -410,7 +410,7 @@ class DistributedSigSpecification extends SigmaTestingCommons //first, commitments are needed from real signers val aliceHints = proverA.generateCommitments(prop, ctx) - println(aliceHints) + printDebug(aliceHints) val secretCmtA: Hint = aliceHints.ownCommitments.head val daveHints = proverD.generateCommitments(prop, ctx) diff --git a/sigmastate/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/ProverSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/ProverSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/ProverSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/ProverSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/SerializationRoundTripSpec.scala b/interpreter/src/test/scala/sigmastate/utxo/SerializationRoundTripSpec.scala similarity index 97% rename from sigmastate/src/test/scala/sigmastate/utxo/SerializationRoundTripSpec.scala rename to interpreter/src/test/scala/sigmastate/utxo/SerializationRoundTripSpec.scala index 3bf3f0cf08..4a653dabdb 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/SerializationRoundTripSpec.scala +++ b/interpreter/src/test/scala/sigmastate/utxo/SerializationRoundTripSpec.scala @@ -45,7 +45,7 @@ class SerializationRoundTripSpec extends AnyPropSpec } val ordered = runs.toArray().sortBy(_.size) for (r <- ordered) { - println(s"Size: ${r.size}, Time: ${r.time}") + printDebug(s"Size: ${r.size}, Time: ${r.time}") } } diff --git a/sigmastate/src/test/scala/sigmastate/utxo/SigmaCompilerSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/SigmaCompilerSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/SigmaCompilerSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/SigmaCompilerSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala b/interpreter/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala rename to interpreter/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchange.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchange.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchange.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchange.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeErgoTests.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeErgoTests.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeErgoTests.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeErgoTests.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/AssetsAtomicExchangeTests.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/AssetsPartialFilling.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/AssetsPartialFilling.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/AssetsPartialFilling.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/AssetsPartialFilling.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/AtomicSwapExampleSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala similarity index 96% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala index 9b585a823b..f2b898e21b 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala +++ b/interpreter/src/test/scala/sigmastate/utxo/examples/CoinEmissionSpecification.scala @@ -205,13 +205,15 @@ block 1600 in 1622 ms, 30000000000 coins remain, defs: 61661 hLimit: Int): Unit = if (height < hLimit) { if (height % 100 == 0) { val t = System.currentTimeMillis() - println(s"block $height in ${t - st} ms, ${emissionBox.value} coins remain, defs: ${IR.defCount}") + if (printDebugInfo) + println(s"block $height in ${t - st} ms, ${emissionBox.value} coins remain, defs: ${IR.defCount}") st = t IR.resetContext() } if (height % 1000 == 0) { val t = System.currentTimeMillis() - println(s"block $height in ${t - thousandTime} ms, ${emissionBox.value} coins remain") + if (printDebugInfo) + println(s"block $height in ${t - thousandTime} ms, ${emissionBox.value} coins remain") thousandTime = t } val tx = genCoinbaseLikeTransaction(state, emissionBox, height) @@ -227,6 +229,7 @@ block 1600 in 1622 ms, 30000000000 coins remain, defs: 61661 chainGen(genesisState, initialBox, 0, 1000000) - println(s"Emission Tree: ${ErgoAlgos.encode(tree.bytes)}") + if (printDebugInfo) + println(s"Emission Tree: ${ErgoAlgos.encode(tree.bytes)}") } } diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/ColdWalletAdvContractExampleSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/ColdWalletAdvContractExampleSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/ColdWalletAdvContractExampleSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/ColdWalletAdvContractExampleSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/ColdWalletContractExampleSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/ColdWalletContractExampleSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/ColdWalletContractExampleSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/ColdWalletContractExampleSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/CoopExampleSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/CoopExampleSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/CoopExampleSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/CoopExampleSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/CrowdFunding.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/CrowdFunding.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/CrowdFunding.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/CrowdFunding.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/CrowdFundingTests.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/CrowdFundingTests.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/CrowdFundingTests.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/CrowdFundingTests.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/DHTupleExampleSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/DHTupleExampleSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/DHTupleExampleSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/DHTupleExampleSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/DemurrageExampleSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/DemurrageExampleSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/DemurrageExampleSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/DemurrageExampleSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/DummyExamplesSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/DummyExamplesSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/DummyExamplesSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/DummyExamplesSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/ExecuteFromExamplesSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/ExecuteFromExamplesSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/ExecuteFromExamplesSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/ExecuteFromExamplesSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/FsmExampleSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/IcoExample.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/IcoExample.scala similarity index 98% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/IcoExample.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/IcoExample.scala index 5b47961119..6500b280b3 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/examples/IcoExample.scala +++ b/interpreter/src/test/scala/sigmastate/utxo/examples/IcoExample.scala @@ -425,8 +425,8 @@ class IcoExample extends SigmaTestingCommons .withContextExtender(1, ByteArrayConstant(proof)) val res = projectProver.prove(env, fundingTree, fundingContext, fakeMessage).get - println("funding script cost: " + res.cost) - println("lookup proof size: " + proof.length) + printDebug("funding script cost: " + res.cost) + printDebug("lookup proof size: " + proof.length) //todo: test switching to fixing stage } @@ -462,7 +462,7 @@ class IcoExample extends SigmaTestingCommons self = projectBoxBeforeClosing, activatedVersionInTests) val res = project.prove(env, issuanceTree, issuanceContext, fakeMessage).get - println("token issuance script cost: " + res.cost) + printDebug("token issuance script cost: " + res.cost) } property("simple ico example - withdrawal stage") { @@ -542,20 +542,20 @@ class IcoExample extends SigmaTestingCommons .withContextExtender(4, IntArrayConstant((1 to withdrawalsCount).toArray)) val res = projectProver.prove(env, withdrawalTree, fundingContext, fakeMessage).get - println("withdrawal script cost: " + res.cost) - println("remove proof size: " + removalProof.length) - println("lookup proof size: " + lookupProof.length) + printDebug("withdrawal script cost: " + res.cost) + printDebug("remove proof size: " + removalProof.length) + printDebug("lookup proof size: " + lookupProof.length) } property("ComplexityTableStat") { - println(ComplexityTableStat.complexityTableString) + printDebug(ComplexityTableStat.complexityTableString) } /** This is the last executed test suite, so this method is executed after all tests. * We output statistics of how PrecompiledScriptProcessor cache was used. */ override protected def afterAll(): Unit = { - println("verifySignatureProfiler ==========================================") - println(Interpreter.verifySignatureProfiler.generateReport) + printDebug("verifySignatureProfiler ==========================================") + printDebug(Interpreter.verifySignatureProfiler.generateReport) } } diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala similarity index 99% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala index 63182e2a1a..aafaa92419 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala +++ b/interpreter/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala @@ -276,8 +276,8 @@ class LetsSpecification extends SigmaTestingCommons with CrossVersionProps { sui |}""".stripMargin ).asSigmaProp -// println(exchangeScript) -// println(managementScript) +// printDebug(exchangeScript) +// printDebug(managementScript) property("adding new member") { val avlProver = new BatchAVLProver[Digest32, Blake2b256.type](keyLength = 32, None) @@ -321,7 +321,7 @@ class LetsSpecification extends SigmaTestingCommons with CrossVersionProps { sui .withContextExtender(1, ByteArrayConstant(proof)) val res = managementProver.prove(env, managementTree, fundingContext, fakeMessage).get - println("new user script cost: " + res.cost) + printDebug("new user script cost: " + res.cost) } property("exchange") { @@ -381,7 +381,7 @@ class LetsSpecification extends SigmaTestingCommons with CrossVersionProps { sui .withContextExtender(1, ByteArrayConstant(proof)) val res = managementProver.prove(env, exchangeTree, exchangeContext, fakeMessage).get - println("exchange script cost: " + res.cost) + printDebug("exchange script cost: " + res.cost) } } diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/MASTExampleSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala similarity index 99% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala index 99806ca35b..6185145aa3 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala +++ b/interpreter/src/test/scala/sigmastate/utxo/examples/MixExampleSpecification.scala @@ -204,10 +204,10 @@ class MixExampleSpecification extends SigmaTestingCommons // if R4^x == R5 then this fullMixOutput0 is Alice's output else its Bob's output. val (aliceAnonBox, bobAnonBox) = if (r4X == fullMixOutput0_R5.asInstanceOf[GroupElementConstant].value) { - println("First output is Alice's") + printDebug("First output is Alice's") (fullMixOutput0, fullMixOutput1) } else { - println("First output is Bob's") + printDebug("First output is Bob's") SigmaDsl.GroupElement(dlogGroup.exponentiate(fullMixOutput0_R5.asInstanceOf[GroupElementConstant], x)) shouldBe fullMixOutput0_R4.asInstanceOf[GroupElementConstant].value (fullMixOutput1, fullMixOutput0) } diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/OracleDataInputsExamplesSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/OracleDataInputsExamplesSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/OracleDataInputsExamplesSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/OracleDataInputsExamplesSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/OracleTokenExamplesSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/OracleTokenExamplesSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/OracleTokenExamplesSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/OracleTokenExamplesSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala similarity index 99% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala index 454b6a7ec8..736462013c 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala +++ b/interpreter/src/test/scala/sigmastate/utxo/examples/RPSGameExampleSpecification.scala @@ -212,7 +212,7 @@ class RPSGameExampleSpecification extends SigmaTestingCommons a - b match { case 0 => // draw - println("Draw") + printDebug("Draw") ///////////////////////////////////////////////////////// // Possibility 1.1: draw ///////////////////////////////////////////////////////// @@ -242,7 +242,7 @@ class RPSGameExampleSpecification extends SigmaTestingCommons verifier.verify(fullGameEnv, fullGameScript, drawContextBob, proofBobDraw, fakeMessage).get._1 shouldBe true case 1 | -2 => // alice wins - println("Alice won") + printDebug("Alice won") ///////////////////////////////////////////////////////// // Possibility 1.2: Alice wins ///////////////////////////////////////////////////////// @@ -253,7 +253,7 @@ class RPSGameExampleSpecification extends SigmaTestingCommons val proofAliceWin1 = aliceProver.prove(fullGameEnv, fullGameScript, winContext1, fakeMessage).get verifier.verify(fullGameEnv, fullGameScript, winContext1, proofAliceWin1, fakeMessage).get._1 shouldBe true case _ => // bob wins - println("Bob won") + printDebug("Bob won") ///////////////////////////////////////////////////////// // Possibility 1.3: Bob wins ///////////////////////////////////////////////////////// diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/RevenueSharingExamplesSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/RevenueSharingExamplesSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/RevenueSharingExamplesSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/RevenueSharingExamplesSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/ReversibleTxExampleSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/ReversibleTxExampleSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/ReversibleTxExampleSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/ReversibleTxExampleSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala similarity index 99% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala index 5a727f0ad0..401b332c66 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala +++ b/interpreter/src/test/scala/sigmastate/utxo/examples/Rule110Specification.scala @@ -482,7 +482,7 @@ class Rule110Specification extends SigmaTestingCommons val firstRowState = genesisState.applyBlock(firstRowBlock, 10000000).get val t1 = System.currentTimeMillis() - println(s"First row time ${t1 - t0} ms.") + printDebug(s"First row time ${t1 - t0} ms.") firstRowState.boxesReader.byTwoInts(RowReg, 1, ColumnReg, 13).get.get(ValueReg).get.asInstanceOf[BooleanConstant].value shouldBe false firstRowState.boxesReader.byTwoInts(RowReg, 1, ColumnReg, 14).get.get(ValueReg).get.asInstanceOf[BooleanConstant].value shouldBe true diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/TimedPaymentExampleSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/TimedPaymentExampleSpecification.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/TimedPaymentExampleSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/TimedPaymentExampleSpecification.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/TrustlessLETS.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/TrustlessLETS.scala similarity index 100% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/TrustlessLETS.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/TrustlessLETS.scala diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala b/interpreter/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala similarity index 99% rename from sigmastate/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala rename to interpreter/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala index 786a7ba5d8..5ae741af6b 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala +++ b/interpreter/src/test/scala/sigmastate/utxo/examples/XorGameExampleSpecification.scala @@ -209,14 +209,14 @@ class XorGameExampleSpecification extends SigmaTestingCommons // Possibility 2.1: Bob wins and Alice reveals secret // Bob can spend anytime. But we show how he will spend before bobDeadline ///////////////////////////////////////////////////////// - println("Bob won") + printDebug("Bob won") bob } else { ///////////////////////////////////////////////////////// // Possibility 2.2: Alice wins (and she may or may not reveal secret). // Alice must spend before bobDeadline height ///////////////////////////////////////////////////////// - println("Alice won") + printDebug("Alice won") alice } }.withContextExtender( diff --git a/sigmastate/src/test/scala/special/sigma/ContractsTestkit.scala b/interpreter/src/test/scala/special/sigma/ContractsTestkit.scala similarity index 100% rename from sigmastate/src/test/scala/special/sigma/ContractsTestkit.scala rename to interpreter/src/test/scala/special/sigma/ContractsTestkit.scala diff --git a/sigmastate/src/test/scala/special/sigma/DataValueComparerSpecification.scala b/interpreter/src/test/scala/special/sigma/DataValueComparerSpecification.scala similarity index 99% rename from sigmastate/src/test/scala/special/sigma/DataValueComparerSpecification.scala rename to interpreter/src/test/scala/special/sigma/DataValueComparerSpecification.scala index c9e16b68f4..b264d52144 100644 --- a/sigmastate/src/test/scala/special/sigma/DataValueComparerSpecification.scala +++ b/interpreter/src/test/scala/special/sigma/DataValueComparerSpecification.scala @@ -228,7 +228,8 @@ class DataValueComparerSpecification extends SigmaDslTesting } override protected def afterAll(): Unit = { - println(suiteProfiler.generateReport) + val report = suiteProfiler.generateReport + if (printDebugInfo) println(report) } } diff --git a/sigmastate/src/test/scala/special/sigma/LoopTests.scala b/interpreter/src/test/scala/special/sigma/LoopTests.scala similarity index 100% rename from sigmastate/src/test/scala/special/sigma/LoopTests.scala rename to interpreter/src/test/scala/special/sigma/LoopTests.scala diff --git a/sigmastate/src/test/scala/special/sigma/SigmaDslSpecification.scala b/interpreter/src/test/scala/special/sigma/SigmaDslSpecification.scala similarity index 99% rename from sigmastate/src/test/scala/special/sigma/SigmaDslSpecification.scala rename to interpreter/src/test/scala/special/sigma/SigmaDslSpecification.scala index 0e0b50dacd..2012febdb8 100644 --- a/sigmastate/src/test/scala/special/sigma/SigmaDslSpecification.scala +++ b/interpreter/src/test/scala/special/sigma/SigmaDslSpecification.scala @@ -10045,8 +10045,9 @@ class SigmaDslSpecification extends SigmaDslTesting } override protected def afterAll(): Unit = { - println(ErgoTreeEvaluator.DefaultProfiler.generateReport) - println("==========================================================") - println(Interpreter.verifySignatureProfiler.generateReport) + printDebug(ErgoTreeEvaluator.DefaultProfiler.generateReport) + printDebug("==========================================================") + printDebug(Interpreter.verifySignatureProfiler.generateReport) + printDebug("==========================================================") } } diff --git a/sigmastate/src/test/scala/special/sigma/SigmaDslStaginTests.scala b/interpreter/src/test/scala/special/sigma/SigmaDslStaginTests.scala similarity index 86% rename from sigmastate/src/test/scala/special/sigma/SigmaDslStaginTests.scala rename to interpreter/src/test/scala/special/sigma/SigmaDslStaginTests.scala index 1b93729e93..afbd3ba4bb 100644 --- a/sigmastate/src/test/scala/special/sigma/SigmaDslStaginTests.scala +++ b/interpreter/src/test/scala/special/sigma/SigmaDslStaginTests.scala @@ -1,14 +1,15 @@ package special.sigma +import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll} import special.collection._ import scala.language.reflectiveCalls import scalan.{BaseCtxTests, BaseLiftableTests} -import sigmastate.{TrivialProp, VersionContext, eval} +import sigmastate.{VersionContext, eval, TrivialProp, ReflectionGenerator} import sigmastate.eval.Extensions._ import sigmastate.eval._ -class SigmaDslStaginTests extends BaseCtxTests with ErgoScriptTestkit with BaseLiftableTests { +class SigmaDslStaginTests extends BaseCtxTests with ErgoScriptTestkit with BaseLiftableTests with BeforeAndAfterAll { class Ctx extends TestContext with IRContext with LiftableTestKit { } @@ -46,10 +47,7 @@ class SigmaDslStaginTests extends BaseCtxTests with ErgoScriptTestkit with BaseL cake.check(boxA1, { env: EnvRep[RBox] => for { obj <- env } yield obj.value }, boxA1.value) cake.check(boxA1, { env: EnvRep[RBox] => for { obj <- env } yield obj.creationInfo }, boxA1.creationInfo) cake.check(boxA1, { env: EnvRep[RBox] => for { obj <- env; arg <- lifted(1) } yield obj.getReg[Coll[Byte]](arg) }, boxA1.getReg[special.collection.Coll[Byte]](1)) - cake.check(boxA1, { env: EnvRep[RBox] => for { obj <- env } yield obj.registers }, boxA1.registers) - cake.check(p1, { env: EnvRep[RSigmaProp] => - for { p1 <- env; arg <- lifted(p2) } yield p1 && arg - }, p1 && p2) } + } diff --git a/sigmastate/src/test/scala/special/sigma/SigmaDslTesting.scala b/interpreter/src/test/scala/special/sigma/SigmaDslTesting.scala similarity index 100% rename from sigmastate/src/test/scala/special/sigma/SigmaDslTesting.scala rename to interpreter/src/test/scala/special/sigma/SigmaDslTesting.scala diff --git a/sigmastate/src/test/scala/special/sigma/SigmaTestingData.scala b/interpreter/src/test/scala/special/sigma/SigmaTestingData.scala similarity index 100% rename from sigmastate/src/test/scala/special/sigma/SigmaTestingData.scala rename to interpreter/src/test/scala/special/sigma/SigmaTestingData.scala diff --git a/library-api/src/main/scala/special/SpecialPredef.scala b/library-api/src/main/scala/special/SpecialPredef.scala deleted file mode 100644 index 9152f55d09..0000000000 --- a/library-api/src/main/scala/special/SpecialPredef.scala +++ /dev/null @@ -1,24 +0,0 @@ -package special - -import scala.reflect.ClassTag -import scalan.RType - -object SpecialPredef { - def loopUntil[A](s1: A, isMatch: A => Boolean, step: A => A): A = { - var res = s1 - while (!isMatch(res)) - res = step(res) - res - } - - def cast[T:ClassTag](v: Any): Option[T] = v match { case _: T => Some(v.asInstanceOf[T]) case _ => None } - - def some[A](x: A): Option[A] = Some(x) - - def none[A](implicit tA: RType[A]): Option[A] = Option.empty[A] - - def optionGetOrElse[A](opt: Option[A], default: A): A = opt.getOrElse(default) - - def rewritableMethod = - sys.error(s"Shouldn't be called, instead it should be either handled in rewrite rule, or overridden in derived class.") -} diff --git a/library-api/src/main/scala/special/wrappers/WrappersSpec.scala b/library-api/src/main/scala/special/wrappers/WrappersSpec.scala deleted file mode 100644 index 0765ba3358..0000000000 --- a/library-api/src/main/scala/special/wrappers/WrappersSpec.scala +++ /dev/null @@ -1,24 +0,0 @@ -package special.wrappers - -import scalan.{RType, WrapSpec} - -trait WrapSpecBase extends WrapSpec { -} - -/** Wrappers spec for Option */ -trait OptionWrapSpec extends WrapSpecBase { - def get[A](xs: Option[A]): A = xs.get - // TODO codegen: convertion to Thunk is required - def getOrElse[A](xs: Option[A], default: => A): A = xs.getOrElse(default) - def map[A,B](xs: Option[A], f: A => B): Option[B] = xs.map(f) - def flatMap[A,B](xs: Option[A], f: A => Option[B]): Option[B] = xs.flatMap(f) - def filter[A](xs: Option[A], f: A => Boolean): Option[A] = xs.filter(f) - def isDefined[A](xs: Option[A]): Boolean = xs.isDefined - def isEmpty[A](xs: Option[A]): Boolean = xs.isEmpty - // TODO codegen: fold should have single section, and convertion to Thunk is required - def fold[A,B](xs: Option[A], ifEmpty: =>B, f: A => B): B = xs.fold(ifEmpty)(f) -}; - -trait RTypeWrapSpec extends WrapSpecBase { - def name[T](d: RType[T]): String = d.name -} diff --git a/library/src/main/scala/special/collection/impl/CollsImpl.scala b/library/src/main/scala/special/collection/impl/CollsImpl.scala deleted file mode 100644 index 15c209bece..0000000000 --- a/library/src/main/scala/special/collection/impl/CollsImpl.scala +++ /dev/null @@ -1,1466 +0,0 @@ -package special.collection - -import scala.language.{existentials,implicitConversions} -import scalan._ -import scala.reflect.runtime.universe._ -import scala.reflect._ -import scala.collection.compat.immutable.ArraySeq - -package impl { -// Abs ----------------------------------- -trait CollsDefs extends scalan.Scalan with Colls { - self: Library => -import Coll._ -import CollBuilder._ -import PairColl._ -import WOption._ - -object Coll extends EntityObject("Coll") { - // entityConst: single const for each entity - import Liftables._ - import scala.reflect.{ClassTag, classTag} - type SColl[A] = special.collection.Coll[A] - case class CollConst[SA, A]( - constValue: SColl[SA], - lA: Liftable[SA, A] - ) extends LiftedConst[SColl[SA], Coll[A]] with Coll[A] - with Def[Coll[A]] with CollConstMethods[A] { - implicit final def eA: Elem[A] = lA.eW - - val liftable: Liftable[SColl[SA], Coll[A]] = liftableColl(lA) - val resultType: Elem[Coll[A]] = liftable.eW - } - - trait CollConstMethods[A] extends Coll[A] { thisConst: Def[_] => - implicit def eA: Elem[A] - private val CollClass = classOf[Coll[A]] - - override def builder: Ref[CollBuilder] = { - asRep[CollBuilder](mkMethodCall(self, - CollClass.getMethod("builder"), - ArraySeq.empty, - true, false, element[CollBuilder])) - } - - override def length: Ref[Int] = { - asRep[Int](mkMethodCall(self, - CollClass.getMethod("length"), - ArraySeq.empty, - true, false, element[Int])) - } - - override def isEmpty: Ref[Boolean] = { - asRep[Boolean](mkMethodCall(self, - CollClass.getMethod("isEmpty"), - ArraySeq.empty, - true, false, element[Boolean])) - } - - override def nonEmpty: Ref[Boolean] = { - asRep[Boolean](mkMethodCall(self, - CollClass.getMethod("nonEmpty"), - ArraySeq.empty, - true, false, element[Boolean])) - } - - override def apply(i: Ref[Int]): Ref[A] = { - asRep[A](mkMethodCall(self, - CollClass.getMethod("apply", classOf[Sym]), - Array[AnyRef](i), - true, false, element[A])) - } - - override def isDefinedAt(idx: Ref[Int]): Ref[Boolean] = { - asRep[Boolean](mkMethodCall(self, - CollClass.getMethod("isDefinedAt", classOf[Sym]), - Array[AnyRef](idx), - true, false, element[Boolean])) - } - - override def getOrElse(index: Ref[Int], default: Ref[A]): Ref[A] = { - asRep[A](mkMethodCall(self, - CollClass.getMethod("getOrElse", classOf[Sym], classOf[Sym]), - Array[AnyRef](index, default), - true, false, element[A])) - } - - override def map[B](f: Ref[A => B]): Ref[Coll[B]] = { - implicit val eB = f.elem.eRange - asRep[Coll[B]](mkMethodCall(self, - CollClass.getMethod("map", classOf[Sym]), - Array[AnyRef](f), - true, false, element[Coll[B]])) - } - - override def zip[B](ys: Ref[Coll[B]]): Ref[Coll[(A, B)]] = { - implicit val eB = ys.eA - asRep[Coll[(A, B)]](mkMethodCall(self, - CollClass.getMethod("zip", classOf[Sym]), - Array[AnyRef](ys), - true, false, element[Coll[(A, B)]])) - } - - override def exists(p: Ref[A => Boolean]): Ref[Boolean] = { - asRep[Boolean](mkMethodCall(self, - CollClass.getMethod("exists", classOf[Sym]), - Array[AnyRef](p), - true, false, element[Boolean])) - } - - override def forall(p: Ref[A => Boolean]): Ref[Boolean] = { - asRep[Boolean](mkMethodCall(self, - CollClass.getMethod("forall", classOf[Sym]), - Array[AnyRef](p), - true, false, element[Boolean])) - } - - override def filter(p: Ref[A => Boolean]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(self, - CollClass.getMethod("filter", classOf[Sym]), - Array[AnyRef](p), - true, false, element[Coll[A]])) - } - - override def foldLeft[B](zero: Ref[B], op: Ref[((B, A)) => B]): Ref[B] = { - implicit val eB = zero.elem - asRep[B](mkMethodCall(self, - CollClass.getMethod("foldLeft", classOf[Sym], classOf[Sym]), - Array[AnyRef](zero, op), - true, false, element[B])) - } - - override def indices: Ref[Coll[Int]] = { - asRep[Coll[Int]](mkMethodCall(self, - CollClass.getMethod("indices"), - ArraySeq.empty, - true, false, element[Coll[Int]])) - } - - override def flatMap[B](f: Ref[A => Coll[B]]): Ref[Coll[B]] = { - implicit val eB = f.elem.eRange.typeArgs("A")._1.asInstanceOf[Elem[B]] - asRep[Coll[B]](mkMethodCall(self, - CollClass.getMethod("flatMap", classOf[Sym]), - Array[AnyRef](f), - true, false, element[Coll[B]])) - } - - override def segmentLength(p: Ref[A => Boolean], from: Ref[Int]): Ref[Int] = { - asRep[Int](mkMethodCall(self, - CollClass.getMethod("segmentLength", classOf[Sym], classOf[Sym]), - Array[AnyRef](p, from), - true, false, element[Int])) - } - - override def find(p: Ref[A => Boolean]): Ref[WOption[A]] = { - asRep[WOption[A]](mkMethodCall(self, - CollClass.getMethod("find", classOf[Sym]), - Array[AnyRef](p), - true, false, element[WOption[A]])) - } - - override def indexWhere(p: Ref[A => Boolean], from: Ref[Int]): Ref[Int] = { - asRep[Int](mkMethodCall(self, - CollClass.getMethod("indexWhere", classOf[Sym], classOf[Sym]), - Array[AnyRef](p, from), - true, false, element[Int])) - } - - override def indexOf(elem: Ref[A], from: Ref[Int]): Ref[Int] = { - asRep[Int](mkMethodCall(self, - CollClass.getMethod("indexOf", classOf[Sym], classOf[Sym]), - Array[AnyRef](elem, from), - true, false, element[Int])) - } - - override def lastIndexWhere(p: Ref[A => Boolean], end: Ref[Int]): Ref[Int] = { - asRep[Int](mkMethodCall(self, - CollClass.getMethod("lastIndexWhere", classOf[Sym], classOf[Sym]), - Array[AnyRef](p, end), - true, false, element[Int])) - } - - override def take(n: Ref[Int]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(self, - CollClass.getMethod("take", classOf[Sym]), - Array[AnyRef](n), - true, false, element[Coll[A]])) - } - - override def patch(from: Ref[Int], patch: Ref[Coll[A]], replaced: Ref[Int]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(self, - CollClass.getMethod("patch", classOf[Sym], classOf[Sym], classOf[Sym]), - Array[AnyRef](from, patch, replaced), - true, false, element[Coll[A]])) - } - - override def updated(index: Ref[Int], elem: Ref[A]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(self, - CollClass.getMethod("updated", classOf[Sym], classOf[Sym]), - Array[AnyRef](index, elem), - true, false, element[Coll[A]])) - } - - override def updateMany(indexes: Ref[Coll[Int]], values: Ref[Coll[A]]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(self, - CollClass.getMethod("updateMany", classOf[Sym], classOf[Sym]), - Array[AnyRef](indexes, values), - true, false, element[Coll[A]])) - } - - override def unionSet(that: Ref[Coll[A]]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(self, - CollClass.getMethod("unionSet", classOf[Sym]), - Array[AnyRef](that), - true, false, element[Coll[A]])) - } - - override def diff(that: Ref[Coll[A]]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(self, - CollClass.getMethod("diff", classOf[Sym]), - Array[AnyRef](that), - true, false, element[Coll[A]])) - } - - override def intersect(that: Ref[Coll[A]]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(self, - CollClass.getMethod("intersect", classOf[Sym]), - Array[AnyRef](that), - true, false, element[Coll[A]])) - } - - override def slice(from: Ref[Int], until: Ref[Int]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(self, - CollClass.getMethod("slice", classOf[Sym], classOf[Sym]), - Array[AnyRef](from, until), - true, false, element[Coll[A]])) - } - - override def append(other: Ref[Coll[A]]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(self, - CollClass.getMethod("append", classOf[Sym]), - Array[AnyRef](other), - true, false, element[Coll[A]])) - } - - override def reverse: Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(self, - CollClass.getMethod("reverse"), - ArraySeq.empty, - true, false, element[Coll[A]])) - } - } - - case class LiftableColl[SA, A](lA: Liftable[SA, A]) - extends Liftable[SColl[SA], Coll[A]] { - lazy val eW: Elem[Coll[A]] = collElement(lA.eW) - lazy val sourceType: RType[SColl[SA]] = { - implicit val tagSA = lA.sourceType.asInstanceOf[RType[SA]] - RType[SColl[SA]] - } - def lift(x: SColl[SA]): Ref[Coll[A]] = CollConst(x, lA) - def unlift(w: Ref[Coll[A]]): SColl[SA] = w match { - case Def(CollConst(x: SColl[_], _lA)) - if _lA == lA => x.asInstanceOf[SColl[SA]] - case _ => unliftError(w) - } - } - implicit final def liftableColl[SA, A](implicit lA: Liftable[SA,A]): Liftable[SColl[SA], Coll[A]] = - LiftableColl(lA) - - private val CollClass = classOf[Coll[_]] - - // entityAdapter for Coll trait - case class CollAdapter[A](source: Ref[Coll[A]]) - extends Node with Coll[A] - with Def[Coll[A]] { - implicit lazy val eA = source.elem.typeArgs("A")._1.asInstanceOf[Elem[A]] - - val resultType: Elem[Coll[A]] = element[Coll[A]] - override def transform(t: Transformer) = CollAdapter[A](t(source)) - - def builder: Ref[CollBuilder] = { - asRep[CollBuilder](mkMethodCall(source, - CollClass.getMethod("builder"), - ArraySeq.empty, - true, true, element[CollBuilder])) - } - - def length: Ref[Int] = { - asRep[Int](mkMethodCall(source, - CollClass.getMethod("length"), - ArraySeq.empty, - true, true, element[Int])) - } - - def isEmpty: Ref[Boolean] = { - asRep[Boolean](mkMethodCall(source, - CollClass.getMethod("isEmpty"), - ArraySeq.empty, - true, true, element[Boolean])) - } - - def nonEmpty: Ref[Boolean] = { - asRep[Boolean](mkMethodCall(source, - CollClass.getMethod("nonEmpty"), - ArraySeq.empty, - true, true, element[Boolean])) - } - - def apply(i: Ref[Int]): Ref[A] = { - asRep[A](mkMethodCall(source, - CollClass.getMethod("apply", classOf[Sym]), - Array[AnyRef](i), - true, true, element[A])) - } - - def isDefinedAt(idx: Ref[Int]): Ref[Boolean] = { - asRep[Boolean](mkMethodCall(source, - CollClass.getMethod("isDefinedAt", classOf[Sym]), - Array[AnyRef](idx), - true, true, element[Boolean])) - } - - def getOrElse(index: Ref[Int], default: Ref[A]): Ref[A] = { - asRep[A](mkMethodCall(source, - CollClass.getMethod("getOrElse", classOf[Sym], classOf[Sym]), - Array[AnyRef](index, default), - true, true, element[A])) - } - - def map[B](f: Ref[A => B]): Ref[Coll[B]] = { - implicit val eB = f.elem.eRange - asRep[Coll[B]](mkMethodCall(source, - CollClass.getMethod("map", classOf[Sym]), - Array[AnyRef](f), - true, true, element[Coll[B]])) - } - - def zip[B](ys: Ref[Coll[B]]): Ref[Coll[(A, B)]] = { - implicit val eB = ys.eA - asRep[Coll[(A, B)]](mkMethodCall(source, - CollClass.getMethod("zip", classOf[Sym]), - Array[AnyRef](ys), - true, true, element[Coll[(A, B)]])) - } - - def exists(p: Ref[A => Boolean]): Ref[Boolean] = { - asRep[Boolean](mkMethodCall(source, - CollClass.getMethod("exists", classOf[Sym]), - Array[AnyRef](p), - true, true, element[Boolean])) - } - - def forall(p: Ref[A => Boolean]): Ref[Boolean] = { - asRep[Boolean](mkMethodCall(source, - CollClass.getMethod("forall", classOf[Sym]), - Array[AnyRef](p), - true, true, element[Boolean])) - } - - def filter(p: Ref[A => Boolean]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(source, - CollClass.getMethod("filter", classOf[Sym]), - Array[AnyRef](p), - true, true, element[Coll[A]])) - } - - def foldLeft[B](zero: Ref[B], op: Ref[((B, A)) => B]): Ref[B] = { - implicit val eB = zero.elem - asRep[B](mkMethodCall(source, - CollClass.getMethod("foldLeft", classOf[Sym], classOf[Sym]), - Array[AnyRef](zero, op), - true, true, element[B])) - } - - def indices: Ref[Coll[Int]] = { - asRep[Coll[Int]](mkMethodCall(source, - CollClass.getMethod("indices"), - ArraySeq.empty, - true, true, element[Coll[Int]])) - } - - def flatMap[B](f: Ref[A => Coll[B]]): Ref[Coll[B]] = { - implicit val eB = f.elem.eRange.typeArgs("A")._1.asInstanceOf[Elem[B]] - asRep[Coll[B]](mkMethodCall(source, - CollClass.getMethod("flatMap", classOf[Sym]), - Array[AnyRef](f), - true, true, element[Coll[B]])) - } - - def segmentLength(p: Ref[A => Boolean], from: Ref[Int]): Ref[Int] = { - asRep[Int](mkMethodCall(source, - CollClass.getMethod("segmentLength", classOf[Sym], classOf[Sym]), - Array[AnyRef](p, from), - true, true, element[Int])) - } - - override def find(p: Ref[A => Boolean]): Ref[WOption[A]] = { - asRep[WOption[A]](mkMethodCall(source, - CollClass.getMethod("find", classOf[Sym]), - Array[AnyRef](p), - true, true, element[WOption[A]])) - } - - def indexWhere(p: Ref[A => Boolean], from: Ref[Int]): Ref[Int] = { - asRep[Int](mkMethodCall(source, - CollClass.getMethod("indexWhere", classOf[Sym], classOf[Sym]), - Array[AnyRef](p, from), - true, true, element[Int])) - } - - override def indexOf(elem: Ref[A], from: Ref[Int]): Ref[Int] = { - asRep[Int](mkMethodCall(source, - CollClass.getMethod("indexOf", classOf[Sym], classOf[Sym]), - Array[AnyRef](elem, from), - true, true, element[Int])) - } - - def lastIndexWhere(p: Ref[A => Boolean], end: Ref[Int]): Ref[Int] = { - asRep[Int](mkMethodCall(source, - CollClass.getMethod("lastIndexWhere", classOf[Sym], classOf[Sym]), - Array[AnyRef](p, end), - true, true, element[Int])) - } - - def take(n: Ref[Int]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(source, - CollClass.getMethod("take", classOf[Sym]), - Array[AnyRef](n), - true, true, element[Coll[A]])) - } - - def patch(from: Ref[Int], patch: Ref[Coll[A]], replaced: Ref[Int]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(source, - CollClass.getMethod("patch", classOf[Sym], classOf[Sym], classOf[Sym]), - Array[AnyRef](from, patch, replaced), - true, true, element[Coll[A]])) - } - - def updated(index: Ref[Int], elem: Ref[A]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(source, - CollClass.getMethod("updated", classOf[Sym], classOf[Sym]), - Array[AnyRef](index, elem), - true, true, element[Coll[A]])) - } - - def updateMany(indexes: Ref[Coll[Int]], values: Ref[Coll[A]]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(source, - CollClass.getMethod("updateMany", classOf[Sym], classOf[Sym]), - Array[AnyRef](indexes, values), - true, true, element[Coll[A]])) - } - - def unionSet(that: Ref[Coll[A]]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(source, - CollClass.getMethod("unionSet", classOf[Sym]), - Array[AnyRef](that), - true, true, element[Coll[A]])) - } - - override def diff(that: Ref[Coll[A]]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(source, - CollClass.getMethod("diff", classOf[Sym]), - Array[AnyRef](that), - true, true, element[Coll[A]])) - } - - override def intersect(that: Ref[Coll[A]]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(source, - CollClass.getMethod("intersect", classOf[Sym]), - Array[AnyRef](that), - true, true, element[Coll[A]])) - } - - def slice(from: Ref[Int], until: Ref[Int]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(source, - CollClass.getMethod("slice", classOf[Sym], classOf[Sym]), - Array[AnyRef](from, until), - true, true, element[Coll[A]])) - } - - def append(other: Ref[Coll[A]]): Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(source, - CollClass.getMethod("append", classOf[Sym]), - Array[AnyRef](other), - true, true, element[Coll[A]])) - } - - def reverse: Ref[Coll[A]] = { - asRep[Coll[A]](mkMethodCall(source, - CollClass.getMethod("reverse"), - ArraySeq.empty, - true, true, element[Coll[A]])) - } - } - - // entityUnref: single unref method for each type family - val createCollAdapter: Ref[Coll[Any]] => Coll[Any] = x => CollAdapter(x) - - implicit final def unrefColl[A](p: Ref[Coll[A]]): Coll[A] = { - val sym = p.asInstanceOf[SingleRef[Coll[A]]] - sym.getAdapter( - p.node.isInstanceOf[Coll[A]@unchecked], - createCollAdapter.asInstanceOf[Ref[Coll[A]] => Coll[A]]) - } - - implicit final def castCollElement[A](elem: Elem[Coll[A]]): CollElem[A, Coll[A]] = - elem.asInstanceOf[CollElem[A, Coll[A]]] - - implicit lazy val containerColl: Functor[Coll] = new Functor[Coll] { - def lift[A](implicit evA: Elem[A]) = element[Coll[A]] - def unlift[A](implicit eFT: Elem[Coll[A]]) = - castCollElement(eFT).eA - def unapply[T](e: Elem[_]) = e match { - case e: CollElem[_,_] => Some(asElem[Coll[T]](e)) - case _ => None - } - def map[A,B](xs: Ref[Coll[A]])(f: Ref[A] => Ref[B]) = { implicit val eA = unlift(xs.elem); xs.map(fun(f))} - } - - // manual fix: CollIso, collIso - - // familyElem - class CollElem[A, To <: Coll[A]](implicit _eA: Elem[A]) - extends EntityElem1[A, To, Coll](_eA, container[Coll]) { - def eA = _eA - - override val liftable: Liftables.Liftable[_, To] = asLiftable[SColl[_], To](liftableColl(_eA.liftable)) - - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { - super.collectMethods ++ - Elem.declaredMethods(classOf[Coll[A]], classOf[SColl[_]], Set( - "builder", "length", "size", "isEmpty", "nonEmpty", "apply", "isDefinedAt", "getOrElse", "map", "zip", "exists", "forall", "filter", "foldLeft", "indices", "flatMap", "segmentLength", "find", "indexWhere", "indexOf", "lastIndexWhere", "take", "patch", "updated", "updateMany", "unionSet", "diff", "intersect", "slice", "append", "reverse" - )) - } - - override def buildTypeArgs = super.buildTypeArgs ++ TypeArgs("A" -> (eA -> scalan.util.Invariant)) - } - - implicit final def collElement[A](implicit eA: Elem[A]): Elem[Coll[A]] = - cachedElemByClass(eA)(classOf[CollElem[A, Coll[A]]]) - - implicit case object CollCompanionElem extends CompanionElem[CollCompanionCtor] - - abstract class CollCompanionCtor extends CompanionDef[CollCompanionCtor] with CollCompanion { - def resultType = CollCompanionElem - override def toString = "Coll" - } - implicit final def unrefCollCompanionCtor(p: Ref[CollCompanionCtor]): CollCompanionCtor = - p.node.asInstanceOf[CollCompanionCtor] - - lazy val RColl: MutableLazy[CollCompanionCtor] = MutableLazy(new CollCompanionCtor { - private val thisClass = classOf[CollCompanion] - }) - - // manual fix: ViewColl - - object CollMethods { - object builder { - def unapply(d: Def[_]): Nullable[Ref[Coll[A]] forSome {type A}] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "builder" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Coll[A]] forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Coll[A]] forSome {type A}] = unapply(exp.node) - } - - object length { - def unapply(d: Def[_]): Nullable[Ref[Coll[A]] forSome {type A}] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "length" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Coll[A]] forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Coll[A]] forSome {type A}] = unapply(exp.node) - } - - object size { - def unapply(d: Def[_]): Nullable[Ref[Coll[A]] forSome {type A}] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "size" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Coll[A]] forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Coll[A]] forSome {type A}] = unapply(exp.node) - } - - object isEmpty { - def unapply(d: Def[_]): Nullable[Ref[Coll[A]] forSome {type A}] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "isEmpty" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Coll[A]] forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Coll[A]] forSome {type A}] = unapply(exp.node) - } - - object nonEmpty { - def unapply(d: Def[_]): Nullable[Ref[Coll[A]] forSome {type A}] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "nonEmpty" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Coll[A]] forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Coll[A]] forSome {type A}] = unapply(exp.node) - } - - object apply { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Int]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "apply" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Int]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Int]) forSome {type A}] = unapply(exp.node) - } - - object isDefinedAt { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Int]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "isDefinedAt" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Int]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Int]) forSome {type A}] = unapply(exp.node) - } - - object getOrElse { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Int], Ref[A]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "getOrElse" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Int], Ref[A]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Int], Ref[A]) forSome {type A}] = unapply(exp.node) - } - - object map { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => B]) forSome {type A; type B}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "map" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => B]) forSome {type A; type B}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => B]) forSome {type A; type B}] = unapply(exp.node) - } - - object zip { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Coll[B]]) forSome {type A; type B}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "zip" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Coll[B]]) forSome {type A; type B}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Coll[B]]) forSome {type A; type B}] = unapply(exp.node) - } - - object exists { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "exists" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = unapply(exp.node) - } - - object forall { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "forall" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = unapply(exp.node) - } - - object filter { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "filter" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = unapply(exp.node) - } - - object foldLeft { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[B], Ref[((B, A)) => B]) forSome {type A; type B}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "foldLeft" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[B], Ref[((B, A)) => B]) forSome {type A; type B}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[B], Ref[((B, A)) => B]) forSome {type A; type B}] = unapply(exp.node) - } - - object indices { - def unapply(d: Def[_]): Nullable[Ref[Coll[A]] forSome {type A}] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "indices" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Coll[A]] forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Coll[A]] forSome {type A}] = unapply(exp.node) - } - - object flatMap { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => Coll[B]]) forSome {type A; type B}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "flatMap" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => Coll[B]]) forSome {type A; type B}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => Coll[B]]) forSome {type A; type B}] = unapply(exp.node) - } - - object segmentLength { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => Boolean], Ref[Int]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "segmentLength" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => Boolean], Ref[Int]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => Boolean], Ref[Int]) forSome {type A}] = unapply(exp.node) - } - - object find { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "find" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => Boolean]) forSome {type A}] = unapply(exp.node) - } - - object indexWhere { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => Boolean], Ref[Int]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "indexWhere" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => Boolean], Ref[Int]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => Boolean], Ref[Int]) forSome {type A}] = unapply(exp.node) - } - - object indexOf { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A], Ref[Int]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "indexOf" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A], Ref[Int]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A], Ref[Int]) forSome {type A}] = unapply(exp.node) - } - - object lastIndexWhere { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[A => Boolean], Ref[Int]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "lastIndexWhere" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[A => Boolean], Ref[Int]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[A => Boolean], Ref[Int]) forSome {type A}] = unapply(exp.node) - } - - object take { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Int]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "take" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Int]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Int]) forSome {type A}] = unapply(exp.node) - } - - object patch { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Int], Ref[Coll[A]], Ref[Int]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "patch" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0), args(1), args(2)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Int], Ref[Coll[A]], Ref[Int]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Int], Ref[Coll[A]], Ref[Int]) forSome {type A}] = unapply(exp.node) - } - - object updated { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Int], Ref[A]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "updated" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Int], Ref[A]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Int], Ref[A]) forSome {type A}] = unapply(exp.node) - } - - object updateMany { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Coll[Int]], Ref[Coll[A]]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "updateMany" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Coll[Int]], Ref[Coll[A]]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Coll[Int]], Ref[Coll[A]]) forSome {type A}] = unapply(exp.node) - } - - object unionSet { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "unionSet" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}] = unapply(exp.node) - } - - object diff { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "diff" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}] = unapply(exp.node) - } - - object intersect { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "intersect" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}] = unapply(exp.node) - } - - object slice { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Int], Ref[Int]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "slice" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Int], Ref[Int]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Int], Ref[Int]) forSome {type A}] = unapply(exp.node) - } - - object append { - def unapply(d: Def[_]): Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "append" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Coll[A]], Ref[Coll[A]]) forSome {type A}] = unapply(exp.node) - } - - object reverse { - def unapply(d: Def[_]): Nullable[Ref[Coll[A]] forSome {type A}] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "reverse" && receiver.elem.isInstanceOf[CollElem[_, _]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[Coll[A]] forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[Coll[A]] forSome {type A}] = unapply(exp.node) - } - } - - object CollCompanionMethods { - } -} // of object Coll - registerEntityObject("Coll", Coll) - -object PairColl extends EntityObject("PairColl") { - private val PairCollClass = classOf[PairColl[_, _]] - - // entityAdapter for PairColl trait - case class PairCollAdapter[L, R](source: Ref[PairColl[L, R]]) - extends Node with PairColl[L, R] - with Def[PairColl[L, R]] { - implicit lazy val eL = source.elem.typeArgs("L")._1.asInstanceOf[Elem[L]]; -implicit lazy val eR = source.elem.typeArgs("R")._1.asInstanceOf[Elem[R]] - override lazy val eA: Elem[(L, R)] = implicitly[Elem[(L, R)]] - val resultType: Elem[PairColl[L, R]] = element[PairColl[L, R]] - override def transform(t: Transformer) = PairCollAdapter[L, R](t(source)) - - def ls: Ref[Coll[L]] = { - asRep[Coll[L]](mkMethodCall(source, - PairCollClass.getMethod("ls"), - ArraySeq.empty, - true, true, element[Coll[L]])) - } - - def rs: Ref[Coll[R]] = { - asRep[Coll[R]](mkMethodCall(source, - PairCollClass.getMethod("rs"), - ArraySeq.empty, - true, true, element[Coll[R]])) - } - - def mapFirst[T1](f: Ref[L => T1]): Ref[Coll[(T1, R)]] = { - implicit val eT1 = f.elem.eRange - asRep[Coll[(T1, R)]](mkMethodCall(source, - PairCollClass.getMethod("mapFirst", classOf[Sym]), - Array[AnyRef](f), - true, true, element[Coll[(T1, R)]])) - } - - def mapSecond[T1](f: Ref[R => T1]): Ref[Coll[(L, T1)]] = { - implicit val eT1 = f.elem.eRange - asRep[Coll[(L, T1)]](mkMethodCall(source, - PairCollClass.getMethod("mapSecond", classOf[Sym]), - Array[AnyRef](f), - true, true, element[Coll[(L, T1)]])) - } - - def builder: Ref[CollBuilder] = { - asRep[CollBuilder](mkMethodCall(source, - PairCollClass.getMethod("builder"), - ArraySeq.empty, - true, true, element[CollBuilder])) - } - - def length: Ref[Int] = { - asRep[Int](mkMethodCall(source, - PairCollClass.getMethod("length"), - ArraySeq.empty, - true, true, element[Int])) - } - - def isEmpty: Ref[Boolean] = { - asRep[Boolean](mkMethodCall(source, - PairCollClass.getMethod("isEmpty"), - ArraySeq.empty, - true, true, element[Boolean])) - } - - def nonEmpty: Ref[Boolean] = { - asRep[Boolean](mkMethodCall(source, - PairCollClass.getMethod("nonEmpty"), - ArraySeq.empty, - true, true, element[Boolean])) - } - - def apply(i: Ref[Int]): Ref[(L, R)] = { - asRep[(L, R)](mkMethodCall(source, - PairCollClass.getMethod("apply", classOf[Sym]), - Array[AnyRef](i), - true, true, element[(L, R)])) - } - - def isDefinedAt(idx: Ref[Int]): Ref[Boolean] = { - asRep[Boolean](mkMethodCall(source, - PairCollClass.getMethod("isDefinedAt", classOf[Sym]), - Array[AnyRef](idx), - true, true, element[Boolean])) - } - - def getOrElse(index: Ref[Int], default: Ref[(L, R)]): Ref[(L, R)] = { - asRep[(L, R)](mkMethodCall(source, - PairCollClass.getMethod("getOrElse", classOf[Sym], classOf[Sym]), - Array[AnyRef](index, default), - true, true, element[(L, R)])) - } - - def map[B](f: Ref[((L, R)) => B]): Ref[Coll[B]] = { - implicit val eB = f.elem.eRange - asRep[Coll[B]](mkMethodCall(source, - PairCollClass.getMethod("map", classOf[Sym]), - Array[AnyRef](f), - true, true, element[Coll[B]])) - } - - // manual fix - def zip[B](ys: Ref[Coll[B]]): Ref[Coll[((L, R), B)]] = { - implicit val eB = ys.eA - asRep[Coll[((L, R), B)]](mkMethodCall(source, - PairCollClass.getMethod("zip", classOf[Sym]), - Array[AnyRef](ys), - true, true, element[Coll[((L, R), B)]](collElement(pairElement(pairElement(eL, eR), eB))))) - } - - def exists(p: Ref[((L, R)) => Boolean]): Ref[Boolean] = { - asRep[Boolean](mkMethodCall(source, - PairCollClass.getMethod("exists", classOf[Sym]), - Array[AnyRef](p), - true, true, element[Boolean])) - } - - def forall(p: Ref[((L, R)) => Boolean]): Ref[Boolean] = { - asRep[Boolean](mkMethodCall(source, - PairCollClass.getMethod("forall", classOf[Sym]), - Array[AnyRef](p), - true, true, element[Boolean])) - } - - def filter(p: Ref[((L, R)) => Boolean]): Ref[Coll[(L, R)]] = { - asRep[Coll[(L, R)]](mkMethodCall(source, - PairCollClass.getMethod("filter", classOf[Sym]), - Array[AnyRef](p), - true, true, element[Coll[(L, R)]])) - } - - def foldLeft[B](zero: Ref[B], op: Ref[((B, (L, R))) => B]): Ref[B] = { - implicit val eB = zero.elem - asRep[B](mkMethodCall(source, - PairCollClass.getMethod("foldLeft", classOf[Sym], classOf[Sym]), - Array[AnyRef](zero, op), - true, true, element[B])) - } - - def indices: Ref[Coll[Int]] = { - asRep[Coll[Int]](mkMethodCall(source, - PairCollClass.getMethod("indices"), - ArraySeq.empty, - true, true, element[Coll[Int]])) - } - - def flatMap[B](f: Ref[((L, R)) => Coll[B]]): Ref[Coll[B]] = { - implicit val eB = f.elem.eRange.typeArgs("A")._1.asInstanceOf[Elem[B]] - asRep[Coll[B]](mkMethodCall(source, - PairCollClass.getMethod("flatMap", classOf[Sym]), - Array[AnyRef](f), - true, true, element[Coll[B]])) - } - - def segmentLength(p: Ref[((L, R)) => Boolean], from: Ref[Int]): Ref[Int] = { - asRep[Int](mkMethodCall(source, - PairCollClass.getMethod("segmentLength", classOf[Sym], classOf[Sym]), - Array[AnyRef](p, from), - true, true, element[Int])) - } - - override def find(p: Ref[((L, R)) => Boolean]): Ref[WOption[(L, R)]] = { - asRep[WOption[(L, R)]](mkMethodCall(source, - PairCollClass.getMethod("find", classOf[Sym]), - Array[AnyRef](p), - true, true, element[WOption[(L, R)]])) - } - - def indexWhere(p: Ref[((L, R)) => Boolean], from: Ref[Int]): Ref[Int] = { - asRep[Int](mkMethodCall(source, - PairCollClass.getMethod("indexWhere", classOf[Sym], classOf[Sym]), - Array[AnyRef](p, from), - true, true, element[Int])) - } - - override def indexOf(elem: Ref[(L, R)], from: Ref[Int]): Ref[Int] = { - asRep[Int](mkMethodCall(source, - PairCollClass.getMethod("indexOf", classOf[Sym], classOf[Sym]), - Array[AnyRef](elem, from), - true, true, element[Int])) - } - - def lastIndexWhere(p: Ref[((L, R)) => Boolean], end: Ref[Int]): Ref[Int] = { - asRep[Int](mkMethodCall(source, - PairCollClass.getMethod("lastIndexWhere", classOf[Sym], classOf[Sym]), - Array[AnyRef](p, end), - true, true, element[Int])) - } - - def take(n: Ref[Int]): Ref[Coll[(L, R)]] = { - asRep[Coll[(L, R)]](mkMethodCall(source, - PairCollClass.getMethod("take", classOf[Sym]), - Array[AnyRef](n), - true, true, element[Coll[(L, R)]])) - } - - def patch(from: Ref[Int], patch: Ref[Coll[(L, R)]], replaced: Ref[Int]): Ref[Coll[(L, R)]] = { - asRep[Coll[(L, R)]](mkMethodCall(source, - PairCollClass.getMethod("patch", classOf[Sym], classOf[Sym], classOf[Sym]), - Array[AnyRef](from, patch, replaced), - true, true, element[Coll[(L, R)]])) - } - - def updated(index: Ref[Int], elem: Ref[(L, R)]): Ref[Coll[(L, R)]] = { - asRep[Coll[(L, R)]](mkMethodCall(source, - PairCollClass.getMethod("updated", classOf[Sym], classOf[Sym]), - Array[AnyRef](index, elem), - true, true, element[Coll[(L, R)]])) - } - - def updateMany(indexes: Ref[Coll[Int]], values: Ref[Coll[(L, R)]]): Ref[Coll[(L, R)]] = { - asRep[Coll[(L, R)]](mkMethodCall(source, - PairCollClass.getMethod("updateMany", classOf[Sym], classOf[Sym]), - Array[AnyRef](indexes, values), - true, true, element[Coll[(L, R)]])) - } - - def unionSet(that: Ref[Coll[(L, R)]]): Ref[Coll[(L, R)]] = { - asRep[Coll[(L, R)]](mkMethodCall(source, - PairCollClass.getMethod("unionSet", classOf[Sym]), - Array[AnyRef](that), - true, true, element[Coll[(L, R)]])) - } - - override def diff(that: Ref[Coll[(L, R)]]): Ref[Coll[(L, R)]] = { - asRep[Coll[(L, R)]](mkMethodCall(source, - PairCollClass.getMethod("diff", classOf[Sym]), - Array[AnyRef](that), - true, true, element[Coll[(L, R)]])) - } - - override def intersect(that: Ref[Coll[(L, R)]]): Ref[Coll[(L, R)]] = { - asRep[Coll[(L, R)]](mkMethodCall(source, - PairCollClass.getMethod("intersect", classOf[Sym]), - Array[AnyRef](that), - true, true, element[Coll[(L, R)]])) - } - - def slice(from: Ref[Int], until: Ref[Int]): Ref[Coll[(L, R)]] = { - asRep[Coll[(L, R)]](mkMethodCall(source, - PairCollClass.getMethod("slice", classOf[Sym], classOf[Sym]), - Array[AnyRef](from, until), - true, true, element[Coll[(L, R)]])) - } - - def append(other: Ref[Coll[(L, R)]]): Ref[Coll[(L, R)]] = { - asRep[Coll[(L, R)]](mkMethodCall(source, - PairCollClass.getMethod("append", classOf[Sym]), - Array[AnyRef](other), - true, true, element[Coll[(L, R)]])) - } - - def reverse: Ref[Coll[(L, R)]] = { - asRep[Coll[(L, R)]](mkMethodCall(source, - PairCollClass.getMethod("reverse"), - ArraySeq.empty, - true, true, element[Coll[(L, R)]])) - } - } - - // entityUnref: single unref method for each type family - implicit final def unrefPairColl[L, R](p: Ref[PairColl[L, R]]): PairColl[L, R] = { - if (p.node.isInstanceOf[PairColl[L, R]@unchecked]) p.node.asInstanceOf[PairColl[L, R]] - else - PairCollAdapter(p) - } - - // familyElem - class PairCollElem[L, R, To <: PairColl[L, R]](implicit _eL: Elem[L], _eR: Elem[R]) - extends CollElem[(L, R), To] { - def eL = _eL - def eR = _eR - - override lazy val parent: Option[Elem[_]] = Some(collElement(pairElement(element[L],element[R]))) - override def buildTypeArgs = super.buildTypeArgs ++ TypeArgs("L" -> (eL -> scalan.util.Invariant), "R" -> (eR -> scalan.util.Invariant)) - } - - implicit final def pairCollElement[L, R](implicit eL: Elem[L], eR: Elem[R]): Elem[PairColl[L, R]] = - cachedElemByClass(eL, eR)(classOf[PairCollElem[L, R, PairColl[L, R]]]) - - implicit case object PairCollCompanionElem extends CompanionElem[PairCollCompanionCtor] - - abstract class PairCollCompanionCtor extends CompanionDef[PairCollCompanionCtor] with PairCollCompanion { - def resultType = PairCollCompanionElem - override def toString = "PairColl" - } - implicit final def unrefPairCollCompanionCtor(p: Ref[PairCollCompanionCtor]): PairCollCompanionCtor = - p.node.asInstanceOf[PairCollCompanionCtor] - - lazy val RPairColl: MutableLazy[PairCollCompanionCtor] = MutableLazy(new PairCollCompanionCtor { - private val thisClass = classOf[PairCollCompanion] - }) - - object PairCollMethods { - object ls { - def unapply(d: Def[_]): Nullable[Ref[PairColl[L, R]] forSome {type L; type R}] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "ls" && receiver.elem.isInstanceOf[PairCollElem[_, _, _]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[PairColl[L, R]] forSome {type L; type R}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[PairColl[L, R]] forSome {type L; type R}] = unapply(exp.node) - } - - object rs { - def unapply(d: Def[_]): Nullable[Ref[PairColl[L, R]] forSome {type L; type R}] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "rs" && receiver.elem.isInstanceOf[PairCollElem[_, _, _]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[PairColl[L, R]] forSome {type L; type R}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[PairColl[L, R]] forSome {type L; type R}] = unapply(exp.node) - } - - object mapFirst { - def unapply(d: Def[_]): Nullable[(Ref[PairColl[L, R]], Ref[L => T1]) forSome {type L; type R; type T1}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "mapFirst" && receiver.elem.isInstanceOf[PairCollElem[_, _, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[PairColl[L, R]], Ref[L => T1]) forSome {type L; type R; type T1}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[PairColl[L, R]], Ref[L => T1]) forSome {type L; type R; type T1}] = unapply(exp.node) - } - - object mapSecond { - def unapply(d: Def[_]): Nullable[(Ref[PairColl[L, R]], Ref[R => T1]) forSome {type L; type R; type T1}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "mapSecond" && receiver.elem.isInstanceOf[PairCollElem[_, _, _]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[PairColl[L, R]], Ref[R => T1]) forSome {type L; type R; type T1}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[PairColl[L, R]], Ref[R => T1]) forSome {type L; type R; type T1}] = unapply(exp.node) - } - } - - object PairCollCompanionMethods { - } -} // of object PairColl - registerEntityObject("PairColl", PairColl) - -object CollBuilder extends EntityObject("CollBuilder") { - // entityConst: single const for each entity - import Liftables._ - import scala.reflect.{ClassTag, classTag} - type SCollBuilder = special.collection.CollBuilder - case class CollBuilderConst( - constValue: SCollBuilder - ) extends LiftedConst[SCollBuilder, CollBuilder] with CollBuilder - with Def[CollBuilder] with CollBuilderConstMethods { - val liftable: Liftable[SCollBuilder, CollBuilder] = LiftableCollBuilder - val resultType: Elem[CollBuilder] = liftable.eW - } - - trait CollBuilderConstMethods extends CollBuilder { thisConst: Def[_] => - - private val CollBuilderClass = classOf[CollBuilder] - - override def pairColl[A, B](as: Ref[Coll[A]], bs: Ref[Coll[B]]): Ref[PairColl[A, B]] = { - implicit val eA = as.eA -implicit val eB = bs.eA - asRep[PairColl[A, B]](mkMethodCall(self, - CollBuilderClass.getMethod("pairColl", classOf[Sym], classOf[Sym]), - Array[AnyRef](as, bs), - true, false, element[PairColl[A, B]])) - } - - override def fromItems[T](items: Ref[T]*)(implicit cT: Elem[T]): Ref[Coll[T]] = { - asRep[Coll[T]](mkMethodCall(self, - CollBuilderClass.getMethod("fromItems", classOf[Seq[_]], classOf[Elem[_]]), - Array[AnyRef](items, cT), - true, false, element[Coll[T]])) - } - - override def unzip[A, B](xs: Ref[Coll[(A, B)]]): Ref[(Coll[A], Coll[B])] = { - implicit val eA = xs.eA.eFst -implicit val eB = xs.eA.eSnd - asRep[(Coll[A], Coll[B])](mkMethodCall(self, - CollBuilderClass.getMethod("unzip", classOf[Sym]), - Array[AnyRef](xs), - true, false, element[(Coll[A], Coll[B])])) - } - - override def xor(left: Ref[Coll[Byte]], right: Ref[Coll[Byte]]): Ref[Coll[Byte]] = { - asRep[Coll[Byte]](mkMethodCall(self, - CollBuilderClass.getMethod("xor", classOf[Sym], classOf[Sym]), - Array[AnyRef](left, right), - true, false, element[Coll[Byte]])) - } - - override def replicate[T](n: Ref[Int], v: Ref[T]): Ref[Coll[T]] = { - implicit val eT = v.elem - asRep[Coll[T]](mkMethodCall(self, - CollBuilderClass.getMethod("replicate", classOf[Sym], classOf[Sym]), - Array[AnyRef](n, v), - true, false, element[Coll[T]])) - } - - override def emptyColl[T](implicit tT: Elem[T]): Ref[Coll[T]] = { - asRep[Coll[T]](mkMethodCall(self, - CollBuilderClass.getMethod("emptyColl", classOf[Elem[_]]), - Array[AnyRef](tT), - true, false, element[Coll[T]])) - } - } - - implicit object LiftableCollBuilder - extends Liftable[SCollBuilder, CollBuilder] { - lazy val eW: Elem[CollBuilder] = collBuilderElement - lazy val sourceType: RType[SCollBuilder] = { - RType[SCollBuilder] - } - def lift(x: SCollBuilder): Ref[CollBuilder] = CollBuilderConst(x) - def unlift(w: Ref[CollBuilder]): SCollBuilder = w match { - case Def(CollBuilderConst(x: SCollBuilder)) - => x.asInstanceOf[SCollBuilder] - case _ => unliftError(w) - } - } - - private val CollBuilderClass = classOf[CollBuilder] - - // entityAdapter for CollBuilder trait - case class CollBuilderAdapter(source: Ref[CollBuilder]) - extends Node with CollBuilder - with Def[CollBuilder] { - val resultType: Elem[CollBuilder] = element[CollBuilder] - override def transform(t: Transformer) = CollBuilderAdapter(t(source)) - - def pairColl[A, B](as: Ref[Coll[A]], bs: Ref[Coll[B]]): Ref[PairColl[A, B]] = { - implicit val eA = as.eA -implicit val eB = bs.eA - asRep[PairColl[A, B]](mkMethodCall(source, - CollBuilderClass.getMethod("pairColl", classOf[Sym], classOf[Sym]), - Array[AnyRef](as, bs), - true, true, element[PairColl[A, B]])) - } - - def fromItems[T](items: Ref[T]*)(implicit cT: Elem[T]): Ref[Coll[T]] = { - asRep[Coll[T]](mkMethodCall(source, - CollBuilderClass.getMethod("fromItems", classOf[Seq[_]], classOf[Elem[_]]), - Array[AnyRef](items, cT), - true, true, element[Coll[T]])) - } - - def unzip[A, B](xs: Ref[Coll[(A, B)]]): Ref[(Coll[A], Coll[B])] = { - implicit val eA = xs.eA.eFst -implicit val eB = xs.eA.eSnd - asRep[(Coll[A], Coll[B])](mkMethodCall(source, - CollBuilderClass.getMethod("unzip", classOf[Sym]), - Array[AnyRef](xs), - true, true, element[(Coll[A], Coll[B])])) - } - - def xor(left: Ref[Coll[Byte]], right: Ref[Coll[Byte]]): Ref[Coll[Byte]] = { - asRep[Coll[Byte]](mkMethodCall(source, - CollBuilderClass.getMethod("xor", classOf[Sym], classOf[Sym]), - Array[AnyRef](left, right), - true, true, element[Coll[Byte]])) - } - - def replicate[T](n: Ref[Int], v: Ref[T]): Ref[Coll[T]] = { - implicit val eT = v.elem - asRep[Coll[T]](mkMethodCall(source, - CollBuilderClass.getMethod("replicate", classOf[Sym], classOf[Sym]), - Array[AnyRef](n, v), - true, true, element[Coll[T]])) - } - - def emptyColl[T](implicit tT: Elem[T]): Ref[Coll[T]] = { - asRep[Coll[T]](mkMethodCall(source, - CollBuilderClass.getMethod("emptyColl", classOf[Elem[_]]), - Array[AnyRef](tT), - true, true, element[Coll[T]])) - } - } - - // entityUnref: single unref method for each type family - val createCollBuilderAdapter: Ref[CollBuilder] => CollBuilder = x => CollBuilderAdapter(x) - - implicit final def unrefCollBuilder(p: Ref[CollBuilder]): CollBuilder = - p.asInstanceOf[SingleRef[CollBuilder]].getAdapter( - p.node.isInstanceOf[CollBuilder], - createCollBuilderAdapter.asInstanceOf[Ref[CollBuilder] => CollBuilder]) - - // familyElem - class CollBuilderElem[To <: CollBuilder] - extends EntityElem[To] { - override val liftable: Liftables.Liftable[_, To] = asLiftable[SCollBuilder, To](LiftableCollBuilder) - - override protected def collectMethods: Map[java.lang.reflect.Method, MethodDesc] = { - super.collectMethods ++ - Elem.declaredMethods(classOf[CollBuilder], classOf[SCollBuilder], Set( - "pairColl", "fromItems", "unzip", "xor", "replicate", "emptyColl" - )) - } - } - - implicit lazy val collBuilderElement: Elem[CollBuilder] = - new CollBuilderElem[CollBuilder] - - implicit case object CollBuilderCompanionElem extends CompanionElem[CollBuilderCompanionCtor] - - abstract class CollBuilderCompanionCtor extends CompanionDef[CollBuilderCompanionCtor] with CollBuilderCompanion { - def resultType = CollBuilderCompanionElem - override def toString = "CollBuilder" - } - implicit final def unrefCollBuilderCompanionCtor(p: Ref[CollBuilderCompanionCtor]): CollBuilderCompanionCtor = - p.node.asInstanceOf[CollBuilderCompanionCtor] - - lazy val RCollBuilder: MutableLazy[CollBuilderCompanionCtor] = MutableLazy(new CollBuilderCompanionCtor { - private val thisClass = classOf[CollBuilderCompanion] - }) - - object CollBuilderMethods { - object pairColl { - def unapply(d: Def[_]): Nullable[(Ref[CollBuilder], Ref[Coll[A]], Ref[Coll[B]]) forSome {type A; type B}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "pairColl" && receiver.elem.isInstanceOf[CollBuilderElem[_]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[CollBuilder], Ref[Coll[A]], Ref[Coll[B]]) forSome {type A; type B}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[CollBuilder], Ref[Coll[A]], Ref[Coll[B]]) forSome {type A; type B}] = unapply(exp.node) - } - - object fromItems { - def unapply(d: Def[_]): Nullable[(Ref[CollBuilder], Seq[Ref[T]], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "fromItems" && receiver.elem.isInstanceOf[CollBuilderElem[_]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[CollBuilder], Seq[Ref[T]], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[CollBuilder], Seq[Ref[T]], Elem[T]) forSome {type T}] = unapply(exp.node) - } - - object unzip { - def unapply(d: Def[_]): Nullable[(Ref[CollBuilder], Ref[Coll[(A, B)]]) forSome {type A; type B}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "unzip" && receiver.elem.isInstanceOf[CollBuilderElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[CollBuilder], Ref[Coll[(A, B)]]) forSome {type A; type B}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[CollBuilder], Ref[Coll[(A, B)]]) forSome {type A; type B}] = unapply(exp.node) - } - - object xor { - def unapply(d: Def[_]): Nullable[(Ref[CollBuilder], Ref[Coll[Byte]], Ref[Coll[Byte]])] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "xor" && receiver.elem.isInstanceOf[CollBuilderElem[_]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[CollBuilder], Ref[Coll[Byte]], Ref[Coll[Byte]])]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[CollBuilder], Ref[Coll[Byte]], Ref[Coll[Byte]])] = unapply(exp.node) - } - - object replicate { - def unapply(d: Def[_]): Nullable[(Ref[CollBuilder], Ref[Int], Ref[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "replicate" && receiver.elem.isInstanceOf[CollBuilderElem[_]] => - val res = (receiver, args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[CollBuilder], Ref[Int], Ref[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[CollBuilder], Ref[Int], Ref[T]) forSome {type T}] = unapply(exp.node) - } - - object emptyColl { - def unapply(d: Def[_]): Nullable[(Ref[CollBuilder], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "emptyColl" && receiver.elem.isInstanceOf[CollBuilderElem[_]] => - val res = (receiver, args(0)) - Nullable(res).asInstanceOf[Nullable[(Ref[CollBuilder], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[CollBuilder], Elem[T]) forSome {type T}] = unapply(exp.node) - } - } - - object CollBuilderCompanionMethods { - } -} // of object CollBuilder - registerEntityObject("CollBuilder", CollBuilder) - - override def resetContext(): Unit = { - super.resetContext() - RColl.reset() - RPairColl.reset() - RCollBuilder.reset() - } - - registerModule(CollsModule) -} - -object CollsModule extends scalan.ModuleInfo("special.collection", "Colls") -} - -trait CollsModule extends special.collection.impl.CollsDefs {self: Library =>} diff --git a/library/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala b/library/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala deleted file mode 100644 index f46566435f..0000000000 --- a/library/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala +++ /dev/null @@ -1,159 +0,0 @@ -package wrappers.special - -import scala.language.{existentials,implicitConversions} -import scalan._ -import special.wrappers.WrappersModule - -package impl { -// Abs ----------------------------------- -trait WSpecialPredefsDefs extends scalan.Scalan with WSpecialPredefs { - self: WrappersModule => -import WOption._ -import WSpecialPredef._ - -object WSpecialPredef extends EntityObject("WSpecialPredef") { - private val WSpecialPredefClass = classOf[WSpecialPredef] - - // entityAdapter for WSpecialPredef trait - case class WSpecialPredefAdapter(source: Ref[WSpecialPredef]) - extends Node with WSpecialPredef - with Def[WSpecialPredef] { - val resultType: Elem[WSpecialPredef] = element[WSpecialPredef] - override def transform(t: Transformer) = WSpecialPredefAdapter(t(source)) - } - - // entityUnref: single unref method for each type family - implicit final def unrefWSpecialPredef(p: Ref[WSpecialPredef]): WSpecialPredef = { - if (p.node.isInstanceOf[WSpecialPredef]) p.node.asInstanceOf[WSpecialPredef] - else - WSpecialPredefAdapter(p) - } - - // familyElem - class WSpecialPredefElem[To <: WSpecialPredef] - extends EntityElem[To] { - } - - implicit lazy val wSpecialPredefElement: Elem[WSpecialPredef] = - new WSpecialPredefElem[WSpecialPredef] - - implicit case object WSpecialPredefCompanionElem extends CompanionElem[WSpecialPredefCompanionCtor] - - abstract class WSpecialPredefCompanionCtor extends CompanionDef[WSpecialPredefCompanionCtor] with WSpecialPredefCompanion { - def resultType = WSpecialPredefCompanionElem - override def toString = "WSpecialPredef" - } - implicit final def unrefWSpecialPredefCompanionCtor(p: Ref[WSpecialPredefCompanionCtor]): WSpecialPredefCompanionCtor = - p.node.asInstanceOf[WSpecialPredefCompanionCtor] - - lazy val RWSpecialPredef: MutableLazy[WSpecialPredefCompanionCtor] = MutableLazy(new WSpecialPredefCompanionCtor { - private val thisClass = classOf[WSpecialPredefCompanion] - - def optionGetOrElse[A](opt: Ref[WOption[A]], default: Ref[A]): Ref[A] = { - implicit val eA = opt.eA - asRep[A](mkMethodCall(self, - thisClass.getMethod("optionGetOrElse", classOf[Sym], classOf[Sym]), - Array[AnyRef](opt, default), - true, false, element[A])) - } - - def none[A](implicit emA: Elem[A]): Ref[WOption[A]] = { - asRep[WOption[A]](mkMethodCall(self, - thisClass.getMethod("none", classOf[Elem[_]]), - Array[AnyRef](emA), - true, false, element[WOption[A]])) - } - - def some[A](x: Ref[A]): Ref[WOption[A]] = { - implicit val eA = x.elem - asRep[WOption[A]](mkMethodCall(self, - thisClass.getMethod("some", classOf[Sym]), - Array[AnyRef](x), - true, false, element[WOption[A]])) - } - - def cast[T](v: Ref[Any])(implicit emT: Elem[T]): Ref[WOption[T]] = { - asRep[WOption[T]](mkMethodCall(self, - thisClass.getMethod("cast", classOf[Sym], classOf[Elem[_]]), - Array[AnyRef](v, emT), - true, false, element[WOption[T]])) - } - - def loopUntil[A](s1: Ref[A], isMatch: Ref[A => Boolean], step: Ref[A => A]): Ref[A] = { - implicit val eA = s1.elem - asRep[A](mkMethodCall(self, - thisClass.getMethod("loopUntil", classOf[Sym], classOf[Sym], classOf[Sym]), - Array[AnyRef](s1, isMatch, step), - true, false, element[A])) - } - }) - - object WSpecialPredefMethods { - } - - object WSpecialPredefCompanionMethods { - object optionGetOrElse { - def unapply(d: Def[_]): Nullable[(Ref[WOption[A]], Ref[A]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "optionGetOrElse" && receiver.elem == WSpecialPredefCompanionElem => - val res = (args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[WOption[A]], Ref[A]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[WOption[A]], Ref[A]) forSome {type A}] = unapply(exp.node) - } - - object none { - def unapply(d: Def[_]): Nullable[Elem[A] forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "none" && receiver.elem == WSpecialPredefCompanionElem => - val res = args(0) - Nullable(res).asInstanceOf[Nullable[Elem[A] forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Elem[A] forSome {type A}] = unapply(exp.node) - } - - object some { - def unapply(d: Def[_]): Nullable[Ref[A] forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "some" && receiver.elem == WSpecialPredefCompanionElem => - val res = args(0) - Nullable(res).asInstanceOf[Nullable[Ref[A] forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[A] forSome {type A}] = unapply(exp.node) - } - - object cast { - def unapply(d: Def[_]): Nullable[(Ref[Any], Elem[T]) forSome {type T}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "cast" && receiver.elem == WSpecialPredefCompanionElem => - val res = (args(0), args(1)) - Nullable(res).asInstanceOf[Nullable[(Ref[Any], Elem[T]) forSome {type T}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[Any], Elem[T]) forSome {type T}] = unapply(exp.node) - } - - object loopUntil { - def unapply(d: Def[_]): Nullable[(Ref[A], Ref[A => Boolean], Ref[A => A]) forSome {type A}] = d match { - case MethodCall(receiver, method, args, _) if method.getName == "loopUntil" && receiver.elem == WSpecialPredefCompanionElem => - val res = (args(0), args(1), args(2)) - Nullable(res).asInstanceOf[Nullable[(Ref[A], Ref[A => Boolean], Ref[A => A]) forSome {type A}]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[(Ref[A], Ref[A => Boolean], Ref[A => A]) forSome {type A}] = unapply(exp.node) - } - } -} // of object WSpecialPredef - registerEntityObject("WSpecialPredef", WSpecialPredef) - - override def resetContext(): Unit = { - super.resetContext() - RWSpecialPredef.reset() - } - - registerModule(WSpecialPredefsModule) -} - -object WSpecialPredefsModule extends scalan.ModuleInfo("wrappers.special", "WSpecialPredefs") -} - -trait WSpecialPredefsModule extends wrappers.special.impl.WSpecialPredefsDefs {self: WrappersModule =>} diff --git a/sc/src/test/scala/thelastpackage/ZLastSpec.scala b/sc/src/test/scala/thelastpackage/ZLastSpec.scala new file mode 100644 index 0000000000..c714036f50 --- /dev/null +++ b/sc/src/test/scala/thelastpackage/ZLastSpec.scala @@ -0,0 +1,23 @@ +package thelastpackage + +import org.scalatest.BeforeAndAfterAll +import org.scalatest.propspec.AnyPropSpec +import sigmastate.ReflectionGenerator + +/** This spec is the last in queue for execution when running all the tests. + * It is thus useful to do something after all the tests have been executed. + * For example, some generators (like ReflectionGenerator) and Profiler collect + * runtime information about the program execution. + * This information can be printed out after all the tests have been executed. + */ +class ZLastSpec extends AnyPropSpec with BeforeAndAfterAll { + + property("the last property") { + + } + + override protected def afterAll(): Unit = { +// uncomment to see the report +// println(ReflectionGenerator.generateReport) + } +}