diff --git a/.travis.yml b/.travis.yml index db05759cbc..d3899c3d97 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,6 +8,9 @@ cache: - "$HOME/.ivy2/cache" - "$HOME/.sbt" language: scala +scala: + - 2.12.10 + - 2.11.12 jdk: - oraclejdk8 stages: @@ -16,27 +19,22 @@ stages: - name: release if: tag =~ ^v - name: snapshot - if: NOT tag IS present + if: "(NOT tag IS present) AND (type = push)" jobs: include: - stage: test - script: sbt -jvm-opts .travis.jvmopts test + script: sbt -jvm-opts .travis.jvmopts +test # enable scoverage after SpamSpecification timeout issue is resolved # script: sbt -jvm-opts .travis.jvmopts coverage test # - stage: coverage # script: sbt coverageReport coveralls - stage: release - script: sbt -jvm-opts .travis.jvmopts publishSigned sonatypeBundleRelease + script: openssl aes-256-cbc -K $encrypted_98cf3af00429_key -iv $encrypted_98cf3af00429_iv -in ci/secring.asc.enc -out ci/secring.asc -d && gpg --import ci/secring.asc && sbt -jvm-opts .travis.jvmopts +publishSigned sonatypeBundleRelease - stage: snapshot - script: sbt -jvm-opts .travis.jvmopts publish + script: sbt -jvm-opts .travis.jvmopts +publish env: global: - secure: IGwd+lY2TfkAeX1SfzaYBwyhiiPaFrTxoF0e+4R1bkGxiGCce1hBYjn15z1HRfK+k3hgEZh/FBG7dv8LQfNWQ6AJY5PQ2zwckd4ArYMhTVpiY4eRzUMqO1/gjTCCbbTjfFKOMsR2pAw+TGeglqoX4eyziIaS8nR901dZcFvHuC1Fr5EdKFZ0x+WHnX8vaSQoDE4u1MoBnyo5cRVumXG+xvs1Q0nZXm/hd/Flfx5u3L7veKAkGtvbHmdsJoSSySTbc1MGYQtofQjbjd9AVvUhgfP32J63UCC2SqgWWKVvIjW+dUn414BV3lelnWR3FdzhC7AUJqYWVfSILh1aj3STnizRnjtCScmyoRz4ldUQ3jr4jBJOREUEus5YH2EqY1MGjX+8kUu9IjDYiQyNy1EdivcmMlXCOcAW2mi4rGDRxZOeFt1ZSHzxqSghZOFwvk/OFcdDzV4/3OnAcGz8LH5qjZU/edjmfkSls5CqxuAFqeD7RZWIu0ccjt6dzQZAf02lBX9kQuwIruC4x4E0iEjml7jmaEeOT4Hqk7wAo6EFMSEkj4EnS/Kln6Wr7JBut5qrMk0+PDgvxaKCaN8LeycCSQdoXfPO602WzfasNcOJexSmGMAE5NYfeXjq1h3F9AVHJ3TbNAOdlQTHbSOqt7WO10JphljYnFEu4aSzvaA3E60= - secure: g4Egz1orKgCAgTckMYHHbpsFY8ppldLLUkBi0GasHN4M2zhfYlqzaJ+ZZ4soMPNshcS3XutGS+/ERF5zrnHF1C9h3txW6AJkgMkTF1q4UyKan25chdPnz1nNUrdQOvaCA4CzLIN3aQAHN40p44ELxfNTARTfbUAIcqNSrKmXZsUbhQg9yyM+gFL6cCw7SYQphC9GJq4mvW19dzzpU8MQ0AtktB6mscuUyiWgniHsnFAmeQBv0csCiMyjUsT1buIkO0gSvZBKkLXu7kXhash/mLjrBYGapVGGFORA3pWy9JCB9OfxV8Bj1wNUqPyAImjGgVfgK6RxOnQ/C4GTsf8uVH/sYIiPnzPmbCrO7fQee68/+SWtZc1kko8HuiqHvouNHmKQy+Hwku2AIdp6nZDhOuFtQTP1PbkYLrdNj1evAI6913rq51e7vDWTriWmOKjMz2m4Tj2HGJx0VS0pNOZkpxwVhHOdyc1UXurpBKgkYis1HVcaEM3trFzhsMf7kllNvJLA1COwg7KbVebKwA9gXfYrKAp6p76YMaSYodSDq9VaSDPF/2MVCZYXs+FAUZ3MzcsAZ7TegSX2OWrrneGArjcQgdMLUetm+UgBFZF7pG3BpjMLVwMgp9ulUNkq1sP1vLU08cvQv6A3W/kcyrVyCNzg80XTQqDpxz7hCTbyBSw= - secure: gfhEv/PXEckwZPnwJHl4fBCJKCrCKK4KMeYCPNZZtKuV1gC4mZscvECm8r+kgB+o2G3i4tEIYcIC5Jbdcbjf4bk6uNZW/X3dna0irl/Mdswt7rTLzLan1rPz3k8Bylgs8ehETFBGr8HyNitEa8ODyaEXa84MPQaucXUmpHS+sUEhQn0Z70T70d1H9ZubUhGv9VLltNoSWkPGW5CPZlpQTHl63ZShfmylfQuQVTbVMdL8LLUHn2x2edlDKMGD8YPH5d+of0AKc3IKnlnMM36WjgYVsf1yehfLi0NH/b2Dzk7wLjetu/bw8Cu9Ne6/u0Lu83Hbh4DyS2iPQivDUGB+JXlHDFI4uji3GurnvpFDku1gbc4HVoFqhgOWyXQAiRllj2BXmq2vwp6797TUG4HrD2EVzIJV7eIZdWNN/QttZtNxNdSbBq8QQc92G2SU4q7PcogMSr0LpX05SfyL1sMgX2WeGzFzyMIu/+rAJhG0lPt7krBxEfQrRtTLdJ9eyeFjFQlxM6G/9gk68j+Nida6KunLwe9QEl2T+t1YbE4i9pndoCMJFxAOjirhw5OM3PfSWfb/mU7zXd4PSNK7RQIdOaPJff5C6UEM7h/iQ6riRZp1Pn7d/rxppTXsvUbtvwUYnkoOeUZyMvQNQsPI6Slns8jWl0zp5XiTmzSRVOuH3ME= # decrypt the private key (exported via https://docs.scala-lang.org/overviews/contributors/index.html#export-your-pgp-key-pair ) -before_install: -- openssl aes-256-cbc -K $encrypted_98cf3af00429_key -iv $encrypted_98cf3af00429_iv - -in ci/secring.asc.enc -out ci/secring.asc -d -# import decrypted private key -before_script: gpg --import ci/secring.asc \ No newline at end of file diff --git a/build.sbt b/build.sbt index e1b62c16dc..1fffacbb88 100644 --- a/build.sbt +++ b/build.sbt @@ -6,11 +6,20 @@ organization := "org.scorexfoundation" name := "sigma-state" +lazy val scala212 = "2.12.10" +lazy val scala211 = "2.11.12" +crossScalaVersions := Seq(scala212, scala211) +scalaVersion := scala212 + +javacOptions ++= + "-source" :: "1.7" :: + "-target" :: "1.7" :: + Nil + lazy val allConfigDependency = "compile->compile;test->test" lazy val commonSettings = Seq( organization := "org.scorexfoundation", - scalaVersion := "2.12.8", resolvers += Resolver.sonatypeRepo("public"), licenses := Seq("CC0" -> url("https://creativecommons.org/publicdomain/zero/1.0/legalcode")), homepage := Some(url("https://github.com/ScorexFoundation/sigmastate-interpreter")), @@ -34,7 +43,7 @@ lazy val commonSettings = Seq( , publishMavenStyle := true, - publishTo := sonatypePublishToBundle.value, + publishTo := sonatypePublishToBundle.value ) enablePlugins(GitVersioning) @@ -68,16 +77,15 @@ version in ThisBuild := { git.gitUncommittedChanges in ThisBuild := true -val bouncycastleBcprov = "org.bouncycastle" % "bcprov-jdk15on" % "1.60" -val scrypto = "org.scorexfoundation" %% "scrypto" % "2.1.6" -val scorexUtil = "org.scorexfoundation" %% "scorex-util" % "0.1.4" +val bouncycastleBcprov = "org.bouncycastle" % "bcprov-jdk15on" % "1.64" +val scrypto = "org.scorexfoundation" %% "scrypto" % "2.1.7" +val scorexUtil = "org.scorexfoundation" %% "scorex-util" % "0.1.6" val macroCompat = "org.typelevel" %% "macro-compat" % "1.1.1" val paradise = "org.scalamacros" %% "paradise" % "2.1.0" cross CrossVersion.full val debox = "org.spire-math" %% "debox" % "0.8.0" val kiama = "org.bitbucket.inkytonik.kiama" %% "kiama" % "2.1.0" val fastparse = "com.lihaoyi" %% "fastparse" % "1.0.0" val commonsIo = "commons-io" % "commons-io" % "2.5" -val configs = "com.github.kxbmap" %% "configs" % "0.4.4" val specialVersion = "0.6.1" val meta = "io.github.scalan" %% "meta" % specialVersion @@ -90,7 +98,7 @@ val testingDependencies = Seq( "org.scalacheck" %% "scalacheck" % "1.14.+" % "test", "com.storm-enroute" %% "scalameter" % "0.8.2" % Test, "junit" % "junit" % "4.12" % "test", - "com.novocode" % "junit-interface" % "0.11" % "test", + "com.novocode" % "junit-interface" % "0.11" % "test" ) lazy val testSettings = Seq( @@ -106,7 +114,6 @@ libraryDependencies ++= Seq( scrypto, scorexUtil, "org.bouncycastle" % "bcprov-jdk15on" % "1.+", - "com.typesafe.akka" %% "akka-actor" % "2.4.+", kiama, fastparse, debox ) ++ testingDependencies @@ -123,8 +130,8 @@ scalacOptions ++= Seq("-feature", "-deprecation") // see https://github.com/eclipse/jetty.project/issues/3244 // these options applied only in "compile" task since scalac crashes on scaladoc compilation with "-release 8" // see https://github.com/scala/community-builds/issues/796#issuecomment-423395500 -javacOptions in(Compile, compile) ++= Seq("-target", "8", "-source", "8" ) -scalacOptions in(Compile, compile) ++= Seq("-release", "8") +//javacOptions in(Compile, compile) ++= Seq("-target", "8", "-source", "8" ) +//scalacOptions in(Compile, compile) ++= Seq("-release", "8") //uncomment lines below if the Scala compiler hangs to see where it happens //scalacOptions in Compile ++= Seq("-Xprompt", "-Ydebug", "-verbose" ) @@ -184,7 +191,7 @@ lazy val libraryimpl = Project("library-impl", file("library-impl")) lazy val core = Project("core", file("core")) .dependsOn(common % allConfigDependency, libraryapi % allConfigDependency) .settings(commonSettings, - libraryDependencies ++= Seq( configs, debox )) + libraryDependencies ++= Seq( debox )) .settings(publish / skip := true) lazy val library = Project("library", file("library")) @@ -196,15 +203,26 @@ lazy val library = Project("library", file("library")) lazy val sigmaconf = Project("sigma-conf", file("sigma-conf")) .settings(commonSettings, - libraryDependencies ++= Seq( - plugin, libraryconf - )) + libraryDependencies ++= ( + if(scalaBinaryVersion.value == "2.11") + Seq.empty + else + Seq(plugin, libraryconf) + ), + skip in compile := scalaBinaryVersion.value == "2.11" + ) .settings(publish / skip := true) lazy val scalanizer = Project("scalanizer", file("scalanizer")) .dependsOn(sigmaconf, libraryapi, libraryimpl) .settings(commonSettings, - libraryDependencies ++= Seq(meta, plugin), + libraryDependencies ++= ( + if(scalaBinaryVersion.value == "2.11") + Seq.empty + else + Seq(meta, plugin) + ), + skip in compile := scalaBinaryVersion.value == "2.11", assemblyOption in assembly ~= { _.copy(includeScala = false, includeDependency = true) }, assemblyMergeStrategy in assembly := { case PathList("scalan", xs @ _*) => MergeStrategy.first @@ -276,7 +294,7 @@ lazy val rootSettings = Seq( libraryDependencies := libraryDependencies.all(aggregateCompile).value.flatten, mappings in (Compile, packageSrc) ++= (mappings in(Compile, packageSrc)).all(aggregateCompile).value.flatten, mappings in (Test, packageBin) ++= (mappings in(Test, packageBin)).all(aggregateCompile).value.flatten, - mappings in(Test, packageSrc) ++= (mappings in(Test, packageSrc)).all(aggregateCompile).value.flatten, + mappings in(Test, packageSrc) ++= (mappings in(Test, packageSrc)).all(aggregateCompile).value.flatten ) def runErgoTask(task: String, sigmastateVersion: String, log: Logger): Unit = { diff --git a/common/src/main/java/scalan/Reified.java b/common/src/main/java/scalan/Reified.java index bd49e53118..360340f678 100644 --- a/common/src/main/java/scalan/Reified.java +++ b/common/src/main/java/scalan/Reified.java @@ -12,7 +12,7 @@ * The need for reified type arguments come from ClassTag[T], RType[T] context bounds or * implicit parameters in the source code. */ -@Target({ElementType.TYPE, ElementType.TYPE_PARAMETER}) +@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Reified { String value() default ""; diff --git a/common/src/main/scala/scalan/util/CollectionUtil.scala b/common/src/main/scala/scalan/util/CollectionUtil.scala index aae8ebdca4..bba14c516f 100644 --- a/common/src/main/scala/scalan/util/CollectionUtil.scala +++ b/common/src/main/scala/scalan/util/CollectionUtil.scala @@ -168,7 +168,12 @@ object CollectionUtil { implicit class HashMapOps[K,V](val source: java.util.HashMap[K,V]) extends AnyVal { def toImmutableMap: Map[K,V] = { var res = Map[K,V]() - source.forEach((t: K, u: V) => res = res + (t -> u)) + // don't beautify: at least this code should compile under java 1.7 + val entries = source.entrySet().iterator() + while (entries.hasNext) { + val e = entries.next() + res = res + (e.getKey -> e.getValue) + } res } } diff --git a/common/src/test/scala/scalan/util/CollectionUtilTests.scala b/common/src/test/scala/scalan/util/CollectionUtilTests.scala index be92a01790..7f9b667456 100644 --- a/common/src/test/scala/scalan/util/CollectionUtilTests.scala +++ b/common/src/test/scala/scalan/util/CollectionUtilTests.scala @@ -65,14 +65,14 @@ class CollectionUtilTests extends BaseTests { val xs = Seq(1, 2, 3) { - val (ints, strings, plus1s) = xs.mapUnzip(x => (x, x.toString, x + 1)) + val (ints, strings, plus1s) = xs.mapUnzip((x: Int) => (x, x.toString, x + 1)) ints shouldBe Seq(1, 2, 3) strings shouldBe Seq("1", "2", "3") plus1s shouldBe Seq(2, 3, 4) } { - val (ints, strings) = xs.mapUnzip(x => (x, x.toString)) + val (ints, strings) = xs.mapUnzip((x: Int) => (x, x.toString)) ints shouldBe Seq(1, 2, 3) strings shouldBe Seq("1", "2", "3") } diff --git a/common/src/test/scala/scalan/util/GraphUtilTests.scala b/common/src/test/scala/scalan/util/GraphUtilTests.scala index b467ab6e2f..213d8bc688 100644 --- a/common/src/test/scala/scalan/util/GraphUtilTests.scala +++ b/common/src/test/scala/scalan/util/GraphUtilTests.scala @@ -17,10 +17,12 @@ class GraphUtilTests extends BaseNestedTests { List() // 6 ) - val neighbours: DFunc[Int, DBuffer[Int]] = { node: Int => - val ns = DBuffer.empty[Int] - graph(node) foreach (ns.+=) - ns + val neighbours: DFunc[Int, DBuffer[Int]] = new DFunc[Int, DBuffer[Int]] { + def apply(node: Int) = { + val ns = DBuffer.empty[Int] + graph(node) foreach (ns.+=) + ns + } } it("depthFirstSetFrom") { @@ -31,7 +33,9 @@ class GraphUtilTests extends BaseNestedTests { depthFirstSetFrom(DBuffer(0))(neighbours) shouldBe (DSet(0, 1, 2, 3, 4, 5, 6)) } it("depthFirstOrderFrom") { - val succ: DFunc[Int, DBuffer[Int]] = {id: Int => DBuffer(graph(id):_*)} + val succ: DFunc[Int, DBuffer[Int]] = new DFunc[Int, DBuffer[Int]] { + def apply(id: Int) = DBuffer(graph(id):_*) + } depthFirstOrderFrom(DBuffer(6), succ) shouldBe (DBuffer(6)) depthFirstOrderFrom(DBuffer(5), succ) shouldBe (DBuffer(6, 5)) depthFirstOrderFrom(DBuffer(3), succ) shouldBe (DBuffer(6, 5, 3)) diff --git a/core/src/main/scala/scalan/Plugins.scala b/core/src/main/scala/scalan/Plugins.scala deleted file mode 100644 index a744df0958..0000000000 --- a/core/src/main/scala/scalan/Plugins.scala +++ /dev/null @@ -1,25 +0,0 @@ -package scalan - -import java.io.File -import com.typesafe.config.ConfigFactory -import scalan.util.ClassLoaderUtil - -object Plugins { - val extraClassPathKey = "plugins.extraClassPath" - - lazy val config0 = ConfigFactory.load().getConfig("scalan") - lazy val pluginClassLoader = { - val thisClassLoader = getClass.getClassLoader - - config0.getString(extraClassPathKey) match { - case "" => - thisClassLoader - case path => - val files = path.split(File.pathSeparatorChar).map(new File(_)) - ClassLoaderUtil.URLClassLoader(files, thisClassLoader) - } - } - lazy val configWithPlugins = ConfigFactory.load(pluginClassLoader).getConfig("scalan") - - def loadClass(name: String) = pluginClassLoader.loadClass(name) -} diff --git a/core/src/main/scala/scalan/Scalan.scala b/core/src/main/scala/scalan/Scalan.scala index 6b037ccea5..9ce1599469 100644 --- a/core/src/main/scala/scalan/Scalan.scala +++ b/core/src/main/scala/scalan/Scalan.scala @@ -30,7 +30,7 @@ class Scalan with Functions with IfThenElse with Transforming - with GraphVizExport +// with GraphVizExport with Thunks with Entities with Modules diff --git a/core/src/main/scala/scalan/compilation/GraphVizExport.scala b/core/src/main/scala/scalan/compilation/GraphVizExport.scala index 8c90f221b6..7c3b4e20bd 100644 --- a/core/src/main/scala/scalan/compilation/GraphVizExport.scala +++ b/core/src/main/scala/scalan/compilation/GraphVizExport.scala @@ -3,11 +3,7 @@ package scalan.compilation import java.awt.Desktop import java.io.{PrintWriter, File} -import configs.Configs -import configs.syntax._ -import com.typesafe.config.{ConfigUtil, Config} -import configs.Result.{Success, Failure} -import scalan.{Plugins, Scalan, Base} +import scalan.{Scalan, Base} import scalan.util.{ProcessUtil, FileUtil, StringUtil, ScalaNameUtil} import scala.collection.immutable.StringOps @@ -18,12 +14,7 @@ trait GraphVizExport extends Base { self: Scalan => case class GraphFile(file: File, fileType: String) { def open() = { - Plugins.configWithPlugins.get[String](ConfigUtil.joinPath("graphviz", "viewer", fileType)) match { - case Failure(_) => - Desktop.getDesktop.open(file) - case Success(command) => - ProcessUtil.launch(Seq(command, file.getAbsolutePath)) - } + Desktop.getDesktop.open(file) } } @@ -458,7 +449,6 @@ case object Portrait extends Orientation case object Landscape extends Orientation object Orientation { - implicit val orientationC: Configs[Orientation] = Configs[Orientation] } sealed trait ControlFlowStyle @@ -522,7 +512,6 @@ case class GraphVizConfig(emitGraphs: Boolean, } object GraphVizConfig { - lazy val config = Plugins.configWithPlugins.getConfig("graphviz") // not made implicit because it would be too easy to use // it accidentally instead of passing up // For some reason, return type has to be given explicitly @@ -536,9 +525,7 @@ object GraphVizConfig { typeAliasEdges = false, emitMetadata = false, showLambdaReturnSym = false - ) //config.extract[GraphVizConfig] + ) val none: GraphVizConfig = default.copy(emitGraphs = false) - - def from(config: Config): GraphVizConfig = config.withFallback(this.config).extract[GraphVizConfig].value } diff --git a/core/src/main/scala/scalan/primitives/Functions.scala b/core/src/main/scala/scalan/primitives/Functions.scala index 63f88f4a34..1fc9844344 100644 --- a/core/src/main/scala/scalan/primitives/Functions.scala +++ b/core/src/main/scala/scalan/primitives/Functions.scala @@ -1,13 +1,17 @@ package scalan.primitives import java.util + import scalan.staged.ProgramGraphs import scalan.util.GraphUtil import scalan.{Lazy, Base, Nullable, Scalan} import debox.{Buffer => DBuffer} + import scala.language.implicitConversions import spire.syntax.all.cfor +import scala.collection.Seq + trait Functions extends Base with ProgramGraphs { self: Scalan => implicit class LambdaOps[A,B](f: Ref[A => B]) { @@ -102,9 +106,9 @@ trait Functions extends Base with ProgramGraphs { self: Scalan => def productArity: Int = 2 // AstGraph implementation - val boundVars = Array(x) + val boundVars: Seq[Sym] = Array[Sym](x) val boundVarId = x.node._nodeId - val roots = Array(y) + val roots: Seq[Sym] = Array(y) override lazy val rootIds: DBuffer[Int] = super.rootIds diff --git a/core/src/main/scala/scalan/primitives/Thunks.scala b/core/src/main/scala/scalan/primitives/Thunks.scala index 11eaf7162e..739285f648 100644 --- a/core/src/main/scala/scalan/primitives/Thunks.scala +++ b/core/src/main/scala/scalan/primitives/Thunks.scala @@ -8,6 +8,8 @@ import spire.syntax.all.cfor import scala.reflect.runtime.universe._ import scalan.util.{Covariant, GraphUtil} +import scala.collection.Seq + trait Thunks extends Functions with GraphVizExport { self: Scalan => type Th[+T] = Ref[Thunk[T]] @@ -109,11 +111,11 @@ trait Thunks extends Functions with GraphVizExport { self: Scalan => def productArity: Int = 1 override def boundVars = Nil - override lazy val freeVars = if (schedule.isEmpty) Array(root) else super.freeVars + override lazy val freeVars: Seq[Sym] = if (schedule.isEmpty) Array(root) else super.freeVars override protected def getDeps: Array[Sym] = freeVars.toArray - val roots = Array(root) + val roots: Seq[Sym] = Array(root) override lazy val rootIds: DBuffer[Int] = super.rootIds override def isIdentity: Boolean = false } @@ -139,7 +141,7 @@ trait Thunks extends Functions with GraphVizExport { self: Scalan => def scheduleForResult(root: Ref[Any]): DBuffer[Int] = { val sch = GraphUtil.depthFirstOrderFrom( DBuffer(root.node.nodeId), - { id: Int => + new DFunc[Int, DBuffer[Int]] { def apply(id: Int) = { val deps = getSym(id).node.deps val res = DBuffer.ofSize[Int](deps.length) cfor(0)(_ < deps.length, _ + 1) { i => @@ -149,7 +151,7 @@ trait Thunks extends Functions with GraphVizExport { self: Scalan => res += id } res - } + }} ) sch } diff --git a/core/src/main/scala/scalan/staged/ProgramGraphs.scala b/core/src/main/scala/scalan/staged/ProgramGraphs.scala index 12b10624dd..bcffabc964 100644 --- a/core/src/main/scala/scalan/staged/ProgramGraphs.scala +++ b/core/src/main/scala/scalan/staged/ProgramGraphs.scala @@ -35,7 +35,7 @@ trait ProgramGraphs extends AstGraphs { self: Scalan => override lazy val scheduleIds = { val neighbours: DFunc[Int, DBuffer[Int]] = filterNode match { case Nullable(pred) => - { (id: Int) => + new DFunc[Int, DBuffer[Int]] { def apply(id: Int) = { val deps = getSym(id).node.deps val len = deps.length val res = DBuffer.ofSize[Int](len) @@ -45,9 +45,9 @@ trait ProgramGraphs extends AstGraphs { self: Scalan => res += sym.node.nodeId } res - } + }} case _ => - { (id: Int) => + new DFunc[Int, DBuffer[Int]] { def apply(id: Int) = { val deps = getSym(id).node.deps val len = deps.length val res = DBuffer.ofSize[Int](len) @@ -57,7 +57,7 @@ trait ProgramGraphs extends AstGraphs { self: Scalan => res += sym.node.nodeId } res - } + }} } val sch = GraphUtil.depthFirstOrderFrom(rootIds, neighbours) sch diff --git a/docs/notes.md b/docs/notes.md new file mode 100644 index 0000000000..0f7a441ee7 --- /dev/null +++ b/docs/notes.md @@ -0,0 +1,24 @@ +## Approximate sizes of different dependencies + +These dependencies can be removed with simple refactoring + +| Jar | Size, Kb | +|---------------|---------------| +| kiama_2.12-2.1.0.jar | 652 | +| - jline-2.14.3.jar | 268 | +| - scallop_2.12-2.1.1.jar | 348 | +| - dsprofile_2.12-0.4.0.jar | 49 | +| - dsprofile_2.12-0.4.0.jar | 49 | +| - dsinfo_2.12-0.4.0.jar | 15 | +| - jsr305-3.0.2.jar | 20 | +| com.typesafe.config:config-1.3.3.jar | 286 | +| commons-io-2.5.jar | 209 | +| cats-core_2.12-1.4.0.jar | 4400 | +| - cats-kernel_2.12-1.4.0.jar | 3200 | +| spire_2.12-0.14.1.jar | 7700 | +| - algebra_2.12-0.7.0.jar | 1100 | +| - spire-macros_2.12-0.14.1.jar | 73 | + + + + diff --git a/library/src/test/scala/special/collections/CollGens.scala b/library/src/test/scala/special/collections/CollGens.scala index b77e4d305b..00b1ab68cc 100644 --- a/library/src/test/scala/special/collections/CollGens.scala +++ b/library/src/test/scala/special/collections/CollGens.scala @@ -81,7 +81,7 @@ trait CollGens { testSuite => getCollPairGenFinal(collGen, collGen), getCollPairGenLeft(lg, collGen), getCollPairGenRight(collGen, rg), - getCollPairGenBoth(lg, rg), + getCollPairGenBoth(lg, rg) ) return gen } diff --git a/project/plugins.sbt b/project/plugins.sbt index 0c2445295a..5a6217d66b 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,6 +1,5 @@ logLevel := Level.Warn -//addSbtPlugin("com.github.tkawachi" % "sbt-lock" % "0.4.0") addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.9") addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.9.0") addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "1.0.0") diff --git a/sigmastate/src/main/scala/org/ergoplatform/JsonCodecs.scala b/sigmastate/src/main/scala/org/ergoplatform/JsonCodecs.scala index b76f393d36..7391f8e324 100644 --- a/sigmastate/src/main/scala/org/ergoplatform/JsonCodecs.scala +++ b/sigmastate/src/main/scala/org/ergoplatform/JsonCodecs.scala @@ -21,6 +21,7 @@ import sigmastate.{AvlTreeData, AvlTreeFlags, SType} import special.collection.Coll import special.sigma.{AnyValue, Header, PreHeader} import scala.util.Try +import sigmastate.utils.Helpers._ trait JsonCodecs { @@ -36,73 +37,73 @@ trait JsonCodecs { Either.catchNonFatal(throwsBlock).leftMap(e => DecodingFailure(e.toString, cursor.history)) } - private def bytesDecoder[T](transform: Array[Byte] => T): Decoder[T] = { implicit cursor => + private def bytesDecoder[T](transform: Array[Byte] => T): Decoder[T] = Decoder.instance({ implicit cursor => for { str <- cursor.as[String] bytes <- fromTry(ErgoAlgos.decode(str)) } yield transform(bytes) - } + }) - implicit val anyValueEncoder: Encoder[AnyValue] = { anyval => DataJsonEncoder.encodeAnyValue(anyval) } + implicit val anyValueEncoder: Encoder[AnyValue] = Encoder.instance({ anyval => DataJsonEncoder.encodeAnyValue(anyval) }) - implicit val anyValueDecoder: Decoder[AnyValue] = { implicit cursor => + implicit val anyValueDecoder: Decoder[AnyValue] = Decoder.instance({ implicit cursor => fromTry(Try.apply(DataJsonEncoder.decodeAnyValue(cursor.value))) - } + }) - implicit val sigmaBigIntEncoder: Encoder[special.sigma.BigInt] = { bigInt => + implicit val sigmaBigIntEncoder: Encoder[special.sigma.BigInt] = Encoder.instance({ bigInt => JsonNumber.fromDecimalStringUnsafe(bigInt.asInstanceOf[WrapperOf[BigInteger]].wrappedValue.toString).asJson - } + }) - implicit val sigmaBigIntDecoder: Decoder[special.sigma.BigInt] = { implicit cursor => + implicit val sigmaBigIntDecoder: Decoder[special.sigma.BigInt] = Decoder.instance({ implicit cursor => for { jsonNumber <- cursor.as[JsonNumber] bigInt <- fromOption(jsonNumber.toBigInt) } yield CBigInt(bigInt.bigInteger) - } + }) - implicit val arrayBytesEncoder: Encoder[Array[Byte]] = ErgoAlgos.encode(_).asJson + implicit val arrayBytesEncoder: Encoder[Array[Byte]] = Encoder.instance(ErgoAlgos.encode(_).asJson) implicit val arrayBytesDecoder: Decoder[Array[Byte]] = bytesDecoder(x => x) - implicit val collBytesEncoder: Encoder[Coll[Byte]] = ErgoAlgos.encode(_).asJson + implicit val collBytesEncoder: Encoder[Coll[Byte]] = Encoder.instance(ErgoAlgos.encode(_).asJson) implicit val collBytesDecoder: Decoder[Coll[Byte]] = bytesDecoder(Colls.fromArray(_)) - implicit val adKeyEncoder: Encoder[ADKey] = _.array.asJson + implicit val adKeyEncoder: Encoder[ADKey] = Encoder.instance(_.array.asJson) implicit val adKeyDecoder: Decoder[ADKey] = bytesDecoder(ADKey @@ _) - implicit val adDigestEncoder: Encoder[ADDigest] = _.array.asJson + implicit val adDigestEncoder: Encoder[ADDigest] = Encoder.instance(_.array.asJson) implicit val adDigestDecoder: Decoder[ADDigest] = bytesDecoder(ADDigest @@ _) - implicit val digest32Encoder: Encoder[Digest32] = _.array.asJson + implicit val digest32Encoder: Encoder[Digest32] = Encoder.instance(_.array.asJson) implicit val digest32Decoder: Decoder[Digest32] = bytesDecoder(Digest32 @@ _) - implicit val assetEncoder: Encoder[(TokenId, Long)] = { asset => + implicit val assetEncoder: Encoder[(TokenId, Long)] = Encoder.instance({ asset => Json.obj( "tokenId" -> asset._1.asJson, "amount" -> asset._2.asJson ) - } + }) - implicit val assetDecoder: Decoder[(TokenId, Long)] = { cursor => + implicit val assetDecoder: Decoder[(TokenId, Long)] = Decoder.instance({ cursor => for { tokenId <- cursor.downField("tokenId").as[TokenId] amount <- cursor.downField("amount").as[Long] } yield (tokenId, amount) - } + }) - implicit val modifierIdEncoder: Encoder[ModifierId] = _.asInstanceOf[String].asJson - implicit val modifierIdDecoder: Decoder[ModifierId] = ModifierId @@ _.as[String] + implicit val modifierIdEncoder: Encoder[ModifierId] = Encoder.instance(_.asInstanceOf[String].asJson) + implicit val modifierIdDecoder: Decoder[ModifierId] = Decoder.instance(ModifierId @@ _.as[String]) - implicit val registerIdEncoder: KeyEncoder[NonMandatoryRegisterId] = { regId => + implicit val registerIdEncoder: KeyEncoder[NonMandatoryRegisterId] = KeyEncoder.instance({ regId => s"R${regId.number}" - } + }) - implicit val registerIdDecoder: KeyDecoder[NonMandatoryRegisterId] = { key => + implicit val registerIdDecoder: KeyDecoder[NonMandatoryRegisterId] = KeyDecoder.instance({ key => ErgoBox.registerByName.get(key).collect { case nonMandatoryId: NonMandatoryRegisterId => nonMandatoryId } - } + }) - implicit val headerEncoder: Encoder[Header] = { h: Header => + implicit val headerEncoder: Encoder[Header] = Encoder.instance({ h: Header => Map( "id" -> h.id.asJson, "version" -> h.version.asJson, @@ -120,9 +121,9 @@ trait JsonCodecs { "powDistance" -> h.powDistance.asJson, "votes" -> h.votes.asJson ).asJson - } + }) - implicit val headerDecoder: Decoder[Header] = { cursor => + implicit val headerDecoder: Decoder[Header] = Decoder.instance({ cursor => for { id <- cursor.downField("id").as[Coll[Byte]] version <- cursor.downField("version").as[Byte] @@ -141,9 +142,9 @@ trait JsonCodecs { votes <- cursor.downField("votes").as[Coll[Byte]] } yield new CHeader(id, version, parentId, adProofsRoot, stateRoot, transactionsRoot, timestamp, nBits, height, extensionRoot, SigmaDsl.decodePoint(minerPk), SigmaDsl.decodePoint(powOnetimePk), powNonce, powDistance, votes) - } + }) - implicit val preHeaderEncoder: Encoder[PreHeader] = { v: PreHeader => + implicit val preHeaderEncoder: Encoder[PreHeader] = Encoder.instance({ v: PreHeader => Map( "version" -> v.version.asJson, "parentId" -> v.parentId.asJson, @@ -153,9 +154,9 @@ trait JsonCodecs { "minerPk" -> v.minerPk.getEncoded.asJson, "votes" -> v.votes.asJson ).asJson - } + }) - implicit val preHeaderDecoder: Decoder[PreHeader] = { cursor => + implicit val preHeaderDecoder: Decoder[PreHeader] = Decoder.instance({ cursor => for { version <- cursor.downField("version").as[Byte] parentId <- cursor.downField("parentId").as[Coll[Byte]] @@ -165,130 +166,130 @@ trait JsonCodecs { minerPk <- cursor.downField("minerPk").as[Coll[Byte]] votes <- cursor.downField("votes").as[Coll[Byte]] } yield CPreHeader(version, parentId, timestamp, nBits, height, SigmaDsl.decodePoint(minerPk), votes) - } + }) - implicit val evaluatedValueEncoder: Encoder[EvaluatedValue[_ <: SType]] = { value => + implicit val evaluatedValueEncoder: Encoder[EvaluatedValue[_ <: SType]] = Encoder.instance({ value => ValueSerializer.serialize(value).asJson - } + }) implicit val evaluatedValueDecoder: Decoder[EvaluatedValue[_ <: SType]] = { decodeEvaluatedValue(_.asInstanceOf[EvaluatedValue[SType]]) } - def decodeEvaluatedValue[T](transform: EvaluatedValue[SType] => T): Decoder[T] = { implicit cursor: ACursor => + def decodeEvaluatedValue[T](transform: EvaluatedValue[SType] => T): Decoder[T] = Decoder.instance({ implicit cursor: ACursor => cursor.as[Array[Byte]] flatMap { bytes => fromThrows(transform(ValueSerializer.deserialize(bytes).asInstanceOf[EvaluatedValue[SType]])) } - } + }) - implicit val dataInputEncoder: Encoder[DataInput] = { input => + implicit val dataInputEncoder: Encoder[DataInput] = Encoder.instance({ input => Json.obj( - "boxId" -> input.boxId.asJson, + "boxId" -> input.boxId.asJson ) - } + }) - implicit val dataInputDecoder: Decoder[DataInput] = { cursor => + implicit val dataInputDecoder: Decoder[DataInput] = Decoder.instance({ cursor => for { boxId <- cursor.downField("boxId").as[ADKey] } yield DataInput(boxId) - } + }) - implicit val inputEncoder: Encoder[Input] = { input => + implicit val inputEncoder: Encoder[Input] = Encoder.instance({ input => Json.obj( "boxId" -> input.boxId.asJson, "spendingProof" -> input.spendingProof.asJson ) - } + }) - implicit val inputDecoder: Decoder[Input] = { cursor => + implicit val inputDecoder: Decoder[Input] = Decoder.instance({ cursor => for { boxId <- cursor.downField("boxId").as[ADKey] proof <- cursor.downField("spendingProof").as[ProverResult] } yield Input(boxId, proof) - } + }) - implicit val unsignedInputEncoder: Encoder[UnsignedInput] = { input => + implicit val unsignedInputEncoder: Encoder[UnsignedInput] = Encoder.instance({ input => Json.obj( "boxId" -> input.boxId.asJson, "extension" -> input.extension.asJson ) - } + }) - implicit val unsignedInputDecoder: Decoder[UnsignedInput] = { cursor => + implicit val unsignedInputDecoder: Decoder[UnsignedInput] = Decoder.instance({ cursor => for { boxId <- cursor.downField("boxId").as[ADKey] extension <- cursor.downField("extension").as[ContextExtension] } yield new UnsignedInput(boxId, extension) - } + }) - implicit val contextExtensionEncoder: Encoder[ContextExtension] = { extension => + implicit val contextExtensionEncoder: Encoder[ContextExtension] = Encoder.instance({ extension => extension.values.map { case (key, value) => key -> evaluatedValueEncoder(value) }.asJson - } + }) - implicit val contextExtensionDecoder: Decoder[ContextExtension] = { cursor => + implicit val contextExtensionDecoder: Decoder[ContextExtension] = Decoder.instance({ cursor => for { values <- cursor.as[Map[Byte, EvaluatedValue[SType]]] } yield ContextExtension(values) - } + }) - implicit val proverResultEncoder: Encoder[ProverResult] = { v => + implicit val proverResultEncoder: Encoder[ProverResult] = Encoder.instance({ v => Json.obj( "proofBytes" -> v.proof.asJson, "extension" -> v.extension.asJson ) - } + }) - implicit val proverResultDecoder: Decoder[ProverResult] = { cursor => + implicit val proverResultDecoder: Decoder[ProverResult] = Decoder.instance({ cursor => for { proofBytes <- cursor.downField("proofBytes").as[Array[Byte]] extMap <- cursor.downField("extension").as[Map[Byte, EvaluatedValue[SType]]] } yield ProverResult(proofBytes, ContextExtension(extMap)) - } + }) - implicit val avlTreeDataEncoder: Encoder[AvlTreeData] = { v => + implicit val avlTreeDataEncoder: Encoder[AvlTreeData] = Encoder.instance({ v => Json.obj( "digest" -> v.digest.asJson, "treeFlags" -> v.treeFlags.serializeToByte.asJson, "keyLength" -> v.keyLength.asJson, "valueLength" -> v.valueLengthOpt.asJson ) - } + }) - implicit val avlTreeDataDecoder: Decoder[AvlTreeData] = { cursor => + implicit val avlTreeDataDecoder: Decoder[AvlTreeData] = Decoder.instance({ cursor => for { digest <- cursor.downField("digest").as[ADDigest] treeFlagsByte <- cursor.downField("treeFlags").as[Byte] keyLength <- cursor.downField("keyLength").as[Int] valueLength <- cursor.downField("valueLength").as[Option[Int]] } yield new AvlTreeData(digest, AvlTreeFlags(treeFlagsByte), keyLength, valueLength) - } + }) - implicit val ergoTreeEncoder: Encoder[ErgoTree] = { value => + implicit val ergoTreeEncoder: Encoder[ErgoTree] = Encoder.instance({ value => ErgoTreeSerializer.DefaultSerializer.serializeErgoTree(value).asJson - } + }) - def decodeErgoTree[T](transform: ErgoTree => T): Decoder[T] = { implicit cursor: ACursor => + def decodeErgoTree[T](transform: ErgoTree => T): Decoder[T] = Decoder.instance({ implicit cursor: ACursor => cursor.as[Array[Byte]] flatMap { bytes => fromThrows(transform(ErgoTreeSerializer.DefaultSerializer.deserializeErgoTree(bytes))) } - } + }) implicit val ergoTreeDecoder: Decoder[ErgoTree] = { decodeErgoTree(_.asInstanceOf[ErgoTree]) } - implicit def registersEncoder[T <: EvaluatedValue[_ <: SType]]: Encoder[Map[NonMandatoryRegisterId, T]] = { m => + implicit def registersEncoder[T <: EvaluatedValue[_ <: SType]]: Encoder[Map[NonMandatoryRegisterId, T]] = Encoder.instance({ m => Json.obj( m.toSeq .sortBy(_._1.number) .map { case (k, v) => registerIdEncoder(k) -> evaluatedValueEncoder(v) }: _*) - } + }) - implicit val ergoBoxEncoder: Encoder[ErgoBox] = { box => + implicit val ergoBoxEncoder: Encoder[ErgoBox] = Encoder.instance({ box => Json.obj( "boxId" -> box.id.asJson, "value" -> box.value.asJson, @@ -299,9 +300,9 @@ trait JsonCodecs { "transactionId" -> box.transactionId.asJson, "index" -> box.index.asJson ) - } + }) - implicit val ergoBoxDecoder: Decoder[ErgoBox] = { cursor => + implicit val ergoBoxDecoder: Decoder[ErgoBox] = Decoder.instance({ cursor => for { value <- cursor.downField("value").as[Long] ergoTreeBytes <- cursor.downField("ergoTree").as[Array[Byte]] @@ -319,33 +320,33 @@ trait JsonCodecs { index = index, creationHeight = creationHeight ) - } + }) - implicit val ergoLikeTransactionEncoder: Encoder[ErgoLikeTransaction] = { tx => + implicit val ergoLikeTransactionEncoder: Encoder[ErgoLikeTransaction] = Encoder.instance({ tx => Json.obj( "id" -> tx.id.asJson, "inputs" -> tx.inputs.asJson, "dataInputs" -> tx.dataInputs.asJson, "outputs" -> tx.outputs.asJson ) - } + }) - implicit val unsignedErgoLikeTransactionEncoder: Encoder[UnsignedErgoLikeTransaction] = { tx => + implicit val unsignedErgoLikeTransactionEncoder: Encoder[UnsignedErgoLikeTransaction] = Encoder.instance({ tx => Json.obj( "id" -> tx.id.asJson, "inputs" -> tx.inputs.asJson, "dataInputs" -> tx.dataInputs.asJson, "outputs" -> tx.outputs.asJson ) - } + }) - implicit def ergoLikeTransactionTemplateEncoder[T <: UnsignedInput]: Encoder[ErgoLikeTransactionTemplate[T]] = { + implicit def ergoLikeTransactionTemplateEncoder[T <: UnsignedInput]: Encoder[ErgoLikeTransactionTemplate[T]] = Encoder.instance({ case transaction: ErgoLikeTransaction => ergoLikeTransactionEncoder(transaction) case transaction: UnsignedErgoLikeTransaction => unsignedErgoLikeTransactionEncoder(transaction) case t => throw new SigmaException(s"Don't know how to encode transaction $t") - } + }) - implicit val transactionOutputsDecoder: Decoder[(ErgoBoxCandidate, Option[BoxId])] = { cursor => + implicit val transactionOutputsDecoder: Decoder[(ErgoBoxCandidate, Option[BoxId])] = Decoder.instance({ cursor => for { maybeId <- cursor.downField("boxId").as[Option[BoxId]] value <- cursor.downField("value").as[Long] @@ -354,40 +355,40 @@ trait JsonCodecs { assets <- cursor.downField("assets").as[Seq[(ErgoBox.TokenId, Long)]] // TODO optimize: encode directly into Coll avoiding allocation of Tuple2 for each element registers <- cursor.downField("additionalRegisters").as[Map[NonMandatoryRegisterId, EvaluatedValue[SType]]] } yield (new ErgoBoxCandidate(value, ergoTree, creationHeight, assets.toColl, registers), maybeId) - } + }) - implicit val ergoLikeTransactionDecoder: Decoder[ErgoLikeTransaction] = { implicit cursor => + implicit val ergoLikeTransactionDecoder: Decoder[ErgoLikeTransaction] = Decoder.instance({ implicit cursor => for { inputs <- cursor.downField("inputs").as[IndexedSeq[Input]] dataInputs <- cursor.downField("dataInputs").as[IndexedSeq[DataInput]] outputsWithIndex <- cursor.downField("outputs").as[IndexedSeq[(ErgoBoxCandidate, Option[BoxId])]] } yield new ErgoLikeTransaction(inputs, dataInputs, outputsWithIndex.map(_._1)) - } + }) - implicit val unsignedErgoLikeTransactionDecoder: Decoder[UnsignedErgoLikeTransaction] = { implicit cursor => + implicit val unsignedErgoLikeTransactionDecoder: Decoder[UnsignedErgoLikeTransaction] = Decoder.instance({ implicit cursor => for { inputs <- cursor.downField("inputs").as[IndexedSeq[UnsignedInput]] dataInputs <- cursor.downField("dataInputs").as[IndexedSeq[DataInput]] outputsWithIndex <- cursor.downField("outputs").as[IndexedSeq[(ErgoBoxCandidate, Option[BoxId])]] } yield new UnsignedErgoLikeTransaction(inputs, dataInputs, outputsWithIndex.map(_._1)) - } + }) implicit val ergoLikeTransactionTemplateDecoder: Decoder[ErgoLikeTransactionTemplate[_ <: UnsignedInput]] = { ergoLikeTransactionDecoder.asInstanceOf[Decoder[ErgoLikeTransactionTemplate[_ <: UnsignedInput]]] or unsignedErgoLikeTransactionDecoder.asInstanceOf[Decoder[ErgoLikeTransactionTemplate[_ <: UnsignedInput]]] } - implicit val sigmaValidationSettingsEncoder: Encoder[SigmaValidationSettings] = { v => + implicit val sigmaValidationSettingsEncoder: Encoder[SigmaValidationSettings] = Encoder.instance({ v => SigmaValidationSettingsSerializer.toBytes(v).asJson - } + }) - implicit val sigmaValidationSettingsDecoder: Decoder[SigmaValidationSettings] = { implicit cursor: ACursor => + implicit val sigmaValidationSettingsDecoder: Decoder[SigmaValidationSettings] = Decoder.instance({ implicit cursor: ACursor => cursor.as[Array[Byte]] flatMap { bytes => fromThrows(SigmaValidationSettingsSerializer.fromBytes(bytes)) } - } + }) - implicit val ergoLikeContextEncoder: Encoder[ErgoLikeContext] = { ctx => + implicit val ergoLikeContextEncoder: Encoder[ErgoLikeContext] = Encoder.instance({ ctx => Json.obj( "lastBlockUtxoRoot" -> ctx.lastBlockUtxoRoot.asJson, "headers" -> ctx.headers.toArray.toSeq.asJson, @@ -401,9 +402,9 @@ trait JsonCodecs { "costLimit" -> ctx.costLimit.asJson, "initCost" -> ctx.initCost.asJson ) - } + }) - implicit val ergoLikeContextDecoder: Decoder[ErgoLikeContext] = { cursor => + implicit val ergoLikeContextDecoder: Decoder[ErgoLikeContext] = Decoder.instance({ cursor => for { lastBlockUtxoRoot <- cursor.downField("lastBlockUtxoRoot").as[AvlTreeData] headers <- cursor.downField("headers").as[Seq[Header]] @@ -418,5 +419,5 @@ trait JsonCodecs { initCost <- cursor.downField("initCost").as[Long] } yield new ErgoLikeContext(lastBlockUtxoRoot, Colls.fromArray(headers.toArray), preHeader, dataBoxes, boxesToSpend, spendingTransaction, selfIndex, extension, validationSettings, costLimit, initCost) - } + }) } diff --git a/sigmastate/src/main/scala/org/ergoplatform/validation/ValidationRules.scala b/sigmastate/src/main/scala/org/ergoplatform/validation/ValidationRules.scala index 5cc5ad4350..8d07c2e0ec 100644 --- a/sigmastate/src/main/scala/org/ergoplatform/validation/ValidationRules.scala +++ b/sigmastate/src/main/scala/org/ergoplatform/validation/ValidationRules.scala @@ -15,7 +15,7 @@ import sigmastate.serialization.OpCodes.{OpCode, OpCodeExtra} import sigmastate.serialization.TypeSerializer.embeddableIdToType import sigmastate.serialization.{OpCodes, ValueSerializer} import sigmastate.utxo.DeserializeContext - +import sigmastate.utils.Helpers._ import scala.collection.mutable /** Base class for different validation rules registered in ValidationRules.currentSettings. diff --git a/sigmastate/src/main/scala/sigmastate/eval/CostingDataContext.scala b/sigmastate/src/main/scala/sigmastate/eval/CostingDataContext.scala index 6e8601bb35..50988e76dd 100644 --- a/sigmastate/src/main/scala/sigmastate/eval/CostingDataContext.scala +++ b/sigmastate/src/main/scala/sigmastate/eval/CostingDataContext.scala @@ -408,7 +408,7 @@ case class CPreHeader( nBits: Long, height: Int, minerPk: GroupElement, - votes: Coll[Byte], + votes: Coll[Byte] ) extends PreHeader {} case class CHeader( @@ -426,7 +426,7 @@ case class CHeader( powOnetimePk: GroupElement, powNonce: Coll[Byte], powDistance: BigInt, - votes: Coll[Byte], + votes: Coll[Byte] ) extends Header { } diff --git a/sigmastate/src/main/scala/sigmastate/eval/Evaluation.scala b/sigmastate/src/main/scala/sigmastate/eval/Evaluation.scala index 1e3706952b..bac1ef19fe 100644 --- a/sigmastate/src/main/scala/sigmastate/eval/Evaluation.scala +++ b/sigmastate/src/main/scala/sigmastate/eval/Evaluation.scala @@ -119,7 +119,7 @@ trait Evaluation extends RuntimeCosting { IR: IRContext => SizeOfCode, SliceCode, TupleCode, - UpcastCode, + UpcastCode ).map(toExtra) ++ HashSet[OpCodeExtra]( OpCostCode, PerKbCostOfCode, @@ -164,7 +164,7 @@ trait Evaluation extends RuntimeCosting { IR: IRContext => CBMFromItemsCode, CostOfCode, UOSizeOfCode, - SPCMSomeCode, + SPCMSomeCode ) /** Returns a set of opCodeEx values (extended op codes) which are allowed in cost function. diff --git a/sigmastate/src/main/scala/sigmastate/eval/Sized.scala b/sigmastate/src/main/scala/sigmastate/eval/Sized.scala index 5c006383d6..3f8c7d4756 100644 --- a/sigmastate/src/main/scala/sigmastate/eval/Sized.scala +++ b/sigmastate/src/main/scala/sigmastate/eval/Sized.scala @@ -20,7 +20,7 @@ trait SizedLowPriority { * Takes advantage of RType.isConstantSize to use ReplColl representation of Coll when all items are the same. * When all elements of T are of the same size, then only single Size[T] value is created and replicated * to the length of source collection `xs`. */ - implicit def collIsSized[T: Sized]: Sized[Coll[T]] = (xs: Coll[T]) => { + implicit def collIsSized[T: Sized]: Sized[Coll[T]] = Sized.instance((xs: Coll[T]) => { implicit val tT = xs.tItem val sizes = if (xs.isEmpty) Colls.emptyColl[Size[T]] @@ -29,14 +29,19 @@ trait SizedLowPriority { else new CViewColl(xs, Sized[T].size) new CSizeColl(sizes) - } - implicit def optionIsSized[T: Sized]: Sized[Option[T]] = (xs: Option[T]) => new CSizeOption(xs.map(Sized[T].size)) - implicit def pairIsSized[A: Sized, B: Sized]: Sized[(A,B)] = (in: (A,B)) => new CSizePair(Sized[A].size(in._1), Sized[B].size(in._2)) + }) + implicit def optionIsSized[T: Sized]: Sized[Option[T]] = + Sized.instance((xs: Option[T]) => new CSizeOption(xs.map(Sized[T].size))) + implicit def pairIsSized[A: Sized, B: Sized]: Sized[(A,B)] = + Sized.instance((in: (A,B)) => new CSizePair(Sized[A].size(in._1), Sized[B].size(in._2))) } object Sized extends SizedLowPriority { def apply[T](implicit sz: Sized[T]): Sized[T] = sz def sizeOf[T: Sized](x: T): Size[T] = Sized[T].size(x) + def instance[T](f: T => Size[T]) = new Sized[T] { + override def size(x: T): Size[T] = f(x) + } val SizeBoolean: Size[Boolean] = new CSizePrim(1L, BooleanType) val SizeByte: Size[Byte] = new CSizePrim(1L, ByteType) @@ -48,15 +53,15 @@ object Sized extends SizedLowPriority { val SizeSigmaProp: Size[SigmaProp] = new CSizePrim(SSigmaProp.MaxSizeInBytes, SigmaPropRType) val SizeAvlTree: Size[AvlTree] = new CSizePrim(AvlTreeData.TreeDataSize, AvlTreeRType) - implicit val BooleanIsSized: Sized[Boolean] = (_: Boolean) => SizeBoolean - implicit val ByteIsSized: Sized[Byte] = (_: Byte) => SizeByte - implicit val ShortIsSized: Sized[Short] = (_: Short) => SizeShort - implicit val IntIsSized: Sized[Int] = (_: Int) => SizeInt - implicit val LongIsSized: Sized[Long] = (_: Long) => SizeLong - implicit val BigIntIsSized: Sized[BigInt] = (_: BigInt) => SizeBigInt - implicit val GroupElementIsSized: Sized[GroupElement] = (_: GroupElement) => SizeGroupElement - implicit val SigmaPropIsSized: Sized[SigmaProp] = (_: SigmaProp) => SizeSigmaProp - implicit val AvlTreeIsSized: Sized[AvlTree] = (_: AvlTree) => SizeAvlTree + implicit val BooleanIsSized: Sized[Boolean] = Sized.instance((_: Boolean) => SizeBoolean) + implicit val ByteIsSized: Sized[Byte] = Sized.instance((_: Byte) => SizeByte) + implicit val ShortIsSized: Sized[Short] = Sized.instance((_: Short) => SizeShort) + implicit val IntIsSized: Sized[Int] = Sized.instance((_: Int) => SizeInt) + implicit val LongIsSized: Sized[Long] = Sized.instance((_: Long) => SizeLong) + implicit val BigIntIsSized: Sized[BigInt] = Sized.instance((_: BigInt) => SizeBigInt) + implicit val GroupElementIsSized: Sized[GroupElement] = Sized.instance((_: GroupElement) => SizeGroupElement) + implicit val SigmaPropIsSized: Sized[SigmaProp] = Sized.instance((_: SigmaProp) => SizeSigmaProp) + implicit val AvlTreeIsSized: Sized[AvlTree] = Sized.instance((_: AvlTree) => SizeAvlTree) def typeToSized[T](t: RType[T]): Sized[T] = (t match { case BooleanType => BooleanIsSized @@ -84,7 +89,7 @@ object Sized extends SizedLowPriority { new CSizeAnyValue(NothingType.asInstanceOf[RType[Any]], size) } - implicit val anyValueIsSized: Sized[AnyValue] = (x: AnyValue) => { + implicit val anyValueIsSized: Sized[AnyValue] = Sized.instance((x: AnyValue) => { if (x.tVal == null) { SizeNullValue } else { @@ -93,11 +98,11 @@ object Sized extends SizedLowPriority { val size = sized.size(x.value) new CSizeAnyValue(x.tVal, size) } - } + }) - implicit val CollByteIsSized: Sized[Coll[Byte]] = (xs: Coll[Byte]) => { + implicit val CollByteIsSized: Sized[Coll[Byte]] = Sized.instance((xs: Coll[Byte]) => { new CSizeColl(Colls.replicate(xs.length, SizeByte)) - } + }) private val SizeOptionAnyValueNone = new CSizeOption[AnyValue](None) @@ -128,7 +133,7 @@ object Sized extends SizedLowPriority { new CSizeColl(Colls.replicate(b.tokens.length, SizeToken)) } - implicit val boxIsSized: Sized[Box] = (b: Box) => { + implicit val boxIsSized: Sized[Box] = Sized.instance((b: Box) => { new EvalSizeBox( SizePropositionBytesMax, SizeBoxBytesMax, @@ -136,15 +141,15 @@ object Sized extends SizedLowPriority { sizeOfRegisters(b), SizeTokensMax ) - } + }) val SizeHeader = new CSizePrim(SHeader.dataSize(0.asWrappedType), HeaderRType) - implicit val headerIsSized: Sized[Header] = (_: Header) => SizeHeader + implicit val headerIsSized: Sized[Header] = Sized.instance((_: Header) => SizeHeader) val SizePreHeader = new CSizePrim(SPreHeader.dataSize(0.asWrappedType), PreHeaderRType) - implicit val preHeaderIsSized: Sized[PreHeader] = (_: PreHeader) => SizePreHeader + implicit val preHeaderIsSized: Sized[PreHeader] = Sized.instance((_: PreHeader) => SizePreHeader) - implicit val contextIsSized: Sized[Context] = (ctx: Context) => { + implicit val contextIsSized: Sized[Context] = Sized.instance((ctx: Context) => { val outputs = sizeOf(ctx.OUTPUTS) val inputs = sizeOf(ctx.INPUTS) val dataInputs = sizeOf(ctx.dataInputs) @@ -157,7 +162,7 @@ object Sized extends SizedLowPriority { sizeOf(anyV) } new CSizeContext(outputs, inputs, dataInputs, selfBox, rootHash, headers, preHeader, vars) - } + }) } diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/Interpreter.scala b/sigmastate/src/main/scala/sigmastate/interpreter/Interpreter.scala index 429a48b8ca..293ea4af22 100644 --- a/sigmastate/src/main/scala/sigmastate/interpreter/Interpreter.scala +++ b/sigmastate/src/main/scala/sigmastate/interpreter/Interpreter.scala @@ -19,6 +19,7 @@ import sigmastate.utxo.DeserializeContext import sigmastate.{SType, _} import org.ergoplatform.validation.ValidationRules._ import scalan.util.BenchmarkUtil +import sigmastate.utils.Helpers._ import scala.util.Try diff --git a/sigmastate/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala b/sigmastate/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala index 99b2f94903..dd2001a612 100644 --- a/sigmastate/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala +++ b/sigmastate/src/main/scala/sigmastate/interpreter/ProverInterpreter.scala @@ -16,7 +16,7 @@ import sigmastate.basics.{DiffieHellmanTupleInteractiveProver, DiffieHellmanTupl import sigmastate.lang.exceptions.CostLimitException import sigmastate.serialization.SigmaSerializer import sigmastate.utils.{Helpers, SigmaByteReader, SigmaByteWriter} - +import Helpers._ import scala.util.Try /** diff --git a/sigmastate/src/main/scala/sigmastate/lang/SigmaPredef.scala b/sigmastate/src/main/scala/sigmastate/lang/SigmaPredef.scala index e192509b3c..22719d741d 100644 --- a/sigmastate/src/main/scala/sigmastate/lang/SigmaPredef.scala +++ b/sigmastate/src/main/scala/sigmastate/lang/SigmaPredef.scala @@ -112,7 +112,7 @@ object SigmaPredef { "right" -> SCollection(STuple(tK, tR)), "l" -> SFunc(IndexedSeq(tK, tL), tO), "r" -> SFunc(IndexedSeq(tK, tR), tO), - "inner" -> SFunc(IndexedSeq(tK, tL, tR), tO), + "inner" -> SFunc(IndexedSeq(tK, tL, tR), tO) ), SCollection(STuple(tK, tO)), None), PredefFuncInfo(undefined), @@ -398,7 +398,7 @@ object SigmaPredef { AvlTreeFunc, SubstConstantsFunc, ExecuteFromVarFunc, - ExecuteFromSelfRegFunc, + ExecuteFromSelfRegFunc ).map(f => f.name -> f).toMap def comparisonOp(symbolName: String, opDesc: ValueCompanion, desc: String, args: Seq[ArgInfo]) = { @@ -483,7 +483,7 @@ object SigmaPredef { logicalOp("&&", BinAnd, "Logical AND of two operands", Seq(ArgInfo("left", "left operand"), ArgInfo("right", "right operand"))), logicalOp("^", BinXor, "Logical XOR of two operands", - Seq(ArgInfo("left", "left operand"), ArgInfo("right", "right operand"))), + Seq(ArgInfo("left", "left operand"), ArgInfo("right", "right operand"))) ).map(f => f.name -> f).toMap val unaryFuncs: Map[String, PredefinedFunc] = Seq( @@ -507,7 +507,7 @@ object SigmaPredef { OperationInfo(BitInversion, "Invert every bit of the numeric value.", Seq(ArgInfo("input", "value of numeric type"))) - ), + ) ).map(f => f.name -> f).toMap val funcs: Map[String, PredefinedFunc] = globalFuncs ++ infixFuncs ++ unaryFuncs @@ -569,7 +569,7 @@ object SigmaPredef { OperationInfo(ConstantPlaceholder, "Create special ErgoTree node which can be replaced by constant with given id.", Seq(ArgInfo("index", "index of the constant in ErgoTree header"))) - ), + ) ).map(f => f.name -> f).toMap private val funcNameToIrBuilderMap: Map[String, PredefinedFunc] = diff --git a/sigmastate/src/main/scala/sigmastate/serialization/DataJsonEncoder.scala b/sigmastate/src/main/scala/sigmastate/serialization/DataJsonEncoder.scala index f72e2976cb..7736779612 100644 --- a/sigmastate/src/main/scala/sigmastate/serialization/DataJsonEncoder.scala +++ b/sigmastate/src/main/scala/sigmastate/serialization/DataJsonEncoder.scala @@ -28,20 +28,20 @@ object DataJsonEncoder { val encodedData = encodeData(v, tpe) Json.obj( "type" -> Json.fromString(encodedType), - "value" -> encodedData, + "value" -> encodedData ) } - private def encodeBytes: Encoder[Array[Byte]] = (bytes: Array[Byte]) => { + private def encodeBytes: Encoder[Array[Byte]] = Encoder.instance((bytes: Array[Byte]) => { ErgoAlgos.encode(bytes).asJson - } + }) def encodeAnyValue(v: AnyValue): Json = { val encodedType = Evaluation.rtypeToSType(v.tVal) val encodedData = encodeData[SType](v.value.asInstanceOf[SType#WrappedType], encodedType) Json.obj( "type" -> Json.fromString(encodedType.toTermString), - "value" -> encodedData, + "value" -> encodedData ) } diff --git a/sigmastate/src/main/scala/sigmastate/serialization/ValueSerializer.scala b/sigmastate/src/main/scala/sigmastate/serialization/ValueSerializer.scala index 26df3df947..a4766bb882 100644 --- a/sigmastate/src/main/scala/sigmastate/serialization/ValueSerializer.scala +++ b/sigmastate/src/main/scala/sigmastate/serialization/ValueSerializer.scala @@ -149,7 +149,7 @@ object ValueSerializer extends SigmaSerializerCompanion[Value[SType]] { CreateProveDHTupleSerializer(mkCreateProveDHTuple), LogicalNotSerializer(mkLogicalNot), OneArgumentOperationSerializer(Negation, mkNegation[SNumericType]), - OneArgumentOperationSerializer(BitInversion, mkBitInversion[SNumericType]), + OneArgumentOperationSerializer(BitInversion, mkBitInversion[SNumericType]) )) private def serializable(v: Value[SType]): Value[SType] = v match { diff --git a/sigmastate/src/main/scala/sigmastate/types.scala b/sigmastate/src/main/scala/sigmastate/types.scala index 0a65eba7bd..7f8450a828 100644 --- a/sigmastate/src/main/scala/sigmastate/types.scala +++ b/sigmastate/src/main/scala/sigmastate/types.scala @@ -915,10 +915,10 @@ object SOption extends STypeCompanion { FoldMethod, */ MapMethod, - FilterMethod, + FilterMethod ) def apply[T <: SType](implicit elemType: T, ov: Overload1): SOption[T] = SOption(elemType) - def unapply[T <: SType](tOpt: SOption[T]): Option[T] = Some(tOpt.elemType) +// def unapply[T <: SType](tOpt: SOption[T]): Option[T] = Some(tOpt.elemType) } trait SCollection[T <: SType] extends SProduct with SGenericType { @@ -1168,7 +1168,7 @@ object SCollection extends STypeCompanion with MethodByNameUnapply { LastIndexOfMethod, FindMethod, */ - ZipMethod, + ZipMethod /* TODO soft-fork: https://github.com/ScorexFoundation/sigmastate-interpreter/issues/479 DistinctMethod, StartsWithMethod, @@ -1248,7 +1248,7 @@ case class STuple(items: IndexedSeq[SType]) extends SCollection[SAny.type] { Constant[STuple](v, this).asValue[this.type] val typeParams = Nil - val tparamSubst = Map.empty + val tparamSubst: Map[STypeVar, SType] = Map.empty override def toTermString = s"(${items.map(_.toTermString).mkString(",")})" override def toString = s"(${items.mkString(",")})" diff --git a/sigmastate/src/main/scala/sigmastate/utils/Helpers.scala b/sigmastate/src/main/scala/sigmastate/utils/Helpers.scala index d47596c987..b9e67c8208 100644 --- a/sigmastate/src/main/scala/sigmastate/utils/Helpers.scala +++ b/sigmastate/src/main/scala/sigmastate/utils/Helpers.scala @@ -2,7 +2,10 @@ package sigmastate.utils import java.util +import io.circe.Decoder + import scala.reflect.ClassTag +import scala.util.{Failure, Try, Either, Success, Right} object Helpers { def xor(ba1: Array[Byte], ba2: Array[Byte]): Array[Byte] = ba1.zip(ba2).map(t => (t._1 ^ t._2).toByte) @@ -91,6 +94,38 @@ object Helpers { case _ => false } + implicit class TryOps[+A](val source: Try[A]) extends AnyVal { + def fold[B](onError: Throwable => B, onSuccess: A => B) = source match { + case Success(value) => onSuccess(value) + case Failure(t) => onError(t) + } + def toEither: Either[Throwable, A] = source match { + case Success(value) => Right(value) + case Failure(t) => Left(t) + } + } + + implicit class DecoderResultOps[A](val source: Decoder.Result[A]) extends AnyVal { + def toTry: Try[A] = source match { + case Right(value) => Success(value) + case Left(t) => Failure(t) + } + } + + implicit class EitherOps[+A, +B](val source: Either[A, B]) extends AnyVal { + /** The given function is applied if this is a `Right`. + * + * {{{ + * Right(12).map(x => "flower") // Result: Right("flower") + * Left(12).map(x => "flower") // Result: Left(12) + * }}} + */ + def mapRight[B1](f: B => B1): Either[A, B1] = source match { + case Right(b) => Right(f(b)) + case _ => this.asInstanceOf[Either[A, B1]] + } + } + } object Overloading { diff --git a/sigmastate/src/main/scala/sigmastate/utils/SigmaByteWriter.scala b/sigmastate/src/main/scala/sigmastate/utils/SigmaByteWriter.scala index 6884575b5a..43d05e8407 100644 --- a/sigmastate/src/main/scala/sigmastate/utils/SigmaByteWriter.scala +++ b/sigmastate/src/main/scala/sigmastate/utils/SigmaByteWriter.scala @@ -1,6 +1,6 @@ package sigmastate.utils -import scorex.util.serialization.{VLQByteStringWriter, VLQByteBufferWriter, Writer} +import scorex.util.serialization.{VLQByteBufferWriter, Writer} import scorex.util.serialization.Writer.Aux import sigmastate.{ArgInfo, SType} import sigmastate.Values.{Value, SValue} @@ -100,7 +100,6 @@ class SigmaByteWriter(val w: Writer, // TODO refactor: move to Writer @inline def toBytes: Array[Byte] = w match { - case wr: VLQByteStringWriter => wr.result().asByteBuffer.array() case wr: VLQByteBufferWriter => wr.toBytes } diff --git a/sigmastate/src/main/scala/sigmastate/utxo/ComplexityTable.scala b/sigmastate/src/main/scala/sigmastate/utxo/ComplexityTable.scala index d5dd4b2b13..2613426257 100644 --- a/sigmastate/src/main/scala/sigmastate/utxo/ComplexityTable.scala +++ b/sigmastate/src/main/scala/sigmastate/utxo/ComplexityTable.scala @@ -95,7 +95,7 @@ object ComplexityTable { LogicalNot.opCode -> 56, // count = 1420 Global.opCode -> 7, // count = 3 ValUse.opCode -> 3, // count = 18771 - Context.opCode -> 1, // count = 72 + Context.opCode -> 1 // count = 72 ).toMap val MethodCallComplexity: Map[(Byte, Byte), Int] = Seq( @@ -156,6 +156,6 @@ object ComplexityTable { (12.toByte, 14.toByte) -> 238, // count = 1725, SCollection.indices (101.toByte, 9.toByte) -> 182, // count = 2, Context.LastBlockUtxoRootHash (106.toByte, 1.toByte) -> 169, // count = 3, SigmaDslBuilder.groupGenerator - (101.toByte, 6.toByte) -> 146, // count = 1, Context.HEIGHT + (101.toByte, 6.toByte) -> 146 // count = 1, Context.HEIGHT ).toMap } diff --git a/sigmastate/src/main/scala/sigmastate/utxo/CostTable.scala b/sigmastate/src/main/scala/sigmastate/utxo/CostTable.scala index 2d3cd7308f..cdb9029073 100644 --- a/sigmastate/src/main/scala/sigmastate/utxo/CostTable.scala +++ b/sigmastate/src/main/scala/sigmastate/utxo/CostTable.scala @@ -294,7 +294,7 @@ object CostTable { ("DecodePoint", "(Coll[Byte]) => GroupElement", decodePointCost), ("SOption$.map", "(Option[T],(T) => R) => Option[R]", OptionOp), - ("SOption$.filter", "(Option[T],(T) => Boolean) => Option[T]", OptionOp), + ("SOption$.filter", "(Option[T],(T) => Boolean) => Option[T]", OptionOp) )) def fromSeq(items: Seq[(String, String, Int)]): CostTable = { diff --git a/sigmastate/src/test/java/gf2t/ReadableTest.java b/sigmastate/src/test/java/gf2t/ReadableTest.java index c5beaeec35..b3bc5383f6 100644 --- a/sigmastate/src/test/java/gf2t/ReadableTest.java +++ b/sigmastate/src/test/java/gf2t/ReadableTest.java @@ -6,18 +6,19 @@ import org.junit.runners.model.InitializationError; import java.util.LinkedList; -import java.util.stream.Collectors; public class ReadableTest extends BlockJUnit4ClassRunner { @Override protected String testName(FrameworkMethod method) { Joiner j = Joiner.on(" "); - return j.join( - splitCamelCaseString(method.getMethod().getName()) - .stream() - .map((s) -> s.substring(0, 1).toUpperCase() + s.substring(1)).collect(Collectors.toList()) - ); + String[] parts = splitCamelCaseString(method.getMethod().getName()).toArray(new String[0]); + String[] mapped = new String[parts.length]; + for (int i = 0; i < parts.length; i++) { + String s = parts[i]; + mapped[i] = s.substring(0, 1).toUpperCase() + s.substring(1); + } + return j.join(mapped); } public ReadableTest(Class klass) throws InitializationError { diff --git a/sigmastate/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala b/sigmastate/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala index 871eb8c97e..64c6fe4b3e 100644 --- a/sigmastate/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala +++ b/sigmastate/src/test/scala/org/ergoplatform/ErgoAddressSpecification.scala @@ -19,6 +19,7 @@ import sigmastate.helpers._ import sigmastate.interpreter.{ContextExtension, Interpreter} import sigmastate.interpreter.Interpreter.{ScriptNameProp, ScriptEnv} import sigmastate.lang.Terms.ValueOps +import sigmastate.utils.Helpers._ class ErgoAddressSpecification extends PropSpec with ObjectGenerators diff --git a/sigmastate/src/test/scala/org/ergoplatform/ErgoScriptPredefSpec.scala b/sigmastate/src/test/scala/org/ergoplatform/ErgoScriptPredefSpec.scala index 9ca011b09a..c3cb355024 100644 --- a/sigmastate/src/test/scala/org/ergoplatform/ErgoScriptPredefSpec.scala +++ b/sigmastate/src/test/scala/org/ergoplatform/ErgoScriptPredefSpec.scala @@ -18,6 +18,7 @@ import sigmastate.serialization.ValueSerializer import sigmastate.utxo.{ByIndex, CostTable, ExtractCreationInfo, SelectField} import scalan.util.BenchmarkUtil._ import ErgoScriptPredef._ +import sigmastate.utils.Helpers._ import scala.util.Try diff --git a/sigmastate/src/test/scala/org/ergoplatform/JsonSerializationSpec.scala b/sigmastate/src/test/scala/org/ergoplatform/JsonSerializationSpec.scala index 96bb9cd01d..3648e6aa36 100644 --- a/sigmastate/src/test/scala/org/ergoplatform/JsonSerializationSpec.scala +++ b/sigmastate/src/test/scala/org/ergoplatform/JsonSerializationSpec.scala @@ -14,6 +14,7 @@ import sigmastate.basics.DLogProtocol.ProveDlog import sigmastate.helpers.SigmaTestingCommons import sigmastate.interpreter.{ProverResult, ContextExtension, CryptoConstants} import sigmastate.serialization.SerializationSpecification +import sigmastate.utils.Helpers._ import special.collection.Coll import special.sigma.{PreHeader, Header} @@ -130,7 +131,7 @@ class JsonSerializationSpec extends SigmaTestingCommons with SerializationSpecif R4 -> ByteConstant(1), R6 -> IntConstant(10), R5 -> SigmaPropConstant(minerPk), - R8 -> ByteArrayConstant(Base16.decode("123456123456123456123456123456123456123456123456123456123456123456").get), + R8 -> ByteArrayConstant(Base16.decode("123456123456123456123456123456123456123456123456123456123456123456").get) ) // registers should be ordered by their number in Json regs.asJson.spaces2 shouldEqual diff --git a/sigmastate/src/test/scala/sigmastate/CalcSha256Specification.scala b/sigmastate/src/test/scala/sigmastate/CalcSha256Specification.scala index ee120a71fd..5c86926b8c 100644 --- a/sigmastate/src/test/scala/sigmastate/CalcSha256Specification.scala +++ b/sigmastate/src/test/scala/sigmastate/CalcSha256Specification.scala @@ -24,8 +24,7 @@ class CalcSha256Specification extends SigmaTestingCommons { ("", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"), ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"), ("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1"), - (Array.fill[String](1000000)("a").mkString, "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"), - + (Array.fill[String](1000000)("a").mkString, "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0") ) property("CalcSha256: Should pass standard tests.") { diff --git a/sigmastate/src/test/scala/sigmastate/SoftForkabilitySpecification.scala b/sigmastate/src/test/scala/sigmastate/SoftForkabilitySpecification.scala index df252c6b67..fa087fccef 100644 --- a/sigmastate/src/test/scala/sigmastate/SoftForkabilitySpecification.scala +++ b/sigmastate/src/test/scala/sigmastate/SoftForkabilitySpecification.scala @@ -16,6 +16,7 @@ import sigmastate.serialization.OpCodes.{OpCodeExtra, LastConstantCode, OpCode} import sigmastate.serialization._ import sigmastate.utxo.{DeserializeContext, SelectField} import special.sigma.SigmaTestingData +import sigmastate.utils.Helpers._ class SoftForkabilitySpecification extends SigmaTestingData { diff --git a/sigmastate/src/test/scala/sigmastate/TestingInterpreterSpecification.scala b/sigmastate/src/test/scala/sigmastate/TestingInterpreterSpecification.scala index 28306ba7b9..2fc0497495 100644 --- a/sigmastate/src/test/scala/sigmastate/TestingInterpreterSpecification.scala +++ b/sigmastate/src/test/scala/sigmastate/TestingInterpreterSpecification.scala @@ -12,6 +12,7 @@ import scorex.util.encode.Base58 import sigmastate.helpers.{ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTestProvingInterpreter, SigmaTestingCommons} import sigmastate.serialization.ValueSerializer import TrivialProp._ +import sigmastate.utils.Helpers._ import scala.util.Random diff --git a/sigmastate/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala b/sigmastate/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala index 65f3845ac5..40859c0d90 100644 --- a/sigmastate/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala +++ b/sigmastate/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala @@ -17,7 +17,7 @@ import sigmastate.utxo._ class ErgoTreeBuildingTest extends BaseCtxTests with LangTests with ExampleContracts with ErgoScriptTestkit { - implicit override lazy val IR = new TestContext with IRContext with CompiletimeCosting { + implicit override lazy val IR: TestContext with IRContext = new TestContext with IRContext with CompiletimeCosting { beginPass(noConstPropagationPass) } @@ -64,10 +64,10 @@ class ErgoTreeBuildingTest extends BaseCtxTests } test("context data") { - import IR.builder._ - build(emptyEnv, "height1", "HEIGHT + 1L", mkPlus(Height, LongConstant(1))) - build(emptyEnv, "size", "INPUTS.size + OUTPUTS.size", mkPlus(SizeOf(Inputs), SizeOf(Outputs))) - build(emptyEnv, "value", "SELF.value + 1L", mkPlus(ExtractAmount(Self), LongConstant(1))) + val b = IR.builder + build(emptyEnv, "height1", "HEIGHT + 1L", b.mkPlus(Height, LongConstant(1))) + build(emptyEnv, "size", "INPUTS.size + OUTPUTS.size", b.mkPlus(SizeOf(Inputs), SizeOf(Outputs))) + build(emptyEnv, "value", "SELF.value + 1L", b.mkPlus(ExtractAmount(Self), LongConstant(1))) } test("simple lambdas") { diff --git a/sigmastate/src/test/scala/sigmastate/eval/ExampleContracts.scala b/sigmastate/src/test/scala/sigmastate/eval/ExampleContracts.scala index 2acf58361c..8e836f04d0 100644 --- a/sigmastate/src/test/scala/sigmastate/eval/ExampleContracts.scala +++ b/sigmastate/src/test/scala/sigmastate/eval/ExampleContracts.scala @@ -34,7 +34,7 @@ trait ExampleContracts extends ErgoScriptTestkit { self: BaseCtxTests => val envDem = Map( "demurragePeriod" -> demurragePeriod, "demurrageCost" -> demurrageCost, - "regScriptId" -> regScriptId, + "regScriptId" -> regScriptId ) val demurrageScript = diff --git a/sigmastate/src/test/scala/sigmastate/helpers/SigmaTestingCommons.scala b/sigmastate/src/test/scala/sigmastate/helpers/SigmaTestingCommons.scala index 9f9e6de88e..0589eeeb1f 100644 --- a/sigmastate/src/test/scala/sigmastate/helpers/SigmaTestingCommons.scala +++ b/sigmastate/src/test/scala/sigmastate/helpers/SigmaTestingCommons.scala @@ -13,7 +13,6 @@ import org.scalatest.prop.{GeneratorDrivenPropertyChecks, PropertyChecks} import org.scalatest.{Assertion, Matchers, PropSpec} import scalan.{RType, TestContexts, TestUtils} import scorex.crypto.hash.{Blake2b256, Digest32} -import scorex.util.serialization.{VLQByteStringReader, VLQByteStringWriter} import sigma.types.IsPrimView import sigmastate.Values.{Constant, ErgoTree, EvaluatedValue, GroupElementConstant, SValue, Value} import sigmastate.interpreter.Interpreter.{ScriptEnv, ScriptNameProp} @@ -197,13 +196,6 @@ trait SigmaTestingCommons extends PropSpec val positionLimitBefore = r.positionLimit serializer.parse(r) shouldBe v r.positionLimit shouldBe positionLimitBefore - - // using ergo's(scorex) reader/writer - val w = new VLQByteStringWriter() - serializer.serializeWithGenericWriter(v, w) - val byteStr = w.result() - byteStr.nonEmpty shouldBe true - serializer.parseWithGenericReader(new VLQByteStringReader(byteStr)) shouldEqual v } protected def roundTripTestWithPos[T](v: T)(implicit serializer: SigmaSerializer[T, T]): Assertion = { diff --git a/sigmastate/src/test/scala/sigmastate/lang/SigmaTyperTest.scala b/sigmastate/src/test/scala/sigmastate/lang/SigmaTyperTest.scala index d90492dddf..3482ed1e46 100644 --- a/sigmastate/src/test/scala/sigmastate/lang/SigmaTyperTest.scala +++ b/sigmastate/src/test/scala/sigmastate/lang/SigmaTyperTest.scala @@ -678,7 +678,7 @@ class SigmaTyperTest extends PropSpec with PropertyChecks with Matchers with Lan "scriptBytes" -> Colls.fromArray(inputBytes), "positions" -> positions, "newVals" -> newVals, - "expectedBytes" -> Colls.fromArray(expectedBytes), + "expectedBytes" -> Colls.fromArray(expectedBytes) ) typecheck(customEnv, "substConstants(scriptBytes, positions, newVals)") shouldBe SByteArray } diff --git a/sigmastate/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala b/sigmastate/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala index f81b44fda6..bfa922ab69 100644 --- a/sigmastate/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala +++ b/sigmastate/src/test/scala/sigmastate/serialization/AndSerializerSpecification.scala @@ -20,7 +20,7 @@ class AndSerializerSpecification extends TableSerializationSpecification { Array[Byte](AndCode, ConcreteCollectionCode, 2, SBoolean.typeCode, // collection type SBoolean.typeCode, 1, EqCode, SInt.typeCode, encodeZigZagInt(1).toByte, - SInt.typeCode, encodeZigZagInt(1).toByte)), + SInt.typeCode, encodeZigZagInt(1).toByte)) ) tableRoundTripTest("And: Serializer round trip on predefined values") diff --git a/sigmastate/src/test/scala/sigmastate/serialization/DeserializationResilience.scala b/sigmastate/src/test/scala/sigmastate/serialization/DeserializationResilience.scala index 4ba603dfc7..4f6f6be3a5 100644 --- a/sigmastate/src/test/scala/sigmastate/serialization/DeserializationResilience.scala +++ b/sigmastate/src/test/scala/sigmastate/serialization/DeserializationResilience.scala @@ -19,6 +19,7 @@ import sigmastate.lang.exceptions.{DeserializeCallDepthExceeded, InputSizeLimitE import sigmastate.serialization.OpCodes._ import sigmastate.utils.SigmaByteReader import sigmastate.utxo.SizeOf +import sigmastate.utils.Helpers._ import scala.collection.mutable diff --git a/sigmastate/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala b/sigmastate/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala index 124bdfb637..b7fbf54c66 100644 --- a/sigmastate/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala +++ b/sigmastate/src/test/scala/sigmastate/serialization/OrSerializerSpecification.scala @@ -20,7 +20,7 @@ class OrSerializerSpecification extends TableSerializationSpecification { Array[Byte](OrCode, ConcreteCollectionCode, 2, SBoolean.typeCode, // collection type SBoolean.typeCode, 1, EqCode, SInt.typeCode, encodeZigZagInt(1).toByte, - SInt.typeCode, encodeZigZagInt(1).toByte)), + SInt.typeCode, encodeZigZagInt(1).toByte)) ) tableRoundTripTest("Or: Serializer round trip on predefined values") diff --git a/sigmastate/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala b/sigmastate/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala index 02d0a4883f..ceb58bd3fe 100644 --- a/sigmastate/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala +++ b/sigmastate/src/test/scala/sigmastate/serialization/generators/TypeGenerators.scala @@ -39,7 +39,7 @@ trait TypeGenerators { shortTypeGen, intTypeGen, longTypeGen, - bigIntTypeGen, + bigIntTypeGen )) } yield STuple(values.toIndexedSeq) diff --git a/sigmastate/src/test/scala/sigmastate/utils/GenInfoObjects.scala b/sigmastate/src/test/scala/sigmastate/utils/GenInfoObjects.scala index 8e08038066..a6169dc4cf 100644 --- a/sigmastate/src/test/scala/sigmastate/utils/GenInfoObjects.scala +++ b/sigmastate/src/test/scala/sigmastate/utils/GenInfoObjects.scala @@ -3,6 +3,7 @@ package sigmastate.utils import sigmastate.SMethod import scalan.util.PrintExtensions._ import scala.util.Try +import Helpers._ /** Generate as a console output all InfoObject objects. * Those provide stable identifiers to access metadata information. diff --git a/sigmastate/src/test/scala/sigmastate/utils/SparseArrayContainerSpecification.scala b/sigmastate/src/test/scala/sigmastate/utils/SparseArrayContainerSpecification.scala index 796dd1c8f2..b1f6a5705f 100644 --- a/sigmastate/src/test/scala/sigmastate/utils/SparseArrayContainerSpecification.scala +++ b/sigmastate/src/test/scala/sigmastate/utils/SparseArrayContainerSpecification.scala @@ -30,7 +30,7 @@ class SparseArrayContainerSpecification extends PropSpec val mappedValues = codeValuePairs.toMap (Byte.MinValue to Byte.MaxValue).foreach { i => if (mappedValues.get(i.toByte).isEmpty) - cont(i.toByte) shouldBe null.asInstanceOf[Long] + cont(i.toByte) shouldBe 0L } } } diff --git a/sigmastate/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala b/sigmastate/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala index 4a4da55565..0751d252b9 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala +++ b/sigmastate/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala @@ -15,6 +15,7 @@ import sigmastate.lang.Terms._ import special.sigma.InvalidType import SType.AnyOps import sigmastate.interpreter.CryptoConstants +import sigmastate.utils.Helpers._ class BasicOpsSpecification extends SigmaTestingCommons { implicit lazy val IR = new TestingIRContext { @@ -555,7 +556,7 @@ class BasicOpsSpecification extends SigmaTestingCommons { FuncValue(Vector((1, SInt)), Plus(ValUse(1, SInt), IntConstant(1))), Vector(IntConstant(2)) ), - IntConstant(3)).toSigmaProp, + IntConstant(3)).toSigmaProp ) } diff --git a/sigmastate/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala b/sigmastate/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala index 2b419441b3..9af0ab0480 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala +++ b/sigmastate/src/test/scala/sigmastate/utxo/CollectionOperationsSpecification.scala @@ -10,6 +10,7 @@ import org.ergoplatform._ import sigmastate.SCollection._ import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} import sigmastate.serialization.OpCodes._ +import sigmastate.utils.Helpers._ class CollectionOperationsSpecification extends SigmaTestingCommons { implicit lazy val IR: TestingIRContext = new TestingIRContext diff --git a/sigmastate/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala b/sigmastate/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala index 4dedc606c2..50eeea025f 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala +++ b/sigmastate/src/test/scala/sigmastate/utxo/ErgoLikeInterpreterSpecification.scala @@ -18,6 +18,7 @@ import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeConte import sigmastate.lang.Terms._ import sigmastate.lang.exceptions.InterpreterException import sigmastate.serialization.{SerializationSpecification, ValueSerializer} +import sigmastate.utils.Helpers._ class ErgoLikeInterpreterSpecification extends SigmaTestingCommons with SerializationSpecification { diff --git a/sigmastate/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala b/sigmastate/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala index c68f1dc03a..f7fd2eff31 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala +++ b/sigmastate/src/test/scala/sigmastate/utxo/ThresholdSpecification.scala @@ -7,7 +7,7 @@ import sigmastate._ import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter, ErgoLikeTransactionTesting, SigmaTestingCommons} import sigmastate.lang.Terms._ import sigmastate.lang.exceptions.CosterException - +import sigmastate.utils.Helpers._ class ThresholdSpecification extends SigmaTestingCommons { implicit lazy val IR = new TestingIRContext { diff --git a/sigmastate/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala b/sigmastate/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala index 769781e081..c37694ffd3 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala +++ b/sigmastate/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala @@ -9,7 +9,7 @@ import sigmastate.{AvlTreeData, AvlTreeFlags, GE, Values} import sigmastate.Values.{ErgoTree, LongConstant} import sigmastate.eval._ import sigmastate.helpers.{BlockchainState, ErgoLikeContextTesting, ErgoLikeTestProvingInterpreter, ErgoTransactionValidator, SigmaTestingCommons} - +import sigmastate.utils.Helpers._ import scala.collection.mutable import scala.util.{Random, Try} import scorex.util._ diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala b/sigmastate/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala index 6e5f297808..2feb15cf14 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala +++ b/sigmastate/src/test/scala/sigmastate/utxo/examples/OracleExamplesSpecification.scala @@ -19,7 +19,7 @@ import org.ergoplatform.dsl.{ContractSpec, SigmaContractSyntax, StdContracts, Te import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} import sigmastate.utxo._ import special.sigma.Context - +import sigmastate.utils.Helpers._ class OracleExamplesSpecification extends SigmaTestingCommons { suite => implicit lazy val IR: TestingIRContext = new TestingIRContext diff --git a/sigmastate/src/test/scala/sigmastate/utxo/examples/RevenueSharingExamplesSpecification.scala b/sigmastate/src/test/scala/sigmastate/utxo/examples/RevenueSharingExamplesSpecification.scala index cbe2278793..402c4470c3 100644 --- a/sigmastate/src/test/scala/sigmastate/utxo/examples/RevenueSharingExamplesSpecification.scala +++ b/sigmastate/src/test/scala/sigmastate/utxo/examples/RevenueSharingExamplesSpecification.scala @@ -31,7 +31,7 @@ class RevenueSharingExamplesSpecification extends SigmaTestingCommons { suite => "feeProp" -> feeProp, "requireAliceSignature" -> alice.pubKey, "requireBobSignature" -> bob.pubKey, - "requireCarolSignature" -> carol.pubKey, + "requireCarolSignature" -> carol.pubKey ) lazy val prop = proposition("revenueContract", { CONTEXT: Context => import CONTEXT._