From 105bd4e66d72a7e0428d6e0526157b33163a1249 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Mon, 15 Jan 2024 23:47:37 +0300 Subject: [PATCH 01/65] unused mapReduce removed --- .../org/ergoplatform/sdk/Extensions.scala | 23 ------------------- .../org/ergoplatform/sdk/ExtensionsSpec.scala | 6 +---- 2 files changed, 1 insertion(+), 28 deletions(-) diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/Extensions.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/Extensions.scala index c8fb2e57f8..84462d81cb 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/Extensions.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/Extensions.scala @@ -13,29 +13,6 @@ import scala.reflect.ClassTag object Extensions { - implicit class GenIterableOps[A, Source[X] <: GenIterable[X]](val xs: Source[A]) extends AnyVal { - - /** Apply m for each element of this collection, group by key and reduce each group - * using r. - * Note, the ordering of the resulting keys is deterministic and the keys appear in - * the order they first produced by `map`. - * - * @returns one item for each group in a new collection of (K,V) pairs. */ - def mapReduce[K, V](map: A => (K, V))(reduce: (V, V) => V) - (implicit cbf: BuildFrom[Source[A], (K, V), Source[(K, V)]]): Source[(K, V)] = { - val result = scala.collection.mutable.LinkedHashMap.empty[K, V] - xs.foreach { x => - val (key, value) = map(x) - val reduced = if (result.contains(key)) reduce(result(key), value) else value - result.update(key, reduced) - } - - val b = cbf.newBuilder(xs) - for ( kv <- result ) b += kv - b.result() - } - } - implicit class CollOps[A](val coll: Coll[A]) extends AnyVal { /** Partitions this $coll in two $colls according to a predicate. diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/ExtensionsSpec.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/ExtensionsSpec.scala index 98f61331bb..32d71abede 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/ExtensionsSpec.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/ExtensionsSpec.scala @@ -4,7 +4,7 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import sigma.{Coll, CollGens} -import org.ergoplatform.sdk.Extensions.{CollBuilderOps, CollOps, GenIterableOps, PairCollOps} +import org.ergoplatform.sdk.Extensions.{CollBuilderOps, CollOps, PairCollOps} import sigma.data.{CSigmaDslBuilder, RType} class ExtensionsSpec extends AnyPropSpec with ScalaCheckPropertyChecks with Matchers with CollGens { @@ -13,10 +13,6 @@ class ExtensionsSpec extends AnyPropSpec with ScalaCheckPropertyChecks with Matc val items: Iterable[(Int, String)] = Array((1, "a"), (2, "b"), (1, "c")) - property("Traversable.mapReduce") { - val res = items.mapReduce(p => (p._1, p._2))((v1, v2) => v1 + v2) - assertResult(List((1, "ac"), (2, "b")))(res) - } property("Coll.partition") { forAll(collGen) { col: Coll[Int] => From 8168ea02b03fcd241b8b4b01a8894ee582e6f094 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Tue, 16 Jan 2024 00:37:37 +0300 Subject: [PATCH 02/65] DoubleOps removed --- .../src/main/scala/org/ergoplatform/sdk/Extensions.scala | 3 --- 1 file changed, 3 deletions(-) diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/Extensions.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/Extensions.scala index 84462d81cb..320aae5919 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/Extensions.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/Extensions.scala @@ -182,7 +182,4 @@ object Extensions { } } - implicit class DoubleOps(val i: Double) extends AnyVal { - def erg: Long = (i * 1000000000L).toLong - } } From c33801ae3f7e3db0109f3ad7077809e6f838eb5f Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Tue, 16 Jan 2024 01:01:55 +0300 Subject: [PATCH 03/65] unused imports in SigmaDslImpl.scala --- .../src/main/scala/special/sigma/impl/SigmaDslImpl.scala | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala index 8da36ce6cf..037505b531 100644 --- a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala +++ b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala @@ -22,19 +22,16 @@ import BigInt._ import Box._ import Coll._ import CollBuilder._ -import Context._ import GroupElement._ import Header._ import PreHeader._ -import SigmaDslBuilder._ import SigmaProp._ import WOption._ -import WRType._ + object BigInt extends EntityObject("BigInt") { // entityConst: single const for each entity import Liftables._ - import scala.reflect.{ClassTag, classTag} type SBigInt = sigma.BigInt case class BigIntConst( constValue: SBigInt From bd27625b33f7d6dcf25ae31838e1e76d173bc408 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Tue, 16 Jan 2024 01:20:26 +0300 Subject: [PATCH 04/65] removing unused endPass; more unused imports --- .../src/main/scala/sigma/ast/CostItem.scala | 3 --- .../scala/scalan/primitives/Functions.scala | 2 +- .../main/scala/scalan/primitives/Thunks.scala | 2 +- .../scala/scalan/staged/Transforming.scala | 22 ++++++++----------- .../scala/special/collection/CollsUnit.scala | 3 --- 5 files changed, 11 insertions(+), 21 deletions(-) diff --git a/data/shared/src/main/scala/sigma/ast/CostItem.scala b/data/shared/src/main/scala/sigma/ast/CostItem.scala index 8fa973b575..c69c81daa3 100644 --- a/data/shared/src/main/scala/sigma/ast/CostItem.scala +++ b/data/shared/src/main/scala/sigma/ast/CostItem.scala @@ -1,8 +1,5 @@ package sigma.ast -import sigma.ast -import sigma.eval.CostDetails - /** An item in the cost accumulation trace of a [[sigma.ast.ErgoTree]] evaluation. */ abstract class CostItem { def opName: String diff --git a/sc/shared/src/main/scala/scalan/primitives/Functions.scala b/sc/shared/src/main/scala/scalan/primitives/Functions.scala index e5cd6f345e..31a6ca8d81 100644 --- a/sc/shared/src/main/scala/scalan/primitives/Functions.scala +++ b/sc/shared/src/main/scala/scalan/primitives/Functions.scala @@ -332,7 +332,7 @@ trait Functions extends Base with ProgramGraphs { self: Scalan => val m = new java.util.HashMap[Sym, Sym](100) m.put(lam.x, s) val subst = new MapTransformer(m) - val t = DefaultMirror.mirrorSymbols(subst, NoRewriting, lam, body) + val t = DefaultMirror.mirrorSymbols(subst, NoRewriting, body) t(lam.y) } diff --git a/sc/shared/src/main/scala/scalan/primitives/Thunks.scala b/sc/shared/src/main/scala/scalan/primitives/Thunks.scala index ce51dc5638..f9f843664d 100644 --- a/sc/shared/src/main/scala/scalan/primitives/Thunks.scala +++ b/sc/shared/src/main/scala/scalan/primitives/Thunks.scala @@ -323,7 +323,7 @@ trait Thunks extends Functions { self: Scalan => */ def forceThunkDefByMirror[A](th: ThunkDef[A], subst: MapTransformer = MapTransformer.empty()): Ref[A] = { val body = th.scheduleIds - val t = DefaultMirror.mirrorSymbols(subst, NoRewriting, th, body) + val t = DefaultMirror.mirrorSymbols(subst, NoRewriting, body) t(th.root) } diff --git a/sc/shared/src/main/scala/scalan/staged/Transforming.scala b/sc/shared/src/main/scala/scalan/staged/Transforming.scala index 045340e503..cd1fac9fd0 100644 --- a/sc/shared/src/main/scala/scalan/staged/Transforming.scala +++ b/sc/shared/src/main/scala/scalan/staged/Transforming.scala @@ -65,10 +65,6 @@ trait Transforming { self: Scalan => def beginPass(pass: Pass): Unit = { _currentPass = pass } - /** Called to let this IR context to finalized the given pass. */ - def endPass(pass: Pass): Unit = { - _currentPass = Pass.defaultPass - } /** Concrete and default implementation of Transformer using underlying HashMap. * HOTSPOT: don't beatify the code */ @@ -152,7 +148,7 @@ trait Transforming { self: Scalan => protected def mirrorElem(node: Sym): Elem[_] = node.elem // every mirrorXXX method should return a pair (t + (v -> v1), v1) - protected def mirrorVar[A](t: Transformer, rewriter: Rewriter, v: Ref[A]): Transformer = { + protected def mirrorVar[A](t: Transformer, v: Ref[A]): Transformer = { val newVar = variable(Lazy(mirrorElem(v))) t + (v, newVar) } @@ -173,7 +169,7 @@ trait Transforming { self: Scalan => protected def mirrorLambda[A, B](t: Transformer, rewriter: Rewriter, node: Ref[A => B], lam: Lambda[A, B]): Transformer = { var tRes: Transformer = t - val t1 = mirrorNode(t, rewriter, lam, lam.x) + val t1 = mirrorNode(t, rewriter, lam.x) // original root val originalRoot = lam.y @@ -190,7 +186,7 @@ trait Transforming { self: Scalan => // lambdaStack = newLambdaCandidate :: lambdaStack val newRoot = { // reifyEffects block val schedule = lam.scheduleIds - val t2 = mirrorSymbols(t1, rewriter, lam, schedule) + val t2 = mirrorSymbols(t1, rewriter, schedule) tRes = t2 tRes(originalRoot) // this will be a new root } @@ -214,7 +210,7 @@ trait Transforming { self: Scalan => val newScope = thunkStack.beginScope(newThunkSym) val schedule = thunk.scheduleIds - val t1 = mirrorSymbols(t, rewriter, thunk, schedule) + val t1 = mirrorSymbols(t, rewriter, schedule) thunkStack.endScope() val newRoot = t1(thunk.root) @@ -230,12 +226,12 @@ trait Transforming { self: Scalan => protected def isMirrored(t: Transformer, node: Sym): Boolean = t.isDefinedAt(node) - def mirrorNode(t: Transformer, rewriter: Rewriter, g: AstGraph, node: Sym): Transformer = { + def mirrorNode(t: Transformer, rewriter: Rewriter, node: Sym): Transformer = { if (isMirrored(t, node)) t else { node.node match { - case v: Variable[_] => - mirrorVar(t, rewriter, node) + case _: Variable[_] => + mirrorVar(t, node) case lam: Lambda[a, b] => mirrorLambda(t, rewriter, node.asInstanceOf[Ref[a => b]], lam) case th: ThunkDef[a] => @@ -247,12 +243,12 @@ trait Transforming { self: Scalan => } /** HOTSPOT: */ - def mirrorSymbols(t0: Transformer, rewriter: Rewriter, g: AstGraph, nodes: DBuffer[Int]) = { + def mirrorSymbols(t0: Transformer, rewriter: Rewriter, nodes: DBuffer[Int]): Transformer = { var t: Transformer = t0 cfor(0)(_ < nodes.length, _ + 1) { i => val n = nodes(i) val s = getSym(n) - t = mirrorNode(t, rewriter, g, s) + t = mirrorNode(t, rewriter, s) } t } diff --git a/sc/shared/src/main/scala/special/collection/CollsUnit.scala b/sc/shared/src/main/scala/special/collection/CollsUnit.scala index 02e62aeb4d..19ae1f5e48 100644 --- a/sc/shared/src/main/scala/special/collection/CollsUnit.scala +++ b/sc/shared/src/main/scala/special/collection/CollsUnit.scala @@ -9,9 +9,6 @@ package sigma { * for details. */ trait Colls extends Base { self: Library => - import Coll._; - import CollBuilder._; - import WOption._; trait Coll[A] extends Def[Coll[A]] { implicit def eA: Elem[A]; def length: Ref[Int]; From d378c3b66f82781e7a2214c24f6db5b10873f44b Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Tue, 16 Jan 2024 01:31:24 +0300 Subject: [PATCH 05/65] fixing Coll.mapReduce test --- .../src/test/scala/org/ergoplatform/sdk/ExtensionsSpec.scala | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/ExtensionsSpec.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/ExtensionsSpec.scala index 32d71abede..1f3c8d9064 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/ExtensionsSpec.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/ExtensionsSpec.scala @@ -5,6 +5,7 @@ import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import sigma.{Coll, CollGens} import org.ergoplatform.sdk.Extensions.{CollBuilderOps, CollOps, PairCollOps} +import sigma.Extensions.ArrayOps import sigma.data.{CSigmaDslBuilder, RType} class ExtensionsSpec extends AnyPropSpec with ScalaCheckPropertyChecks with Matchers with CollGens { @@ -24,14 +25,14 @@ class ExtensionsSpec extends AnyPropSpec with ScalaCheckPropertyChecks with Matc } property("Coll.mapReduce") { - def m(x: Int) = (math.abs(x) % 10, x) + def m(x: Int): (Int, Int) = (math.abs(x) % 10, x) forAll(collGen) { col => val res = col.mapReduce(m, plusF) val (ks, vs) = builder.unzip(res) vs.toArray.sum shouldBe col.toArray.sum ks.length <= 10 shouldBe true - res.toArray shouldBe col.toArray.toIterable.mapReduce(m)(plus).toArray + res.toArray shouldBe col.toArray.toColl.mapReduce[Int, Int](m, plusF).toArray } } From 3865cd11eb3a6fb5fa502d8d47ea0f72caf2890a Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Thu, 21 Mar 2024 12:26:56 +0300 Subject: [PATCH 06/65] removing more unused arguments --- data/shared/src/main/scala/sigma/ast/SigmaPredef.scala | 2 +- data/shared/src/main/scala/sigma/ast/methods.scala | 7 +++---- data/shared/src/main/scala/sigma/ast/trees.scala | 1 - .../scala/sigma/serialization/ErgoTreeSerializer.scala | 2 +- .../main/scala/sigma/serialization/SigmaSerializer.scala | 4 +--- .../main/scala/sigma/interpreter/js/SigmaPropProver.scala | 1 - .../src/main/scala/org/ergoplatform/ErgoLikeContext.scala | 1 - .../shared/src/main/scala/sigmastate/crypto/GF2_192.scala | 2 -- .../src/main/scala/sigmastate/crypto/GF2_192_Poly.scala | 2 -- .../shared/src/main/scala/sigmastate/eval/CProfiler.scala | 6 +++--- .../main/scala/sigmastate/interpreter/Interpreter.scala | 5 ++--- .../main/scala/sigmastate/interpreter/ProverUtils.scala | 6 ++---- 12 files changed, 13 insertions(+), 26 deletions(-) diff --git a/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala b/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala index 5cdbdedaa8..c4bc32e4a5 100644 --- a/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala +++ b/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala @@ -591,7 +591,7 @@ object SigmaPredef { ).map(f => f.name -> f).toMap private val funcNameToIrBuilderMap: Map[String, PredefinedFunc] = - funcs.filter { case (n, f) => f.irInfo.irBuilder != undefined } + funcs.filter { case (_, f) => f.irInfo.irBuilder != undefined } def irBuilderForFunc(name: String): Option[IrBuilderFunc] = funcNameToIrBuilderMap.get(name).map(_.irInfo.irBuilder) } diff --git a/data/shared/src/main/scala/sigma/ast/methods.scala b/data/shared/src/main/scala/sigma/ast/methods.scala index b637acf792..23a73c9fae 100644 --- a/data/shared/src/main/scala/sigma/ast/methods.scala +++ b/data/shared/src/main/scala/sigma/ast/methods.scala @@ -15,7 +15,6 @@ import sigma.serialization.CoreByteWriter.ArgInfo import sigma.utils.SparseArrayContainer import scala.annotation.unused -import scala.language.implicitConversions /** Base type for all companions of AST nodes of sigma lang. */ trait SigmaNodeCompanion @@ -720,7 +719,7 @@ object SCollectionMethods extends MethodsContainer with MethodByNameUnapply { * of flatMap. Other bodies are rejected with throwing exception. */ val flatMap_BodyPatterns = Array[PartialFunction[SValue, Int]]( - { case MethodCall(ValUse(id, tpe), m, args, _) if args.isEmpty => id }, + { case MethodCall(ValUse(id, _), _, args, _) if args.isEmpty => id }, { case ExtractScriptBytes(ValUse(id, _)) => id }, { case ExtractId(ValUse(id, _)) => id }, { case SigmaPropBytes(ValUse(id, _)) => id }, @@ -766,7 +765,7 @@ object SCollectionMethods extends MethodsContainer with MethodByNameUnapply { var res: Nullable[(Int, SValue)] = Nullable.None E.addFixedCost(MatchSingleArgMethodCall_Info) { res = mc match { - case MethodCall(_, m, Seq(FuncValue(args, body)), _) if args.length == 1 => + case MethodCall(_, _, Seq(FuncValue(args, body)), _) if args.length == 1 => val id = args(0)._1 Nullable((id, body)) case _ => @@ -1480,7 +1479,7 @@ case object SGlobalMethods extends MonoTypeMethods { lazy val groupGeneratorMethod = SMethod( this, "groupGenerator", SFunc(SGlobal, SGroupElement), 1, GroupGenerator.costKind) - .withIRInfo({ case (builder, obj, method, args, tparamSubst) => GroupGenerator }) + .withIRInfo({ case (_, _, _, _, _) => GroupGenerator }) .withInfo(GroupGenerator, "") lazy val xorMethod = SMethod( diff --git a/data/shared/src/main/scala/sigma/ast/trees.scala b/data/shared/src/main/scala/sigma/ast/trees.scala index 38d4565f30..39e666a389 100644 --- a/data/shared/src/main/scala/sigma/ast/trees.scala +++ b/data/shared/src/main/scala/sigma/ast/trees.scala @@ -295,7 +295,6 @@ object AND extends LogicalTransformerCompanion { def apply(children: Seq[Value[SBoolean.type]]): AND = AND(ConcreteCollection.fromSeq(children)) -// def apply(head: Value[SBoolean.type], tail: Value[SBoolean.type]*): AND = apply(head +: tail) def apply(items: Value[SBoolean.type]*)(implicit o1: Overloaded1): AND = apply(items) } diff --git a/data/shared/src/main/scala/sigma/serialization/ErgoTreeSerializer.scala b/data/shared/src/main/scala/sigma/serialization/ErgoTreeSerializer.scala index 3d1061d774..91765f764b 100644 --- a/data/shared/src/main/scala/sigma/serialization/ErgoTreeSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/ErgoTreeSerializer.scala @@ -299,7 +299,7 @@ class ErgoTreeSerializer { */ def substituteConstants(scriptBytes: Array[Byte], positions: Array[Int], - newVals: Array[Constant[SType]])(implicit vs: SigmaValidationSettings): (Array[Byte], Int) = { + newVals: Array[Constant[SType]]): (Array[Byte], Int) = { require(positions.length == newVals.length, s"expected positions and newVals to have the same length, got: positions: ${positions.toSeq},\n newVals: ${newVals.toSeq}") val r = SigmaSerializer.startReader(scriptBytes) diff --git a/data/shared/src/main/scala/sigma/serialization/SigmaSerializer.scala b/data/shared/src/main/scala/sigma/serialization/SigmaSerializer.scala index cdb28d724b..3765adb029 100644 --- a/data/shared/src/main/scala/sigma/serialization/SigmaSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/SigmaSerializer.scala @@ -4,7 +4,6 @@ import java.nio.ByteBuffer import scorex.util.ByteArrayBuilder import scorex.util.serialization._ import sigma.data.SigmaConstants -import sigma.validation.SigmaValidationSettings import sigma.serialization.ValueCodes.OpCode object SigmaSerializer { @@ -35,8 +34,7 @@ object SigmaSerializer { /** Helper function to be use in serializers. */ def startReader(bytes: Array[Byte], constantStore: ConstantStore, - resolvePlaceholdersToConstants: Boolean) - (implicit vs: SigmaValidationSettings): SigmaByteReader = { + resolvePlaceholdersToConstants: Boolean): SigmaByteReader = { val buf = ByteBuffer.wrap(bytes) val r = new SigmaByteReader(new VLQByteBufferReader(buf), constantStore, diff --git a/interpreter/js/src/main/scala/sigma/interpreter/js/SigmaPropProver.scala b/interpreter/js/src/main/scala/sigma/interpreter/js/SigmaPropProver.scala index a04d32fa54..414a9d1220 100644 --- a/interpreter/js/src/main/scala/sigma/interpreter/js/SigmaPropProver.scala +++ b/interpreter/js/src/main/scala/sigma/interpreter/js/SigmaPropProver.scala @@ -65,7 +65,6 @@ class SigmaPropProver(override val wrappedValue: org.ergoplatform.SigmaPropProve val realsToExtract = toSigmaBooleanSeq(realSecretsToExtract) val simsToExtract = toSigmaBooleanSeq(simulatedSecretsToExtract) val hints = wrappedValue.bagForMultisig( - context = null, sigmaTree = sigmaTree.sigmaBoolean, proof.toArray, realSecretsToExtract = realsToExtract, simulatedSecretsToExtract = simsToExtract) diff --git a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeContext.scala b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeContext.scala index 8468175631..e421e8fdfe 100644 --- a/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeContext.scala +++ b/interpreter/shared/src/main/scala/org/ergoplatform/ErgoLikeContext.scala @@ -6,7 +6,6 @@ import sigma.ast.SType.{AnyOps, TypeCode} import sigma.ast._ import sigma.data.{AvlTreeData, CAvlTree, CSigmaDslBuilder, SigmaConstants} import sigma.eval.Extensions.toAnyValue -import sigma.exceptions.InterpreterException import sigma.interpreter.ContextExtension import sigma.validation.SigmaValidationSettings import sigma.{AnyValue, Coll, Header, PreHeader} diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/GF2_192.scala b/interpreter/shared/src/main/scala/sigmastate/crypto/GF2_192.scala index bb0ad60a84..e63526e854 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/GF2_192.scala +++ b/interpreter/shared/src/main/scala/sigmastate/crypto/GF2_192.scala @@ -30,8 +30,6 @@ package sigmastate.crypto import debox.cfor -import java.util - class GF2_192 extends AnyRef { private[crypto] val word: Array[Long] = new Array[Long](3) diff --git a/interpreter/shared/src/main/scala/sigmastate/crypto/GF2_192_Poly.scala b/interpreter/shared/src/main/scala/sigmastate/crypto/GF2_192_Poly.scala index a9212fe565..d2ddc4db48 100644 --- a/interpreter/shared/src/main/scala/sigmastate/crypto/GF2_192_Poly.scala +++ b/interpreter/shared/src/main/scala/sigmastate/crypto/GF2_192_Poly.scala @@ -31,8 +31,6 @@ package sigmastate.crypto import debox.cfor -import java.util - class GF2_192_Poly { final private var c: Array[GF2_192] = null // must be not null and of length at least 1 diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/CProfiler.scala b/interpreter/shared/src/main/scala/sigmastate/eval/CProfiler.scala index ced8a357b8..d07153bd51 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/CProfiler.scala +++ b/interpreter/shared/src/main/scala/sigmastate/eval/CProfiler.scala @@ -280,7 +280,7 @@ class CProfiler extends Profiler { case ci: TypeBasedCostItem => val comment = s"count: $count, suggested: $suggestedCost, actCost: ${ci.cost}$warn" (ci.opName, time, time, comment) - case ci @ SeqCostItem(_, costKind, nItems) => + case ci @ SeqCostItem(_, costKind, _) => val nChunks = ci.chunks val timePerChunk = if (nChunks > 0) time / nChunks else time val name = s"${ci.opName}(nChunks: $nChunks)" @@ -289,7 +289,7 @@ class CProfiler extends Profiler { } } (name, timePerItem, time, comment) - }.sortBy({ case (name, tpi, t, c) => (name, tpi)})(Ordering[(String, Long)]) + }.sortBy({ case (name, tpi, _, _) => (name, tpi)})(Ordering[(String, Long)]) val estLines = estimationCostStat.mapToArray { case (script, stat) => val (cost, count) = stat.mean @@ -302,7 +302,7 @@ class CProfiler extends Profiler { val rows = opCodeLines - .map { case (opName, opCode, time, comment) => + .map { case (opName, _, time, comment) => val key = s"$opName".padTo(26, ' ') s"$key -> time: $time ns, $comment " } diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala index 6b673038c7..523b2a7f35 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala @@ -164,12 +164,11 @@ trait Interpreter { * else `exp` is computed in the given context and the resulting SigmaBoolean returned. * * @param context the context in which `exp` should be executed - * @param env environment of system variables used by the interpreter internally * @param exp expression to be executed in the given `context` * @return result of script reduction * @see `ReductionResult` */ - protected def reduceToCryptoJITC(context: CTX, env: ScriptEnv, exp: SigmaPropValue): Try[ReductionResult] = Try { + protected def reduceToCryptoJITC(context: CTX, exp: SigmaPropValue): Try[ReductionResult] = Try { implicit val vs = context.validationSettings trySoftForkable[ReductionResult](whenSoftFork = WhenSoftForkReductionResult(context.initCost)) { @@ -253,7 +252,7 @@ trait Interpreter { // here we assume that when `propTree` is TrueProp then `reduceToCrypto` always succeeds // and the rest of the verification is also trivial - reduceToCryptoJITC(context2, env, propTree).getOrThrow + reduceToCryptoJITC(context2, propTree).getOrThrow } res diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverUtils.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverUtils.scala index 15daaec382..dc2259b0b7 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverUtils.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/ProverUtils.scala @@ -81,7 +81,7 @@ trait ProverUtils extends Interpreter { realSecretsToExtract: Seq[SigmaBoolean], simulatedSecretsToExtract: Seq[SigmaBoolean] = Seq.empty): HintsBag = { val reduced = fullReduction(ergoTree, context, Interpreter.emptyEnv) - bagForMultisig(context, reduced.value, proof, realSecretsToExtract, simulatedSecretsToExtract) + bagForMultisig(reduced.value, proof, realSecretsToExtract, simulatedSecretsToExtract) } /** @@ -90,15 +90,13 @@ trait ProverUtils extends Interpreter { * * See DistributedSigSpecification for examples of usage. * - * @param context - context used to reduce the proposition * @param sigmaTree - public key (in form of a sigma-tree) * @param proof - signature for the key * @param realSecretsToExtract - public keys of secrets with real proofs * @param simulatedSecretsToExtract - public keys of secrets with simulated proofs * @return - bag of OtherSecretProven and OtherCommitment hints */ - def bagForMultisig(context: CTX, - sigmaTree: SigmaBoolean, + def bagForMultisig(sigmaTree: SigmaBoolean, proof: Array[Byte], realSecretsToExtract: Seq[SigmaBoolean], simulatedSecretsToExtract: Seq[SigmaBoolean]): HintsBag = { From 059cac1925bf2619a5ed83b875e3254d99125cc7 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Fri, 29 Mar 2024 20:21:46 +0300 Subject: [PATCH 07/65] more unused code removed --- data/shared/src/main/scala/sigma/SigmaDataReflection.scala | 3 +-- data/shared/src/main/scala/sigma/ast/SMethod.scala | 2 +- data/shared/src/main/scala/sigma/ast/methods.scala | 2 +- .../src/main/scala/sigmastate/eval/GraphBuilding.scala | 6 ++---- sc/shared/src/main/scala/sigmastate/eval/SigmaLibrary.scala | 2 +- sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala | 6 +++--- sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala | 1 - sc/shared/src/test/scala/scalan/LibraryTests.scala | 2 +- 8 files changed, 10 insertions(+), 14 deletions(-) diff --git a/data/shared/src/main/scala/sigma/SigmaDataReflection.scala b/data/shared/src/main/scala/sigma/SigmaDataReflection.scala index 31703b0856..276deaeeee 100644 --- a/data/shared/src/main/scala/sigma/SigmaDataReflection.scala +++ b/data/shared/src/main/scala/sigma/SigmaDataReflection.scala @@ -314,8 +314,7 @@ object SigmaDataReflection { registerClassEntry(clazz, methods = Map( mkMethod(clazz, "xor_eval", Array[Class[_]](classOf[MethodCall], classOf[SigmaDslBuilder], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SGlobalMethods.type].xor_eval(args(0).asInstanceOf[MethodCall], - args(1).asInstanceOf[SigmaDslBuilder], + obj.asInstanceOf[SGlobalMethods.type].xor_eval( args(2).asInstanceOf[Coll[Byte]], args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) } diff --git a/data/shared/src/main/scala/sigma/ast/SMethod.scala b/data/shared/src/main/scala/sigma/ast/SMethod.scala index 2d306d8948..669625ef1e 100644 --- a/data/shared/src/main/scala/sigma/ast/SMethod.scala +++ b/data/shared/src/main/scala/sigma/ast/SMethod.scala @@ -105,7 +105,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): Any = { + def invokeFixed(obj: Any, args: Array[Any]): Any = { javaMethod.invoke(obj, args.asInstanceOf[Array[AnyRef]]:_*) } diff --git a/data/shared/src/main/scala/sigma/ast/methods.scala b/data/shared/src/main/scala/sigma/ast/methods.scala index 23a73c9fae..2cbc2fda8c 100644 --- a/data/shared/src/main/scala/sigma/ast/methods.scala +++ b/data/shared/src/main/scala/sigma/ast/methods.scala @@ -1494,7 +1494,7 @@ case object SGlobalMethods extends MonoTypeMethods { * Called via reflection based on naming convention. * @see SMethod.evalMethod, Xor.eval, Xor.xorWithCosting */ - def xor_eval(mc: MethodCall, G: SigmaDslBuilder, ls: Coll[Byte], rs: Coll[Byte]) + def xor_eval(ls: Coll[Byte], rs: Coll[Byte]) (implicit E: ErgoTreeEvaluator): Coll[Byte] = { Xor.xorWithCosting(ls, rs) } diff --git a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala index 9c9fa5ffe1..ed25b6afa4 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala @@ -380,8 +380,6 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => case _ => error(s"Cannot find BinOp for opcode newOpCode(${opCode.toUByte - LastConstantCode}) and type $eA") } - import sigmastate._ - protected implicit def groupElementToECPoint(g: sigma.GroupElement): EcPointType = CSigmaDslBuilder.toECPoint(g).asInstanceOf[EcPointType] def error(msg: String) = throw new GraphBuildingException(msg, None) @@ -436,7 +434,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => error(s"Don't know how to buildNode($node)", node.sourceContext.toOption) val res: Ref[Any] = node match { - case c @ Constant(v, tpe) => v match { + case Constant(v, tpe) => v match { case p: SSigmaProp => assert(tpe == SSigmaProp) val resV = liftConst(p) @@ -887,7 +885,7 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => f } - case l @ FuncValue(Seq((n, argTpe)), body) => + case FuncValue(Seq((n, argTpe)), body) => val eArg = stypeToElem(argTpe).asInstanceOf[Elem[Any]] val f = fun { x: Ref[Any] => buildNode(ctx, env + (n -> x), body) diff --git a/sc/shared/src/main/scala/sigmastate/eval/SigmaLibrary.scala b/sc/shared/src/main/scala/sigmastate/eval/SigmaLibrary.scala index be17179cbf..7745873620 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/SigmaLibrary.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/SigmaLibrary.scala @@ -10,7 +10,7 @@ trait SigmaLibrary extends Library { import WRType._ - implicit lazy val wRTypeAnyElement = wRTypeElement(AnyElement) + implicit lazy val wRTypeAnyElement: Elem[WRType[Any]] = wRTypeElement(AnyElement) /** During compilation represent a global value Global, see also SGlobal type. */ def sigmaDslBuilder: Ref[SigmaDslBuilder] diff --git a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala index 26bc33956f..27f659c1ed 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala @@ -161,7 +161,7 @@ trait TreeBuilding extends SigmaLibrary { IR: IRContext => case _ if env.contains(s) => val (id, tpe) = env(s) ValUse(id, tpe) // recursion base - case Def(Lambda(lam, _, x, y)) => + case Def(Lambda(lam, _, x, _)) => val varId = defId + 1 // arguments are treated as ValDefs and occupy id space val env1 = env + (x -> (varId, elemToSType(x.elem))) val block = processAstGraph(ctx, mainG, env1, lam, varId + 1, constantsProcessing) @@ -170,7 +170,7 @@ trait TreeBuilding extends SigmaLibrary { IR: IRContext => case Def(Apply(fSym, xSym, _)) => val Seq(f, x) = Seq(fSym, xSym).map(recurse) builder.mkApply(f, Array(x)) - case Def(th @ ThunkDef(root, _)) => + case Def(th @ ThunkDef(_, _)) => val block = processAstGraph(ctx, mainG, env, th, defId, constantsProcessing) block case Def(Const(x)) => @@ -449,7 +449,7 @@ trait TreeBuilding extends SigmaLibrary { IR: IRContext => (valdefs.toArray[BlockItem], rhs) match { // simple optimization to avoid producing block sub-expressions like: // `{ val idNew = id; idNew }` which this rules rewrites to just `id` - case (Array(ValDef(idNew, _, source @ ValUse(id, tpe))), ValUse(idUse, tpeUse)) + case (Array(ValDef(idNew, _, source @ ValUse(_, tpe))), ValUse(idUse, tpeUse)) if idUse == idNew && tpeUse == tpe => source case (items, _) => BlockValue(items, rhs) diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala index f93e31703d..82aaea7e30 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala @@ -1,7 +1,6 @@ package sigmastate.lang import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix -import org.ergoplatform._ import sigma.ast.NoType import sigma.data.Nullable import sigma.kiama.rewriting.CallbackRewriter diff --git a/sc/shared/src/test/scala/scalan/LibraryTests.scala b/sc/shared/src/test/scala/scalan/LibraryTests.scala index e082e9154d..d095a2f20a 100644 --- a/sc/shared/src/test/scala/scalan/LibraryTests.scala +++ b/sc/shared/src/test/scala/scalan/LibraryTests.scala @@ -8,7 +8,7 @@ class Benchmark[T <: Scalan](createContext: => T) { def run() = { val (ctx, total) = measureTime { var ctx = createContext - measure(10000, okShowIterTime = printDebugInfo, okShowTotalTime = printDebugInfo) { i => + measure(10000, okShowIterTime = printDebugInfo, okShowTotalTime = printDebugInfo) { _ => ctx = createContext } ctx From 08d6b12a73e66d7a1a4903e247154abdb7dfe255 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Tue, 2 Apr 2024 22:29:08 +0300 Subject: [PATCH 08/65] unused SSymName.isImportedBy removed --- sc/shared/src/main/scala/scalan/meta/SSymName.scala | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/sc/shared/src/main/scala/scalan/meta/SSymName.scala b/sc/shared/src/main/scala/scalan/meta/SSymName.scala index ea9b1546ba..b0f8dae6d2 100644 --- a/sc/shared/src/main/scala/scalan/meta/SSymName.scala +++ b/sc/shared/src/main/scala/scalan/meta/SSymName.scala @@ -6,16 +6,11 @@ case class ImportItem(packageName: String, importedNames: List[String]) case class SSymName(packageName: String, name: String) { import SSymName._ - def this(name: String) = this("", name) def mkFullName = fullNameString(packageName, name) - def isImportedBy(item: ImportItem): Boolean = { - if (packageName != item.packageName) return false - item.importedNames.contains(SSymName.ImportAllWildcard) || item.importedNames.contains(name) - } } object SSymName { - /** Wildcard character used to signify imporing all names from namespace */ + /** Wildcard character used to signify importing all names from namespace */ val ImportAllWildcard = "*" def fullNameString(packageName: String, name: String): String = if (packageName.isNullOrEmpty) name else s"$packageName.$name" From de8d3cc849997f5fe60af0d4348a6c4c1742067b Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Tue, 2 Apr 2024 22:42:45 +0300 Subject: [PATCH 09/65] unused PassConfig.withConstantPropagation removed --- data/shared/src/main/scala/sigma/ast/methods.scala | 2 +- .../main/scala/sigma/serialization/ErgoTreeSerializer.scala | 4 ++-- .../src/main/scala/sigmastate/interpreter/Interpreter.scala | 2 +- .../sigma/serialization/ConstantSerializerSpecification.scala | 2 +- .../sigma/serialization/DataSerializerSpecification.scala | 1 - sc/shared/src/main/scala/scalan/Library.scala | 2 +- sc/shared/src/main/scala/scalan/staged/Transforming.scala | 3 --- sc/shared/src/main/scala/special/collection/CollsUnit.scala | 2 -- 8 files changed, 6 insertions(+), 12 deletions(-) diff --git a/data/shared/src/main/scala/sigma/ast/methods.scala b/data/shared/src/main/scala/sigma/ast/methods.scala index 2cbc2fda8c..73d9c4b7b8 100644 --- a/data/shared/src/main/scala/sigma/ast/methods.scala +++ b/data/shared/src/main/scala/sigma/ast/methods.scala @@ -234,7 +234,7 @@ object SNumericTypeMethods extends MethodsContainer { | Each boolean corresponds to one bit. """.stripMargin) - protected override def getMethods: Seq[SMethod] = Array( + protected override def getMethods(): Seq[SMethod] = Array( ToByteMethod, // see Downcast ToShortMethod, // see Downcast ToIntMethod, // see Downcast diff --git a/data/shared/src/main/scala/sigma/serialization/ErgoTreeSerializer.scala b/data/shared/src/main/scala/sigma/serialization/ErgoTreeSerializer.scala index 91765f764b..43e41f91ff 100644 --- a/data/shared/src/main/scala/sigma/serialization/ErgoTreeSerializer.scala +++ b/data/shared/src/main/scala/sigma/serialization/ErgoTreeSerializer.scala @@ -1,13 +1,13 @@ package sigma.serialization import org.ergoplatform.validation.ValidationRules.{CheckDeserializedScriptIsSigmaProp, CheckHeaderSizeBit} -import sigma.ast.{Constant, DeserializationSigmaBuilder, ErgoTree, SType, SubstConstants, UnparsedErgoTree} +import sigma.ast.{Constant, DeserializationSigmaBuilder, ErgoTree, SType, UnparsedErgoTree} import sigma.ast.syntax.ValueOps import sigma.ast.ErgoTree.{EmptyConstants, HeaderType} import sigma.util.safeNewArray import debox.cfor import sigma.VersionContext -import sigma.validation.{SigmaValidationSettings, ValidationException} +import sigma.validation.ValidationException import sigma.validation.ValidationRules.CheckPositionLimit /** diff --git a/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala b/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala index 523b2a7f35..9a1ab11f0e 100644 --- a/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala +++ b/interpreter/shared/src/main/scala/sigmastate/interpreter/Interpreter.scala @@ -23,7 +23,7 @@ import sigmastate.interpreter.CErgoTreeEvaluator.fixedCostOp import sigmastate.interpreter.Interpreter._ import sigma.ast.syntax.ValueOps import sigma.eval.{EvalSettings, SigmaDsl} -import sigma.exceptions.{CostLimitException, InterpreterException} +import sigma.exceptions.InterpreterException import sigma.interpreter.ProverResult import sigma.util.CollectionUtil import sigmastate.utils.Helpers._ diff --git a/interpreter/shared/src/test/scala/sigma/serialization/ConstantSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/ConstantSerializerSpecification.scala index 7bc73643f2..43e9cf9e5d 100644 --- a/interpreter/shared/src/test/scala/sigma/serialization/ConstantSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/ConstantSerializerSpecification.scala @@ -61,7 +61,7 @@ class ConstantSerializerSpecification extends TableSerializationSpecification { } property("Constant serialization round trip") { - forAll { x: Unit => roundTripTest(UnitConstant()) } + forAll { _: Unit => roundTripTest(UnitConstant()) } forAll { x: Byte => roundTripTest(Constant[SByte.type](x, SByte)) } forAll { x: Boolean => roundTripTest(BooleanConstant.fromBoolean(x)) } forAll { x: Long => roundTripTest(Constant[SLong.type](x, SLong)) } diff --git a/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala index ecb2d2ef70..7cd9967e54 100644 --- a/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala @@ -5,7 +5,6 @@ import org.ergoplatform.ErgoBox import org.scalacheck.Arbitrary._ import sigma.data.{DataValueComparer, RType, SigmaBoolean, TupleColl} import sigma.ast.SCollection.SByteArray -import sigmastate._ import sigmastate.eval._ import sigma.{AvlTree, Colls, Evaluation} import sigma.ast.SType.AnyOps diff --git a/sc/shared/src/main/scala/scalan/Library.scala b/sc/shared/src/main/scala/scalan/Library.scala index ee1ff80ad3..43f20813f0 100644 --- a/sc/shared/src/main/scala/scalan/Library.scala +++ b/sc/shared/src/main/scala/scalan/Library.scala @@ -107,7 +107,7 @@ trait Library extends Scalan override def invokeUnlifted(e: Elem[_], mc: MethodCall, dataEnv: DataEnv): Any = e match { case _: CollElem[_,_] => mc match { - case CollMethods.map(xs, f) => + case CollMethods.map(_, f) => val newMC = mc.copy(args = mc.args :+ f.elem.eRange)(mc.resultType, mc.isAdapterCall) super.invokeUnlifted(e, newMC, dataEnv) case _ => diff --git a/sc/shared/src/main/scala/scalan/staged/Transforming.scala b/sc/shared/src/main/scala/scalan/staged/Transforming.scala index cd1fac9fd0..a64b998ff6 100644 --- a/sc/shared/src/main/scala/scalan/staged/Transforming.scala +++ b/sc/shared/src/main/scala/scalan/staged/Transforming.scala @@ -47,9 +47,6 @@ trait Transforming { self: Scalan => constantPropagation: Boolean = true, /** Used in SlicingPass */ shouldSlice: Boolean = false) - { - def withConstantPropagation(value: Boolean) = this.copy(constantPropagation = value) - } /** Default pass to be used when IR is used without special compiler configuration. */ class DefaultPass(val name: String, override val config: PassConfig = PassConfig()) extends Pass diff --git a/sc/shared/src/main/scala/special/collection/CollsUnit.scala b/sc/shared/src/main/scala/special/collection/CollsUnit.scala index 19ae1f5e48..90f0dca99e 100644 --- a/sc/shared/src/main/scala/special/collection/CollsUnit.scala +++ b/sc/shared/src/main/scala/special/collection/CollsUnit.scala @@ -34,7 +34,5 @@ package sigma { 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]]; }; - trait CollCompanion; - trait CollBuilderCompanion } } \ No newline at end of file From 11c6fe94e3e3938449fcee3a4a111e822fe3ae09 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Tue, 2 Apr 2024 22:44:44 +0300 Subject: [PATCH 10/65] CoreByteReader scaladoc cleared --- .../src/main/scala/sigma/serialization/CoreByteReader.scala | 4 ---- 1 file changed, 4 deletions(-) diff --git a/core/shared/src/main/scala/sigma/serialization/CoreByteReader.scala b/core/shared/src/main/scala/sigma/serialization/CoreByteReader.scala index 34ed74ac6a..e238829b6c 100644 --- a/core/shared/src/main/scala/sigma/serialization/CoreByteReader.scala +++ b/core/shared/src/main/scala/sigma/serialization/CoreByteReader.scala @@ -10,10 +10,6 @@ import sigma.validation.ValidationRules.CheckPositionLimit * methods. * * @param r the underlying reader this reader reads from - * @param constantStore the store of constants which is used to resolve - * [[sigma.ast.ConstantPlaceholder]] - * @param resolvePlaceholdersToConstants if true then resolved constants will be - * substituted in the tree instead of the placeholder. * @param maxTreeDepth limit on the tree depth (recursive invocations) * of the deserializer */ From e8978e3c63f5c69d6e719354552cfaa640471a9b Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Wed, 3 Apr 2024 00:04:22 +0300 Subject: [PATCH 11/65] unused LambdaOps.{>>,<<} --- sc/shared/src/main/scala/scalan/primitives/Functions.scala | 6 ------ 1 file changed, 6 deletions(-) diff --git a/sc/shared/src/main/scala/scalan/primitives/Functions.scala b/sc/shared/src/main/scala/scalan/primitives/Functions.scala index 31a6ca8d81..9026461777 100644 --- a/sc/shared/src/main/scala/scalan/primitives/Functions.scala +++ b/sc/shared/src/main/scala/scalan/primitives/Functions.scala @@ -16,12 +16,6 @@ trait Functions extends Base with ProgramGraphs { self: Scalan => /** Apply given function symbol to the given argument symbol. * @return symbol representing result of function application */ final def apply(x: Ref[A]): Ref[B] = mkApply(f, x) - - /** Build new function which applies `f` and then `g`*/ - final def >>[C](g: Ref[B => C]): Ref[A => C] = compose(g, f) - - /** Build new function which applies `g` and then `f`*/ - final def <<[C](g: Ref[C => A]): Ref[C => B] = compose(f, g) } /** Global lambda equality mode used by default. It is used in `fun` and `fun2` lambda builders. From 4771208b126d8df6b7b75c31a698cc5dc0efdffc Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 4 Apr 2024 12:24:43 +0100 Subject: [PATCH 12/65] v5.0.14-RC: ScalaDoc for Extensions --- core/shared/src/main/scala/sigma/Extensions.scala | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/core/shared/src/main/scala/sigma/Extensions.scala b/core/shared/src/main/scala/sigma/Extensions.scala index 865d488803..81976a3c12 100644 --- a/core/shared/src/main/scala/sigma/Extensions.scala +++ b/core/shared/src/main/scala/sigma/Extensions.scala @@ -5,6 +5,9 @@ import scorex.util.encode.Base16 import scorex.util.{ModifierId, bytesToId} import sigma.data.RType +/** Declaration of extension methods introduced in `sigma-core` module. + * See `implicit class ...` wrappers below. + */ object Extensions { /** Extension methods for `Array[Byte]` not available for generic `Array[T]`. */ implicit class CoreArrayByteOps(val arr: Array[Byte]) extends AnyVal { @@ -12,6 +15,9 @@ object Extensions { @inline def toHex: String = Base16.encode(arr) } + /** Extension methods for `Array[T]` where implicit descriptor `RType[T]` is also + * required. + */ implicit class ArrayOps[T: RType](arr: Array[T]) { /** Wraps array into Coll instance. The source array in not cloned. */ @inline def toColl: Coll[T] = Colls.fromArray(arr) From fcb72297cdae62ab27ee9c5bb4ad3129a304062c Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 4 Apr 2024 12:31:42 +0100 Subject: [PATCH 13/65] v5.0.14-RC: rollback potentially breaking changes --- core/shared/src/main/scala/sigma/Evaluation.scala | 3 +-- core/shared/src/main/scala/sigma/data/package.scala | 1 + core/shared/src/main/scala/sigma/package.scala | 7 +++++-- data/shared/src/main/scala/sigma/ast/syntax.scala | 2 -- .../shared/src/test/scala/sigmastate/lang/LangTests.scala | 1 - .../main/scala/org/ergoplatform/dsl/ContractSyntax.scala | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/core/shared/src/main/scala/sigma/Evaluation.scala b/core/shared/src/main/scala/sigma/Evaluation.scala index 893bdfb9f8..d86b7c1650 100644 --- a/core/shared/src/main/scala/sigma/Evaluation.scala +++ b/core/shared/src/main/scala/sigma/Evaluation.scala @@ -76,8 +76,7 @@ object Evaluation { case HeaderRType => SHeader case PreHeaderRType => SPreHeader case SigmaPropRType => SSigmaProp - // TODO remove commented code below after full sync test - // case SigmaBooleanRType => SSigmaProp // this is not used in consensus code + case SigmaBooleanRType => SSigmaProp // TODO remove: this is not used in consensus code case tup: TupleType => STuple(tup.items.map(t => rtypeToSType(t))) case at: ArrayType[_] => SCollection(rtypeToSType(at.tA)) case ct: CollType[_] => SCollection(rtypeToSType(ct.tItem)) diff --git a/core/shared/src/main/scala/sigma/data/package.scala b/core/shared/src/main/scala/sigma/data/package.scala index a0fb219af8..c5a35f7b5f 100644 --- a/core/shared/src/main/scala/sigma/data/package.scala +++ b/core/shared/src/main/scala/sigma/data/package.scala @@ -16,6 +16,7 @@ package object data { val BigIntClassTag = classTag[BigInt] val GroupElementClassTag = classTag[GroupElement] val SigmaPropClassTag = classTag[SigmaProp] + val SigmaBooleanClassTag = classTag[SigmaBoolean] val AvlTreeClassTag = classTag[AvlTree] val BoxClassTag = classTag[Box] val ContextClassTag = classTag[Context] diff --git a/core/shared/src/main/scala/sigma/package.scala b/core/shared/src/main/scala/sigma/package.scala index 67560b462c..89b883f52d 100644 --- a/core/shared/src/main/scala/sigma/package.scala +++ b/core/shared/src/main/scala/sigma/package.scala @@ -25,9 +25,12 @@ package object sigma { implicit val StringType : RType[String] = GeneralType(StringClassTag) - implicit val BigIntRType: RType[BigInt] = GeneralType(BigIntClassTag) + implicit val BigIntRType : RType[BigInt] = GeneralType(BigIntClassTag) implicit val GroupElementRType: RType[GroupElement] = GeneralType(GroupElementClassTag) - implicit val SigmaPropRType: RType[SigmaProp] = GeneralType(SigmaPropClassTag) + implicit val SigmaPropRType : RType[SigmaProp] = GeneralType(SigmaPropClassTag) + implicit val SigmaBooleanRType: RType[SigmaBoolean] = GeneralType(SigmaBooleanClassTag) + + implicit val AvlTreeRType: RType[AvlTree] = GeneralType(AvlTreeClassTag) implicit val BoxRType: RType[Box] = GeneralType(BoxClassTag) diff --git a/data/shared/src/main/scala/sigma/ast/syntax.scala b/data/shared/src/main/scala/sigma/ast/syntax.scala index d75c71a779..5a257481cb 100644 --- a/data/shared/src/main/scala/sigma/ast/syntax.scala +++ b/data/shared/src/main/scala/sigma/ast/syntax.scala @@ -118,8 +118,6 @@ object syntax { @nowarn private def rtypeToClassTag = ??? /** RType descriptors for predefined types used in AOTC-based interpreter. */ - implicit val SigmaBooleanRType: RType[SigmaBoolean] = RType.fromClassTag(classTag[SigmaBoolean]) - implicit val ErgoBoxRType: RType[ErgoBox] = RType.fromClassTag(classTag[ErgoBox]) implicit val ErgoBoxCandidateRType: RType[ErgoBoxCandidate] = RType.fromClassTag(classTag[ErgoBoxCandidate]) diff --git a/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala b/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala index c04f35ef71..498c3934bf 100644 --- a/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala +++ b/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala @@ -8,7 +8,6 @@ import sigma.ast._ import sigma.crypto.CryptoConstants import sigma.data.{CAnyValue, CSigmaDslBuilder, ProveDHTuple, ProveDlog, SigmaBoolean} import sigma.util.Extensions.BigIntegerOps -import sigmastate.eval._ import sigmastate.helpers.NegativeTesting import sigmastate.interpreter.Interpreter.ScriptEnv import sigma.ast.{Ident, MethodCallLike} diff --git a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala index d4accabf3e..11cbaff739 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSyntax.scala @@ -60,7 +60,7 @@ trait ContractSyntax { contract: SigmaContract => case _: Box => BoxRType case _: AvlTreeData => syntax.AvlTreeDataRType // TODO remove this RType case _: AvlTree => AvlTreeRType - case _: SigmaBoolean => syntax.SigmaBooleanRType // TODO remove this RType + case _: SigmaBoolean => SigmaBooleanRType // TODO remove this RType case _: SigmaProp => SigmaPropRType case _: Context => ContextRType case _ => From 58997010050f805ec53a9e7ead52e8b9938b9665 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 4 Apr 2024 12:33:03 +0100 Subject: [PATCH 14/65] v5.0.14-RC: Added ScalaDocs for CoreXXX classes --- .../src/main/scala/sigma/data/SigmaPropCodes.scala | 2 +- .../scala/sigma/serialization/CoreByteWriter.scala | 3 +++ .../scala/sigma/serialization/CoreSerializer.scala | 12 +++++++++--- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/core/shared/src/main/scala/sigma/data/SigmaPropCodes.scala b/core/shared/src/main/scala/sigma/data/SigmaPropCodes.scala index 17257c9ce5..fafd24ffdd 100644 --- a/core/shared/src/main/scala/sigma/data/SigmaPropCodes.scala +++ b/core/shared/src/main/scala/sigma/data/SigmaPropCodes.scala @@ -3,7 +3,7 @@ package sigma.data import sigma.ast.TypeCodes.LastConstantCode import supertagged.TaggedType -/** Encoding of sigma proposition nodes. +/** Opcodes of sigma proposition nodes. * * @see SigmaBoolean.opCode */ diff --git a/core/shared/src/main/scala/sigma/serialization/CoreByteWriter.scala b/core/shared/src/main/scala/sigma/serialization/CoreByteWriter.scala index d6cc9a8d8e..aa4255449c 100644 --- a/core/shared/src/main/scala/sigma/serialization/CoreByteWriter.scala +++ b/core/shared/src/main/scala/sigma/serialization/CoreByteWriter.scala @@ -5,6 +5,9 @@ import scorex.util.serialization.{VLQByteBufferWriter, Writer} import sigma.ast.SType import sigma.serialization.CoreByteWriter.{Bits, DataInfo, U, Vlq, ZigZag} +/** Implementation of [[Writer]] provided by `sigma-core` module. + * @param w destination [[Writer]] to which all the call got delegated. + */ class CoreByteWriter(val w: Writer) extends Writer { type CH = w.CH diff --git a/core/shared/src/main/scala/sigma/serialization/CoreSerializer.scala b/core/shared/src/main/scala/sigma/serialization/CoreSerializer.scala index aec82eb9df..938d3f22c1 100644 --- a/core/shared/src/main/scala/sigma/serialization/CoreSerializer.scala +++ b/core/shared/src/main/scala/sigma/serialization/CoreSerializer.scala @@ -6,25 +6,31 @@ import sigma.data.SigmaConstants import java.nio.ByteBuffer +/** Implementation of [[Serializer]] provided by `sigma-core` module. */ abstract class CoreSerializer[TFamily, T <: TFamily] extends Serializer[TFamily, T, CoreByteReader, CoreByteWriter] { - def error(msg: String) = throw new SerializerException(msg, None) + def error(msg: String) = throw SerializerException(msg, None) + /** Serializes the given 'obj' to a new array of bytes using this serializer. */ final def toBytes(obj: T): Array[Byte] = { val w = CoreSerializer.startWriter() serialize(obj, w) w.toBytes } + /** Deserializes `bytes` to an object of this [[TFamily]] using this serializer. + * The actual class of the returned object is expected to be descendant of [[TFamily]]. + */ final def fromBytes(bytes: Array[Byte]): TFamily = { parse(CoreSerializer.startReader(bytes)) } } object CoreSerializer { - type Position = Int - + /** Max length of Box.propositionBytes collection */ val MaxPropositionSize: Int = SigmaConstants.MaxPropositionBytes.value + + /** Max tree depth should not be greater then provided value */ val MaxTreeDepth: Int = SigmaConstants.MaxTreeDepth.value /** Helper function to be use in serializers. From de8c36299611d5b181149248cd595dd664ed8864 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 4 Apr 2024 12:35:01 +0100 Subject: [PATCH 15/65] v5.0.14-RC: CFunc removed --- .../main/scala/sigmastate/eval/CContext.scala | 56 ------------------- 1 file changed, 56 deletions(-) diff --git a/interpreter/shared/src/main/scala/sigmastate/eval/CContext.scala b/interpreter/shared/src/main/scala/sigmastate/eval/CContext.scala index 418f9e8959..2b076403ad 100644 --- a/interpreter/shared/src/main/scala/sigmastate/eval/CContext.scala +++ b/interpreter/shared/src/main/scala/sigmastate/eval/CContext.scala @@ -9,62 +9,6 @@ import sigma.exceptions.InvalidType import scala.annotation.unused import scala.reflect.ClassTag - -/** This class represents context variable and register value of a functional type A => B. - * When variable or register is accessed using `getVar[A => B](id).get` or - * `box.getReg[A => B].get an instance of this class is returned. - * - * It internally transforms a given `tree` into executable function. - * This it similar to what happens during validation of propositions in the input boxes: - * - size check of underlying ErgoTree against limits - * - construction of `calcF` and `costF` graphs, both are stored together with resulting function. - * - check the types of `calcF` graph to be compatible with expected types A and B - * If anything goes wrong, this operation fails and if it is used in the script, the script also fails. - * - * When f is obtained as `val f = getVar[Int => Int](id).get` then any application `f(x)` involves size estimation - * using underlying `costF(x)`. - * */ -//case class CFunc[A,B](context: sigmastate.interpreter.Context, tree: SValue) -// (implicit tDom: RType[A], tRange: RType[B], IR: IRContext) extends (A => B) { -// import CFunc._ -// -// private val compiled = { -// import IR._ -// val IR.Pair(calcF, costF) = IR.doCosting(emptyEnv, tree) -// -// val eDom = asElem[Any](IR.rtypeToElem(tDom)) -// val eRange = asElem[Any](IR.rtypeToElem(tRange)) -// -// IR.verifyCalcFunc[Any => Any](asRep[Context => (Any => Any)](calcF), IR.funcElement(eDom, eRange)) -//// IR.verifyCostFunc(costF).getOrThrow -//// IR.verifyIsProven(calcF).getOrThrow -// -// // check cost -//// val costingCtx = context.toSigmaContext(IR, isCost = true) -//// val costFun = IR.compile[SInt.type](IR.getDataEnv, costF) -//// val IntConstant(estimatedCost) = costFun(costingCtx) -//// if (estimatedCost > maxCost) { -//// throw new Error(s"Estimated execution cost $estimatedCost exceeds the limit $maxCost in $tree") -//// } -// // check calc -// val calcCtx = context.toSigmaContext(IR, isCost = false) -// val valueFun = IR.compile[SFunc](IR.getDataEnv, asRep[Context => SFunc#WrappedType](calcF)) -// val res = valueFun(calcCtx) match { -// case Constant(f, fTpe: SFunc) => f -// case v => v -// } -// res.asInstanceOf[A => B] -// } -// -// override def apply(x: A): B = compiled(x) -//} -object CFunc { - /** The cost of creating resulting function but not its execution. - * Thus it is expected to be small. It can be increased if useful cases are found - * such that `tree` should contains heavy operations. */ - val maxCost = 1000 -} - /** A default implementation of [[Context]] interface. * @see [[Context]] for detailed descriptions */ From 6196e90fa66b779ae6a53acaea892cb2412854dd Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 4 Apr 2024 12:50:14 +0100 Subject: [PATCH 16/65] v5.0.14-RC: ScalaDoc for ReflectionData is improved --- .../main/scala/sigma/reflection/ReflectionData.scala | 10 ++++++++-- .../src/main/scala/sigma/SigmaDataReflection.scala | 4 ++++ .../main/scala/sigmastate/InterpreterReflection.scala | 4 ++++ .../src/main/scala/scalan/GraphIRReflection.scala | 4 ++++ 4 files changed, 20 insertions(+), 2 deletions(-) diff --git a/core/shared/src/main/scala/sigma/reflection/ReflectionData.scala b/core/shared/src/main/scala/sigma/reflection/ReflectionData.scala index 2aac1a5670..028e68bf72 100644 --- a/core/shared/src/main/scala/sigma/reflection/ReflectionData.scala +++ b/core/shared/src/main/scala/sigma/reflection/ReflectionData.scala @@ -9,9 +9,15 @@ 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. + * Such metadata is only used on JS platform to support reflection-like interfaces of + * RClass, RMethod, RConstructor. These interfaces implemented on JVM using Java + * reflection. + * + * For each class that needs reflection metadata, we register a class entry using + * `registerClassEntry` method with the necessary information such as constructors and + * methods. * Only information that is needed at runtime is registered. + * @see mkConstructor, mkMethod */ object ReflectionData { /** Descriptors of classes. */ diff --git a/data/shared/src/main/scala/sigma/SigmaDataReflection.scala b/data/shared/src/main/scala/sigma/SigmaDataReflection.scala index 31703b0856..48939b1460 100644 --- a/data/shared/src/main/scala/sigma/SigmaDataReflection.scala +++ b/data/shared/src/main/scala/sigma/SigmaDataReflection.scala @@ -11,6 +11,10 @@ import sigma.reflection.{ReflectionData, mkConstructor, mkMethod} import sigma.serialization.ValueCodes.OpCode /** Reflection metadata for `interpreter` module. + * Such metadata is only used on JS platform to support reflection-like interfaces of + * RClass, RMethod, RConstructor. These interfaces implemented on JVM using Java + * reflection. + * * 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. diff --git a/interpreter/shared/src/main/scala/sigmastate/InterpreterReflection.scala b/interpreter/shared/src/main/scala/sigmastate/InterpreterReflection.scala index 8b18e20459..9a06322166 100644 --- a/interpreter/shared/src/main/scala/sigmastate/InterpreterReflection.scala +++ b/interpreter/shared/src/main/scala/sigmastate/InterpreterReflection.scala @@ -8,6 +8,10 @@ import sigmastate.crypto.GF2_192_Poly import sigmastate.crypto.VerifierMessage.Challenge /** Reflection metadata for `interpreter` module. + * Such metadata is only used on JS platform to support reflection-like interfaces of + * RClass, RMethod, RConstructor. These interfaces implemented on JVM using Java + * reflection. + * * 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. diff --git a/sc/shared/src/main/scala/scalan/GraphIRReflection.scala b/sc/shared/src/main/scala/scalan/GraphIRReflection.scala index ee29924fb7..0eaba9d8a3 100644 --- a/sc/shared/src/main/scala/scalan/GraphIRReflection.scala +++ b/sc/shared/src/main/scala/scalan/GraphIRReflection.scala @@ -11,6 +11,10 @@ import special.wrappers.{OptionWrapSpec, RTypeWrapSpec} import wrappers.scalan.WRTypes /** Registrations of reflection metadata for graph-ir module (see README.md). + * Such metadata is only used on JS platform to support reflection-like interfaces of + * RClass, RMethod, RConstructor. These interfaces implemented on JVM using Java + * reflection. + * * 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. From 2b1e49a6fda8327fdcd7ddbd0a933ea89c20573c Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Thu, 4 Apr 2024 19:26:44 +0300 Subject: [PATCH 17/65] RuntimeIRContext removed --- .../scala/sigmastate/eval/IRContext.scala | 8 ++--- .../sigmastate/eval/EvaluationTest.scala | 18 ---------- .../sigmastate/eval/MeasureIRContext.scala | 36 ------------------- 3 files changed, 3 insertions(+), 59 deletions(-) delete mode 100644 sc/shared/src/test/scala/sigmastate/eval/MeasureIRContext.scala diff --git a/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala b/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala index b84098f2e7..a7b6df3f58 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala @@ -10,7 +10,9 @@ import scala.util.Try * methods. * It is not used in v5.0 interpreter and thus not part of consensus. * - * @see RuntimeIRContext, CompiletimeIRContext + * Used in ErgoScript compiler only. + * + * @see CompiletimeIRContext */ trait IRContext extends TreeBuilding with GraphBuilding { import SigmaProp._ @@ -55,10 +57,6 @@ trait IRContext extends TreeBuilding with GraphBuilding { } } -/** IR context to be used by blockchain nodes to validate transactions. */ -class RuntimeIRContext extends IRContext { -} - /** IR context to be used by script development tools to compile ErgoScript into ErgoTree bytecode. */ class CompiletimeIRContext extends IRContext { } diff --git a/sc/shared/src/test/scala/sigmastate/eval/EvaluationTest.scala b/sc/shared/src/test/scala/sigmastate/eval/EvaluationTest.scala index 5fcbd0f220..f9a7edf0cb 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/EvaluationTest.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/EvaluationTest.scala @@ -81,24 +81,6 @@ class EvaluationTest extends BaseCtxTests | f(SELF) || g(SELF.R5[Coll[Int]].get) | }""".stripMargin, ctx, true) } - - test("Measure IRContext creation speed") { - var ctx: RuntimeIRContext = new RuntimeIRContext - measure(100, okShowIterTime = printDebugInfo, okShowTotalTime = printDebugInfo) { i => - ctx = new RuntimeIRContext - } - printDebug(s"Def count: ${ctx.defCount}") - /* - Iter 0: 4 ms - ... - Iter 96: 2 ms - Iter 97: 1 ms - Iter 98: 2 ms - Iter 99: 2 ms - Total time: 244 ms - Def count: 20 - */ - } test("SubstConst") { def script(pk: ProveDlog): SigmaPropValue = diff --git a/sc/shared/src/test/scala/sigmastate/eval/MeasureIRContext.scala b/sc/shared/src/test/scala/sigmastate/eval/MeasureIRContext.scala deleted file mode 100644 index 9f88588cc9..0000000000 --- a/sc/shared/src/test/scala/sigmastate/eval/MeasureIRContext.scala +++ /dev/null @@ -1,36 +0,0 @@ -package sigmastate.eval - -import scalan.{BaseCtxTests, Benchmark} -import sigma.util.BenchmarkUtil.measure - -object MeasureIRContext extends App { - var ctx: RuntimeIRContext = null - measure(1, false) { i => - ctx = new RuntimeIRContext - } - measure(10000, false) { i => - ctx = new RuntimeIRContext - } - print(s"Def count: ${ctx.defCount}") - /* - Total time: 2485 ms - Total time: 2714 ms - Def count: 20 - */ -} - -class SigmaLibraryTests extends BaseCtxTests { - - test("Benchmark SigmaLibrary creation time") { - new Benchmark(new RuntimeIRContext).run() - } -} - -object MeasureSigmaLibraryCreate extends App { - new Benchmark(new RuntimeIRContext).run() - /* - Total time: 12932 ms - Def count: 20, total: 15774 msec - */ -} - From dcec230aea345c8bd10cf23c61d3b5654b4b97e4 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Thu, 4 Apr 2024 19:39:02 +0300 Subject: [PATCH 18/65] xor_eval rollback --- data/shared/src/main/scala/sigma/SigmaDataReflection.scala | 3 ++- data/shared/src/main/scala/sigma/ast/methods.scala | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/data/shared/src/main/scala/sigma/SigmaDataReflection.scala b/data/shared/src/main/scala/sigma/SigmaDataReflection.scala index 9efb3fbf8b..48939b1460 100644 --- a/data/shared/src/main/scala/sigma/SigmaDataReflection.scala +++ b/data/shared/src/main/scala/sigma/SigmaDataReflection.scala @@ -318,7 +318,8 @@ object SigmaDataReflection { registerClassEntry(clazz, methods = Map( mkMethod(clazz, "xor_eval", Array[Class[_]](classOf[MethodCall], classOf[SigmaDslBuilder], classOf[Coll[_]], classOf[Coll[_]], classOf[ErgoTreeEvaluator])) { (obj, args) => - obj.asInstanceOf[SGlobalMethods.type].xor_eval( + obj.asInstanceOf[SGlobalMethods.type].xor_eval(args(0).asInstanceOf[MethodCall], + args(1).asInstanceOf[SigmaDslBuilder], args(2).asInstanceOf[Coll[Byte]], args(3).asInstanceOf[Coll[Byte]])(args(4).asInstanceOf[ErgoTreeEvaluator]) } diff --git a/data/shared/src/main/scala/sigma/ast/methods.scala b/data/shared/src/main/scala/sigma/ast/methods.scala index 73d9c4b7b8..3b7368c542 100644 --- a/data/shared/src/main/scala/sigma/ast/methods.scala +++ b/data/shared/src/main/scala/sigma/ast/methods.scala @@ -1494,7 +1494,7 @@ case object SGlobalMethods extends MonoTypeMethods { * Called via reflection based on naming convention. * @see SMethod.evalMethod, Xor.eval, Xor.xorWithCosting */ - def xor_eval(ls: Coll[Byte], rs: Coll[Byte]) + def xor_eval(mc: MethodCall, G: SigmaDslBuilder, ls: Coll[Byte], rs: Coll[Byte]) (implicit E: ErgoTreeEvaluator): Coll[Byte] = { Xor.xorWithCosting(ls, rs) } From 810ca16eb50b7a33d53e3e20baff9d44ce24f664 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Fri, 5 Apr 2024 12:45:00 +0300 Subject: [PATCH 19/65] IRContext cleared --- .../src/main/scala/sigma/ast/SType.scala | 3 +- .../scala/sigmastate/eval/IRContext.scala | 42 +------------------ .../sigmastate/eval/ErgoScriptTestkit.scala | 27 +++++++++++- .../helpers/CompilerTestingCommons.scala | 3 +- .../utxo/BasicOpsSpecification.scala | 4 +- 5 files changed, 32 insertions(+), 47 deletions(-) diff --git a/core/shared/src/main/scala/sigma/ast/SType.scala b/core/shared/src/main/scala/sigma/ast/SType.scala index e9ea0d43f0..f75cbc9e8b 100644 --- a/core/shared/src/main/scala/sigma/ast/SType.scala +++ b/core/shared/src/main/scala/sigma/ast/SType.scala @@ -94,7 +94,6 @@ object SType { val paramOV = STypeParam(tOV) val paramIVSeq: Seq[STypeParam] = Array(paramIV) - val IndexedSeqOfT1: IndexedSeq[SType] = Array(SType.tT) val IndexedSeqOfT2: IndexedSeq[SType] = Array(SType.tT, SType.tT) /** Immutable empty array, can be used to avoid repeated allocations. */ @@ -146,7 +145,7 @@ object SType { * 2) `isValueOfType == true` for each tree leaf * 3) `isValueOfType == true` for each sub-expression * - * @param value value to check type + * @param x value to check type * @param tpe type descriptor to check value against * @return true if the given `value` is of type tpe` */ diff --git a/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala b/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala index a7b6df3f58..597711d458 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala @@ -1,10 +1,6 @@ package sigmastate.eval import sigma.ast.TransformingSigmaBuilder -import sigma.data.CSigmaDslBuilder - -import java.util.concurrent.locks.ReentrantLock -import scala.util.Try /** Main interface of graph IR context which contain both GraphBuilding and TreeBuilding * methods. @@ -15,49 +11,15 @@ import scala.util.Try * @see CompiletimeIRContext */ trait IRContext extends TreeBuilding with GraphBuilding { - import SigmaProp._ - - private val SigmaM = SigmaPropMethods - override val builder = TransformingSigmaBuilder - /** Can be used to synchronize access to this IR object from multiple threads. */ - val lock = new ReentrantLock() - /** Pass configuration which is used to turn-off constant propagation. + * USED IN TESTS ONLY. * @see `beginPass(noCostPropagationPass)` */ lazy val noConstPropagationPass = new DefaultPass( "noCostPropagationPass", Pass.defaultPassConfig.copy(constantPropagation = false)) - - /** The value of Global ErgoTree operation */ - val sigmaDslBuilderValue = CSigmaDslBuilder - - /** Finds SigmaProp.isProven method calls in the given Lambda `f` */ - def findIsProven[T](f: Ref[Context => T]): Option[Sym] = { - val Def(Lambda(lam,_,_,_)) = f - val s = lam.flatSchedule.find(sym => sym.node match { - case SigmaM.isValid(_) => true - case _ => false - }) - s - } - - /** Checks that if SigmaProp.isProven method calls exists in the given Lambda's schedule, - * then it is the last operation. */ - def verifyIsProven[T](f: Ref[Context => T]): Try[Unit] = { - val isProvenOpt = findIsProven(f) - Try { - isProvenOpt match { - case Some(s) => - if (f.getLambda.y != s) !!!(s"Sigma.isProven found in none-root position", s) - case None => - } - } - } } /** IR context to be used by script development tools to compile ErgoScript into ErgoTree bytecode. */ -class CompiletimeIRContext extends IRContext { -} - +class CompiletimeIRContext extends IRContext diff --git a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala index abbed09992..2832ad27e7 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala @@ -21,7 +21,7 @@ import sigmastate.CompilerTestsBase import sigma.{ContractsTestkit, Context => DContext} import scala.annotation.unused -import scala.util.Success +import scala.util.{Success, Try} trait ErgoScriptTestkit extends ContractsTestkit with LangTests with ValidationSpecification with CompilerTestsBase { self: BaseCtxTests => @@ -147,6 +147,31 @@ trait ErgoScriptTestkit extends ContractsTestkit with LangTests res } + private val SigmaM = SigmaProp.SigmaPropMethods + + /** Finds SigmaProp.isProven method calls in the given Lambda `f` */ + private def findIsProven[T](f: Ref[Context => T]): Option[Sym] = { + val Def(Lambda(lam,_,_,_)) = f + val s = lam.flatSchedule.find(sym => sym.node match { + case SigmaM.isValid(_) => true + case _ => false + }) + s + } + + /** Checks that if SigmaProp.isProven method calls exists in the given Lambda's schedule, + * then it is the last operation. */ + private def verifyIsProven[T](f: Ref[Context => T]): Try[Unit] = { + val isProvenOpt = findIsProven(f) + Try { + isProvenOpt match { + case Some(s) => + if (f.getLambda.y != s) !!!(s"Sigma.isProven found in none-root position", s) + case None => + } + } + } + def doReduce(): Unit = { val res = doCosting verifyIsProven(res.compiledGraph) shouldBe Success(()) diff --git a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala index 332ee902a2..6c3708b782 100644 --- a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala +++ b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala @@ -29,8 +29,7 @@ trait CompilerTestingCommons extends TestingCommons with TestUtils with TestContexts with ValidationSpecification with CompilerTestsBase { - class TestingIRContext extends TestContext with IRContext { - } + class TestingIRContext extends TestContext with IRContext case class CompiledFunc[A,B] (script: String, bindings: Seq[VarBinding], expr: SValue, compiledTree: SValue, func: A => (B, CostDetails)) diff --git a/sc/shared/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala index 346ad69e1a..79701d6e07 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/BasicOpsSpecification.scala @@ -5,7 +5,7 @@ import org.ergoplatform._ import sigma.Extensions.ArrayOps import sigma.ast.SCollection.SByteArray import sigma.ast.SType.AnyOps -import sigma.data.{AvlTreeData, CAnyValue} +import sigma.data.{AvlTreeData, CAnyValue, CSigmaDslBuilder} import sigma.util.StringUtil._ import sigma.ast._ import sigma.ast.syntax._ @@ -339,7 +339,7 @@ class BasicOpsSpecification extends CompilerTestingCommons }) val dataVar = (lastExtVar + 1).toByte - val Colls = IR.sigmaDslBuilderValue.Colls + val Colls = CSigmaDslBuilder.Colls implicit val eAny = sigma.AnyType val data = Colls.fromItems((Array[Byte](1,2,3).toColl, 10L)) val env1 = env + ("dataVar" -> CAnyValue(dataVar)) From bb6224ca8408baf61130d6144e49adfcb10a4da7 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Tue, 9 Apr 2024 14:25:48 +0300 Subject: [PATCH 20/65] removing unused code from ContractsTestkit, ErgoScriptTestkit, and MethodCalls --- .../scala/sigmastate/eval/BasicOpsTests.scala | 7 ++-- .../special/sigma/ContractsTestkit.scala | 35 ++----------------- .../src/main/scala/scalan/MethodCalls.scala | 24 ++----------- .../scala/sigma/SigmaDslStaginTests.scala | 4 +-- .../sigmastate/eval/ErgoScriptTestkit.scala | 12 ++----- 5 files changed, 12 insertions(+), 70 deletions(-) diff --git a/interpreter/shared/src/test/scala/sigmastate/eval/BasicOpsTests.scala b/interpreter/shared/src/test/scala/sigmastate/eval/BasicOpsTests.scala index ba996b0246..e9ba273e17 100644 --- a/interpreter/shared/src/test/scala/sigmastate/eval/BasicOpsTests.scala +++ b/interpreter/shared/src/test/scala/sigmastate/eval/BasicOpsTests.scala @@ -3,16 +3,15 @@ package sigmastate.eval import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers import sigma.crypto.SecP256K1Group -import sigma.data.{CSigmaDslBuilder, TrivialProp} +import sigma.data.{CSigmaDslBuilder => SigmaDsl, TrivialProp} import sigma.util.Extensions.SigmaBooleanOps import java.math.BigInteger -import sigma.{ContractsTestkit, SigmaDslBuilder, SigmaProp} +import sigma.{ContractsTestkit, SigmaProp} import scala.language.implicitConversions class BasicOpsTests extends AnyFunSuite with ContractsTestkit with Matchers { - override val SigmaDsl: SigmaDslBuilder = CSigmaDslBuilder implicit def boolToSigma(b: Boolean): SigmaProp = TrivialProp(b).toSigmaProp @@ -60,7 +59,7 @@ class BasicOpsTests extends AnyFunSuite with ContractsTestkit with Matchers { } test("box.creationInfo._1 is Int") { - val box = newAliceBox(1, 100) + val box = newAliceBox(100) box.creationInfo._1 shouldBe a [Integer] } diff --git a/interpreter/shared/src/test/scala/special/sigma/ContractsTestkit.scala b/interpreter/shared/src/test/scala/special/sigma/ContractsTestkit.scala index 720223ee3a..b04e9c150f 100644 --- a/interpreter/shared/src/test/scala/special/sigma/ContractsTestkit.scala +++ b/interpreter/shared/src/test/scala/special/sigma/ContractsTestkit.scala @@ -8,43 +8,18 @@ import sigmastate.eval._ import sigmastate.helpers.TestingHelpers._ import sigma.data._ -import scala.annotation.nowarn // imports implicit ClassTag - trait ContractsTestkit { - val R0 = 0.toByte; - val R1 = 1.toByte; - val R2 = 2.toByte; - val R3 = 3.toByte; - val R4 = 4.toByte; - val R5 = 5.toByte; - val R6 = 6.toByte; - val R7 = 7.toByte; - val R8 = 8.toByte; - val R9 = 9.toByte; + val Colls = new CollOverArrayBuilder - val SigmaDsl: SigmaDslBuilder = CSigmaDslBuilder - val noRegisters = collection[AnyValue]() - val noBytes = collection[Byte]() val noInputs = Array[Box]() val noOutputs = Array[Box]() val dummyPubkey: Array[Byte] = Array.fill(32)(0: Byte) - val dummyADDigest: Coll[Byte] = Colls.fromArray(Array.fill(33)(0: Byte)) val emptyAvlTree = new CAvlTree(AvlTreeData.dummy) val noHeaders = CSigmaDslBuilder.Colls.emptyColl[Header] val dummyPreHeader: PreHeader = null /** Create collection from array of items */ - def collection[T: RType](items: T*) = Colls.fromArray(items.toArray) - - /** Converts a map of registers to collection of registers. */ - def regs(m: Map[Byte, AnyValue]): Coll[AnyValue] = { - val res = new Array[AnyValue](10) - for ( (id, v) <- m ) { - assert(res(id) == null, s"register $id is defined more then once") - res(id) = v - } - Colls.fromArray(res) - } + def collection[T: RType](items: T*): Coll[T] = Colls.fromArray(items.toArray) /** Converts a map of context vars to collection of context vars. */ def contextVars(m: Map[Byte, AnyValue]): Coll[AnyValue] = { @@ -58,9 +33,7 @@ trait ContractsTestkit { Colls.fromArray(res) } - val AliceId = Array[Byte](1) // 0x0001 - - def newAliceBox(@nowarn id: Byte, value: Long): Box = { + def newAliceBox(value: Long): Box = { val ergoBox = testBox(value, ErgoTree.fromProposition(TrueSigmaProp), creationHeight = 0, additionalTokens = Seq(), additionalRegisters = Map()) @@ -90,8 +63,6 @@ trait ContractsTestkit { implicit class TestContextOps(ctx: CContext) { def withInputs(inputs: Box*) = ctx.copy(inputs = inputs.toArray.toColl) - def withOutputs(outputs: Box*) = ctx.copy(outputs = outputs.toArray.toColl) - def withVariables(vars: Map[Int, AnyValue]) = ctx.copy(vars = contextVars(vars.map { case (k, v) => (k.toByte, v) })) } diff --git a/sc/shared/src/main/scala/scalan/MethodCalls.scala b/sc/shared/src/main/scala/scalan/MethodCalls.scala index af3c3201ef..14212df632 100644 --- a/sc/shared/src/main/scala/scalan/MethodCalls.scala +++ b/sc/shared/src/main/scala/scalan/MethodCalls.scala @@ -101,11 +101,6 @@ trait MethodCalls extends Base { self: Scalan => reifyObject(MethodCall(receiver, method, args, neverInvoke)(asElem[Any](resultElem), isAdapterCall)) } - /** Creates new NewObject node and returns its node ref. */ - def newObjEx[A](args: Any*)(implicit eA: Elem[A]): Ref[A] = { - reifyObject(NewObject[A](eA, args)) - } - @tailrec private def baseCause(e: Throwable): Throwable = e match { case e: ExceptionInInitializerError => baseCause(e.getCause) @@ -120,21 +115,6 @@ trait MethodCalls extends Base { self: Scalan => * point we know that the first RW set didn't triggered any rewrite. */ 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. - * This method returns dynamically constructed instance, which conforms to T. - * Whenever a method of T is called on that instance, the call is intercepted and - * `DelegatedInterceptionHandler.invoke` method is called, then a new MethodCall can - * be constructed (which is befavior by default). - */ - protected def unrefDelegate[T <: AnyRef](x: Ref[T])(implicit ct: ClassTag[T]): T = { - val d = x.node - if (d.isInstanceOf[Const[_]]) - d.asInstanceOf[Const[T]@unchecked].x - else - !!!(s"Cannot do undefDelegate($x -> ${x.node})") - } - /** Generic helper to call the given method on the given receiver node. */ private[scalan] def invokeMethod[A](receiver: Sym, m: RMethod, args: Array[AnyRef], onInvokeSuccess: Any => A, @@ -148,9 +128,9 @@ trait MethodCalls extends Base { self: Scalan => } catch { case e: Exception => onInvokeException(baseCause(e)) } - } - else + } else { onInvokeImpossible + } } /** Method invocation enabler. diff --git a/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala b/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala index 5ac9b80889..91178b2b67 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala @@ -28,8 +28,8 @@ class SigmaDslStaginTests extends BaseCtxTests with ErgoScriptTestkit with BaseL type RContext = cake.Context type RBox = cake.Box type RSigmaProp = cake.SigmaProp - val boxA1 = newAliceBox(1, 100) - val boxA2 = newAliceBox(2, 200) + val boxA1 = newAliceBox(100) + val boxA2 = newAliceBox(200) val ctx: SContext = newContext(10, boxA1, VersionContext.MaxSupportedScriptVersion, VersionContext.MaxSupportedScriptVersion) .withInputs(boxA2) .withVariables(Map(1 -> toAnyValue(30), 2 -> toAnyValue(40))) diff --git a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala index 2832ad27e7..a10a717d2f 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala @@ -54,9 +54,8 @@ trait ErgoScriptTestkit extends ContractsTestkit with LangTests ergoCtx } - - lazy val boxA1 = newAliceBox(1, 100) - lazy val boxA2 = newAliceBox(2, 200) + lazy val boxA1 = newAliceBox(100) + lazy val boxA2 = newAliceBox(200) lazy val n1Sym = liftConst(n1) @@ -208,13 +207,6 @@ trait ErgoScriptTestkit extends ContractsTestkit with LangTests } } - def Case(env: ScriptEnv, name: String, script: String, ctx: ErgoLikeContext, - calc: Ref[Context] => Ref[Any], - tree: SValue, - result: Result) = - EsTestCase(name, env, Code(script), Option(ctx), None, - Option(calc), Option(tree), result) - def reduce(env: ScriptEnv, name: String, script: String, ergoCtx: ErgoLikeContext, expectedResult: Any): Unit = { val tcase = EsTestCase(name, env, Code(script), Some(ergoCtx), expectedResult = Result(expectedResult)) tcase.doReduce() From 9c93753ccc54359b9b1d870bed42b7eb92103fda Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Mon, 15 Apr 2024 22:39:29 +0300 Subject: [PATCH 21/65] removing unused code from SigmaTestingData --- .../special/sigma/SigmaTestingData.scala | 63 +------------------ 1 file changed, 1 insertion(+), 62 deletions(-) diff --git a/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala b/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala index d33f09dd80..f113a484ef 100644 --- a/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala +++ b/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala @@ -30,13 +30,6 @@ trait SigmaTestingData extends TestingCommons with ObjectGenerators { def Coll[T](items: T*)(implicit cT: RType[T]): Coll[T] = CSigmaDslBuilder.Colls.fromItems(items: _*) - /** Generator of random collection with `n` elements. */ - def collOfN[T: RType : Arbitrary](n: Int) - (implicit b: Buildable[T, Array[T]]): Gen[Coll[T]] = { - implicit val g: Gen[T] = Arbitrary.arbitrary[T] - containerOfN[Array, T](n, g).map(Colls.fromArray(_)) - } - val bytesGen: Gen[Array[Byte]] = for { len <- Gen.choose(0, 100) arr <- containerOfN[Array, Byte](len, Arbitrary.arbByte.arbitrary) @@ -54,63 +47,9 @@ trait SigmaTestingData extends TestingCommons with ObjectGenerators { res } - protected def sampleAvlProver = { - val keys = arrayOfN(100, keyCollGen).sample.get - val values = arrayOfN(100, bytesCollGen).sample.get - val (tree, prover) = createAvlTreeAndProver(keys.zip(values): _*) - (keys, values, tree, prover) - } - - protected def sampleAvlTree: AvlTree = { - val (_, _, _, avlProver) = sampleAvlProver - val digest = avlProver.digest.toColl - val tree = SigmaDsl.avlTree(AvlTreeFlags.ReadOnly.serializeToByte, digest, 32, None) - tree - } - val tokenId1: Digest32 = Blake2b256("id1") val tokenId2: Digest32 = Blake2b256("id2") - val header1: Header = CHeader(Blake2b256("Header.id").toColl, - 0, - Blake2b256("Header.parentId").toColl, - Blake2b256("ADProofsRoot").toColl, - sampleAvlTree, - Blake2b256("transactionsRoot").toColl, - timestamp = 0, - nBits = 0, - height = 0, - extensionRoot = Blake2b256("transactionsRoot").toColl, - minerPk = SigmaDsl.groupGenerator, - powOnetimePk = SigmaDsl.groupGenerator, - powNonce = Colls.fromArray(Array[Byte](0, 1, 2, 3, 4, 5, 6, 7)), - powDistance = SigmaDsl.BigInt(BigInt("1405498250268750867257727119510201256371618473728619086008183115260323").bigInteger), - votes = Colls.fromArray(Array[Byte](0, 1, 2)) - ) - val header2: Header = CHeader(Blake2b256("Header2.id").toColl, - 0, - header1.id, - Blake2b256("ADProofsRoot2").toColl, - sampleAvlTree, - Blake2b256("transactionsRoot2").toColl, - timestamp = 2, - nBits = 0, - height = 1, - extensionRoot = Blake2b256("transactionsRoot2").toColl, - minerPk = SigmaDsl.groupGenerator, - powOnetimePk = SigmaDsl.groupGenerator, - powNonce = Colls.fromArray(Array.fill(0.toByte)(8)), - powDistance = SigmaDsl.BigInt(BigInt("19306206489815517413186395405558417825367537880571815686937307203793939").bigInteger), - votes = Colls.fromArray(Array[Byte](0, 1, 0)) - ) - val headers = Colls.fromItems(header2, header1) - val preHeader: PreHeader = CPreHeader(0, - header2.id, - timestamp = 3, - nBits = 0, - height = 2, - minerPk = SigmaDsl.groupGenerator, - votes = Colls.emptyColl[Byte] - ) + object TestData { val BigIntZero: BigInt = CBigInt(new BigInteger("0", 16)) From a9cf9037c6c5bced20c4d4506a5e5e80dd056a9c Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Wed, 17 Apr 2024 18:41:50 +0300 Subject: [PATCH 22/65] SigmaDsl.toBigInteger/BigInt removed --- core/shared/src/main/scala/sigma/SigmaDsl.scala | 6 ------ .../shared/src/main/scala/sigma/data/CSigmaDslBuilder.scala | 4 ---- 2 files changed, 10 deletions(-) diff --git a/core/shared/src/main/scala/sigma/SigmaDsl.scala b/core/shared/src/main/scala/sigma/SigmaDsl.scala index df2b419273..e8ffef3fcf 100644 --- a/core/shared/src/main/scala/sigma/SigmaDsl.scala +++ b/core/shared/src/main/scala/sigma/SigmaDsl.scala @@ -718,12 +718,6 @@ trait SigmaDslBuilder { */ def decodePoint(encoded: Coll[Byte]): GroupElement - /** Create DSL big integer from existing `java.math.BigInteger`*/ - def BigInt(n: BigInteger): BigInt - - /** Extract `java.math.BigInteger` from DSL's `BigInt` type*/ - def toBigInteger(n: BigInt): BigInteger - /** Construct a new authenticated dictionary with given parameters and tree root digest. */ def avlTree(operationFlags: Byte, digest: Coll[Byte], keyLength: Int, valueLengthOpt: Option[Int]): AvlTree diff --git a/data/shared/src/main/scala/sigma/data/CSigmaDslBuilder.scala b/data/shared/src/main/scala/sigma/data/CSigmaDslBuilder.scala index 3938feacd3..c806d4a8c5 100644 --- a/data/shared/src/main/scala/sigma/data/CSigmaDslBuilder.scala +++ b/data/shared/src/main/scala/sigma/data/CSigmaDslBuilder.scala @@ -24,10 +24,6 @@ class CSigmaDslBuilder extends SigmaDslBuilder { dsl => override val Colls: CollBuilder = sigma.Colls - override def BigInt(n: BigInteger): BigInt = CBigInt(n) - - override def toBigInteger(n: BigInt): BigInteger = n.asInstanceOf[CBigInt].wrappedValue - /** Wraps the given elliptic curve point into GroupElement type. */ def GroupElement(p: Ecp): GroupElement = p match { case ept: EcPointType => CGroupElement(ept) From 7562e33bce5dfc20c3fc8ba13ebabb3099b82cf3 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Tue, 23 Apr 2024 12:30:55 +0300 Subject: [PATCH 23/65] unused SigmaDslBuilderAdapter.groupGenerator removed --- .../main/scala/special/sigma/impl/SigmaDslImpl.scala | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala index 037505b531..929d81460d 100644 --- a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala +++ b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala @@ -2278,16 +2278,6 @@ object SigmaDslBuilder extends EntityObject("SigmaDslBuilder") { def unapply(exp: Sym): Nullable[(Ref[SigmaDslBuilder], Ref[GroupElement], Ref[GroupElement], Ref[GroupElement], Ref[GroupElement])] = unapply(exp.node) } - object groupGenerator { - def unapply(d: Def[_]): Nullable[Ref[SigmaDslBuilder]] = d match { - case MethodCall(receiver, method, _, _) if method.getName == "groupGenerator" && receiver.elem.isInstanceOf[SigmaDslBuilderElem[_]] => - val res = receiver - Nullable(res).asInstanceOf[Nullable[Ref[SigmaDslBuilder]]] - case _ => Nullable.None - } - def unapply(exp: Sym): Nullable[Ref[SigmaDslBuilder]] = unapply(exp.node) - } - object substConstants { def unapply(d: Def[_]): Nullable[(Ref[SigmaDslBuilder], Ref[Coll[Byte]], Ref[Coll[Int]], Ref[Coll[T]]) forSome {type T}] = d match { case MethodCall(receiver, method, args, _) if method.getName == "substConstants" && receiver.elem.isInstanceOf[SigmaDslBuilderElem[_]] => From 2590bfa0e92f9442abb940a69f8d57bd8d3cde1c Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Wed, 24 Apr 2024 15:04:49 +0300 Subject: [PATCH 24/65] bigInt predefined function --- .../src/main/scala/sigma/ast/SigmaPredef.scala | 14 ++++++++++++++ docs/LangSpec.md | 6 ++++++ .../scala/sigmastate/lang/SigmaParserTest.scala | 5 +++++ .../scala/sigmastate/lang/SigmaCompilerTest.scala | 9 +++++++++ .../scala/sigmastate/lang/SigmaTyperTest.scala | 1 + 5 files changed, 35 insertions(+) diff --git a/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala b/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala index c4bc32e4a5..8edf9683f5 100644 --- a/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala +++ b/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala @@ -12,6 +12,8 @@ import sigma.exceptions.InvalidArguments import sigma.serialization.CoreByteWriter.ArgInfo import sigma.serialization.ValueSerializer +import java.math.BigInteger + object SigmaPredef { type IrBuilderFunc = PartialFunction[(SValue, Seq[SValue]), SValue] @@ -179,6 +181,17 @@ object SigmaPredef { Seq(ArgInfo("", ""))) ) + val BigIntFromStringFunc = PredefinedFunc("bigInt", + Lambda(Array("input" -> SString), SBigInt, None), + PredefFuncInfo( + { case (_, Seq(arg: EvaluatedValue[SString.type]@unchecked)) => + BigIntConstant(new BigInteger(arg.value)) + }), + OperationInfo(Constant, + """Parsing string argument as a 256-bit signed big integer.""".stripMargin, + Seq(ArgInfo("", ""))) + ) + val FromBase16Func = PredefinedFunc("fromBase16", Lambda(Array("input" -> SString), SByteArray, None), PredefFuncInfo( @@ -402,6 +415,7 @@ object SigmaPredef { SigmaPropFunc, GetVarFunc, DeserializeFunc, + BigIntFromStringFunc, FromBase16Func, FromBase64Func, FromBase58Func, diff --git a/docs/LangSpec.md b/docs/LangSpec.md index ddbb7bd680..59eacc3d80 100644 --- a/docs/LangSpec.md +++ b/docs/LangSpec.md @@ -985,6 +985,12 @@ def proveDHTuple(g: GroupElement, h: GroupElement, */ def proveDlog(value: GroupElement): SigmaProp +/** Transforms Base16 encoded string literal into constant of type Coll[Byte]. + * It is a compile-time operation and only string literal (constant) can be its + * argument. + */ +def bigInt(input: String): BigInt + /** Transforms Base16 encoded string literal into constant of type Coll[Byte]. * It is a compile-time operation and only string literal (constant) can be its * argument. diff --git a/parsers/shared/src/test/scala/sigmastate/lang/SigmaParserTest.scala b/parsers/shared/src/test/scala/sigmastate/lang/SigmaParserTest.scala index 7213088a05..02b28f86ca 100644 --- a/parsers/shared/src/test/scala/sigmastate/lang/SigmaParserTest.scala +++ b/parsers/shared/src/test/scala/sigmastate/lang/SigmaParserTest.scala @@ -615,6 +615,11 @@ class SigmaParserTest extends AnyPropSpec with ScalaCheckPropertyChecks with Mat MethodCallLike(StringConstant("hello"), "+", IndexedSeq(StringConstant("hello"))) } + property("bigInt string decoding") { + parse("""bigInt("32667486267383620946248345338628674027033885928301927616853987602485119134400")""") shouldBe + Apply(BigIntFromStringFunc.symNoType, IndexedSeq(StringConstant("32667486267383620946248345338628674027033885928301927616853987602485119134400"))) + } + property("fromBaseX string decoding") { parse("""fromBase16("1111")""") shouldBe Apply(FromBase16Func.symNoType, IndexedSeq(StringConstant("1111"))) parse("""fromBase58("111")""") shouldBe Apply(FromBase58Func.symNoType, IndexedSeq(StringConstant("111"))) diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala index 88c75a90b6..90e5d21b1e 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaCompilerTest.scala @@ -12,6 +12,8 @@ import sigma.ast.{Apply, MethodCall, ZKProofBlock} import sigma.exceptions.{GraphBuildingException, InvalidArguments, TyperException} import sigma.serialization.ValueSerializer import sigma.serialization.generators.ObjectGenerators + +import java.math.BigInteger import scala.annotation.unused class SigmaCompilerTest extends CompilerTestingCommons with LangTests with ObjectGenerators { @@ -127,6 +129,13 @@ class SigmaCompilerTest extends CompilerTestingCommons with LangTests with Objec res shouldEqual SigmaPropConstant(dk1) } + property("bigInt") { + comp(""" bigInt("326674862673836209462483453386286740270338859283019276168539876024851191344") """) shouldBe + BigIntConstant(new BigInteger("326674862673836209462483453386286740270338859283019276168539876024851191344")) + comp(""" bigInt("-10") """) shouldBe + BigIntConstant(-10L) + } + property("fromBaseX") { comp(""" fromBase16("31") """) shouldBe ByteArrayConstant(Array[Byte](49)) comp(""" fromBase58("r") """) shouldBe ByteArrayConstant(Array[Byte](49)) diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala index 99ad2ae908..a474727943 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala @@ -113,6 +113,7 @@ class SigmaTyperTest extends AnyPropSpec typecheck(env, "min(HEIGHT, INPUTS.size)") shouldBe SInt typecheck(env, "max(1, 2)") shouldBe SInt typecheck(env, "max(1L, 2)") shouldBe SLong + typecheck(env, """bigInt("1111")""") shouldBe SBigInt typecheck(env, """fromBase16("1111")""") shouldBe SByteArray typecheck(env, """fromBase58("111")""") shouldBe SByteArray typecheck(env, """fromBase64("111")""") shouldBe SByteArray From 7ada12a374bd5812db4d81e2e8f3f1483999205d Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Sat, 27 Apr 2024 21:32:30 +0300 Subject: [PATCH 25/65] big int related methods back, TestingInterpreterSpecification.soundness and GraphBuilding.substFromCostTable removed --- core/shared/src/main/scala/sigma/SigmaDsl.scala | 6 ++++++ .../src/main/scala/sigma/data/CSigmaDslBuilder.scala | 4 ++++ .../src/main/scala/sigmastate/eval/GraphBuilding.scala | 4 ---- .../sigmastate/TestingInterpreterSpecification.scala | 8 ++------ 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/core/shared/src/main/scala/sigma/SigmaDsl.scala b/core/shared/src/main/scala/sigma/SigmaDsl.scala index e8ffef3fcf..df2b419273 100644 --- a/core/shared/src/main/scala/sigma/SigmaDsl.scala +++ b/core/shared/src/main/scala/sigma/SigmaDsl.scala @@ -718,6 +718,12 @@ trait SigmaDslBuilder { */ def decodePoint(encoded: Coll[Byte]): GroupElement + /** Create DSL big integer from existing `java.math.BigInteger`*/ + def BigInt(n: BigInteger): BigInt + + /** Extract `java.math.BigInteger` from DSL's `BigInt` type*/ + def toBigInteger(n: BigInt): BigInteger + /** Construct a new authenticated dictionary with given parameters and tree root digest. */ def avlTree(operationFlags: Byte, digest: Coll[Byte], keyLength: Int, valueLengthOpt: Option[Int]): AvlTree diff --git a/data/shared/src/main/scala/sigma/data/CSigmaDslBuilder.scala b/data/shared/src/main/scala/sigma/data/CSigmaDslBuilder.scala index c806d4a8c5..3938feacd3 100644 --- a/data/shared/src/main/scala/sigma/data/CSigmaDslBuilder.scala +++ b/data/shared/src/main/scala/sigma/data/CSigmaDslBuilder.scala @@ -24,6 +24,10 @@ class CSigmaDslBuilder extends SigmaDslBuilder { dsl => override val Colls: CollBuilder = sigma.Colls + override def BigInt(n: BigInteger): BigInt = CBigInt(n) + + override def toBigInteger(n: BigInt): BigInteger = n.asInstanceOf[CBigInt].wrappedValue + /** Wraps the given elliptic curve point into GroupElement type. */ def GroupElement(p: Ecp): GroupElement = p match { case ept: EcPointType => CGroupElement(ept) diff --git a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala index ed25b6afa4..5ddcdfa946 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala @@ -52,10 +52,6 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => this.keepOriginalFunc = false // original lambda of Lambda node contains invocations of evalNode and we don't want that this.useAlphaEquality = false - /** Whether to create CostOf nodes or substutute costs from CostTable as constants in the graph. - * true - substitute; false - create CostOf nodes */ - var substFromCostTable: Boolean = true - /** Whether to save calcF and costF graphs in the file given by ScriptNameProp environment variable */ var saveGraphsInFile: Boolean = false diff --git a/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala b/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala index fe5a678679..66c7099436 100644 --- a/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala @@ -24,13 +24,9 @@ class TestingInterpreterSpecification extends CompilerTestingCommons with CompilerCrossVersionProps with BeforeAndAfterAll { implicit lazy val IR: TestingIRContext = new TestingIRContext - lazy val prover = new ErgoLikeTestProvingInterpreter() { - } - - lazy val verifier = new ErgoLikeTestInterpreter { - } + lazy val prover = new ErgoLikeTestProvingInterpreter() - implicit val soundness: Int = CryptoConstants.soundnessBits + lazy val verifier = new ErgoLikeTestInterpreter def testingContext(h: Int) = ErgoLikeContextTesting(h, From e0795c54565be916a9bbe84c4200abb699d547df Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Sat, 27 Apr 2024 22:01:06 +0300 Subject: [PATCH 26/65] implicits removed #1 --- .../src/main/scala/special/sigma/impl/SigmaDslImpl.scala | 2 -- sc/shared/src/test/scala/sigma/SigmaDslTesting.scala | 4 ++-- .../test/scala/sigmastate/SoftForkabilitySpecification.scala | 4 ++-- .../scala/sigmastate/TestingInterpreterSpecification.scala | 5 +++-- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala index 929d81460d..70fb35c329 100644 --- a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala +++ b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala @@ -1915,7 +1915,6 @@ object SigmaDslBuilder extends EntityObject("SigmaDslBuilder") { } override def substConstants[T](scriptBytes: Ref[Coll[Byte]], positions: Ref[Coll[Int]], newValues: Ref[Coll[T]]): Ref[Coll[Byte]] = { - implicit val eT = newValues.eA asRep[Coll[Byte]](mkMethodCall(self, SigmaDslBuilderClass.getMethod("substConstants", classOf[Sym], classOf[Sym], classOf[Sym]), Array[AnyRef](scriptBytes, positions, newValues), @@ -2075,7 +2074,6 @@ object SigmaDslBuilder extends EntityObject("SigmaDslBuilder") { } def substConstants[T](scriptBytes: Ref[Coll[Byte]], positions: Ref[Coll[Int]], newValues: Ref[Coll[T]]): Ref[Coll[Byte]] = { - implicit val eT = newValues.eA asRep[Coll[Byte]](mkMethodCall(source, SigmaDslBuilderClass.getMethod("substConstants", classOf[Sym], classOf[Sym], classOf[Sym]), Array[AnyRef](scriptBytes, positions, newValues), diff --git a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala index 46222d9fb1..cd99f5498c 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala @@ -1152,8 +1152,8 @@ class SigmaDslTesting extends AnyPropSpec (cases: Seq[A], f: Feature[A, B], nIters: Int, formatter: MeasureFormatter[A]) (implicit IR: IRContext, evalSettings: EvalSettings): Seq[Long] = { val fNew = f.newF - implicit val tA = fNew.tA - implicit val tB = fNew.tB + val tA = fNew.tA + val tB = fNew.tB implicit val cs = defaultCompilerSettings val func = funcJit[A, B](f.script) val noTraceSettings = evalSettings.copy( diff --git a/sc/shared/src/test/scala/sigmastate/SoftForkabilitySpecification.scala b/sc/shared/src/test/scala/sigmastate/SoftForkabilitySpecification.scala index bca2d0e638..c8b9f06399 100644 --- a/sc/shared/src/test/scala/sigmastate/SoftForkabilitySpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/SoftForkabilitySpecification.scala @@ -29,7 +29,7 @@ class SoftForkabilitySpecification extends SigmaTestingData with CompilerTestingCommons with BeforeAndAfterAll { - implicit lazy val IR: TestingIRContext = new TestingIRContext + val IR: TestingIRContext = new TestingIRContext lazy val prover = new ErgoLikeTestProvingInterpreter() lazy val verifier = new ErgoLikeTestInterpreter val deadline = 100 @@ -38,7 +38,7 @@ class SoftForkabilitySpecification extends SigmaTestingData lazy val booleanPropV1 = compile(emptyEnv + ("deadline" -> deadline), """{ | HEIGHT > deadline && OUTPUTS.size == 1 - |}""".stripMargin).asBoolValue + |}""".stripMargin)(IR).asBoolValue // cast Boolean typed prop to SigmaProp (which is invalid) // ErgoTree v0 lazy val invalidPropV1: ErgoTree = diff --git a/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala b/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala index 66c7099436..446f1972a7 100644 --- a/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala @@ -22,7 +22,8 @@ import scala.util.Random class TestingInterpreterSpecification extends CompilerTestingCommons with CompilerCrossVersionProps with BeforeAndAfterAll { - implicit lazy val IR: TestingIRContext = new TestingIRContext + + val IR: TestingIRContext = new TestingIRContext lazy val prover = new ErgoLikeTestProvingInterpreter() @@ -124,7 +125,7 @@ class TestingInterpreterSpecification extends CompilerTestingCommons "box1" -> testBox(10, TrueTree, 0, Seq(), Map( reg1 -> IntArrayConstant(Array[Int](1, 2, 3)), reg2 -> BoolArrayConstant(Array[Boolean](true, false, true))))) - val prop = mkTestErgoTree(compile(env, code).asBoolValue.toSigmaProp) + val prop = mkTestErgoTree(compile(env, code)(IR).asBoolValue.toSigmaProp) val challenge = Array.fill(32)(Random.nextInt(100).toByte) val proof1 = prover.prove(prop, ctx, challenge).get.proof verifier.verify(Interpreter.emptyEnv, prop, ctx, proof1, challenge) From 7f01f11403b9807558f80e25cfb704cf2a9a1280 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Sun, 28 Apr 2024 02:01:10 +0300 Subject: [PATCH 27/65] rolling back implicits in benchmarkCases --- sc/shared/src/test/scala/sigma/SigmaDslTesting.scala | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala index cd99f5498c..46222d9fb1 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala @@ -1152,8 +1152,8 @@ class SigmaDslTesting extends AnyPropSpec (cases: Seq[A], f: Feature[A, B], nIters: Int, formatter: MeasureFormatter[A]) (implicit IR: IRContext, evalSettings: EvalSettings): Seq[Long] = { val fNew = f.newF - val tA = fNew.tA - val tB = fNew.tB + implicit val tA = fNew.tA + implicit val tB = fNew.tB implicit val cs = defaultCompilerSettings val func = funcJit[A, B](f.script) val noTraceSettings = evalSettings.copy( From 691c5eecccd3ae5a9a519b7e1b9fb143ef3e7ac8 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Sun, 28 Apr 2024 02:13:13 +0300 Subject: [PATCH 28/65] CoreArrayByteOps removed --- core/js/src/main/scala/sigma/js/GroupElement.scala | 4 ++-- core/shared/src/main/scala/sigma/Environment.scala | 2 +- core/shared/src/main/scala/sigma/Extensions.scala | 5 ----- 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/core/js/src/main/scala/sigma/js/GroupElement.scala b/core/js/src/main/scala/sigma/js/GroupElement.scala index 21b53b265d..82d8d462d6 100644 --- a/core/js/src/main/scala/sigma/js/GroupElement.scala +++ b/core/js/src/main/scala/sigma/js/GroupElement.scala @@ -1,6 +1,6 @@ package sigma.js -import sigma.Extensions.CoreArrayByteOps +import scorex.util.encode.Base16 import sigma.crypto.{CryptoFacade, CryptoFacadeJs, Ecp, Platform} import scala.scalajs.js @@ -13,7 +13,7 @@ class GroupElement(val point: Ecp) extends js.Object { * @see CryptoFacade.getASN1Encoding */ def toPointHex(): String = { - CryptoFacade.getASN1Encoding(point, true).toHex + Base16.encode(CryptoFacade.getASN1Encoding(point, true)) } } diff --git a/core/shared/src/main/scala/sigma/Environment.scala b/core/shared/src/main/scala/sigma/Environment.scala index 959e02c1fb..432c40110c 100644 --- a/core/shared/src/main/scala/sigma/Environment.scala +++ b/core/shared/src/main/scala/sigma/Environment.scala @@ -14,7 +14,7 @@ sealed abstract class Environment { object Environment { /** Current runtime environment. */ - implicit val current: Environment = new Environment { + val current: Environment = new Environment { override def isJVM: Boolean = runtimePlatform == RuntimePlatform.JVM override def isJS: Boolean = runtimePlatform == RuntimePlatform.JS override def runtimePlatform: RuntimePlatform = sigma.reflection.Platform.runtimePlatform diff --git a/core/shared/src/main/scala/sigma/Extensions.scala b/core/shared/src/main/scala/sigma/Extensions.scala index 81976a3c12..0c79df94ea 100644 --- a/core/shared/src/main/scala/sigma/Extensions.scala +++ b/core/shared/src/main/scala/sigma/Extensions.scala @@ -9,11 +9,6 @@ import sigma.data.RType * See `implicit class ...` wrappers below. */ object Extensions { - /** Extension methods for `Array[Byte]` not available for generic `Array[T]`. */ - implicit class CoreArrayByteOps(val arr: Array[Byte]) extends AnyVal { - /** Encodes array into hex string */ - @inline def toHex: String = Base16.encode(arr) - } /** Extension methods for `Array[T]` where implicit descriptor `RType[T]` is also * required. From 45325928254349f21e3ab9bae784b101ce9fd950 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Wed, 1 May 2024 12:26:42 +0100 Subject: [PATCH 29/65] es-bigint: fixes in ScalaDocs --- data/shared/src/main/scala/sigma/ast/SigmaPredef.scala | 2 +- docs/LangSpec.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala b/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala index 8edf9683f5..631f7f2d75 100644 --- a/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala +++ b/data/shared/src/main/scala/sigma/ast/SigmaPredef.scala @@ -188,7 +188,7 @@ object SigmaPredef { BigIntConstant(new BigInteger(arg.value)) }), OperationInfo(Constant, - """Parsing string argument as a 256-bit signed big integer.""".stripMargin, + """Parsing string literal argument as a 256-bit signed big integer.""".stripMargin, Seq(ArgInfo("", ""))) ) diff --git a/docs/LangSpec.md b/docs/LangSpec.md index 59eacc3d80..ba66748f08 100644 --- a/docs/LangSpec.md +++ b/docs/LangSpec.md @@ -985,7 +985,7 @@ def proveDHTuple(g: GroupElement, h: GroupElement, */ def proveDlog(value: GroupElement): SigmaProp -/** Transforms Base16 encoded string literal into constant of type Coll[Byte]. +/** Transforms Base16 encoded string literal into constant of type BigInt. * It is a compile-time operation and only string literal (constant) can be its * argument. */ From 60660f20656370e0c191266604211c4866c34db7 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 2 May 2024 13:43:28 +0100 Subject: [PATCH 30/65] i956-box-in-register: moved Value to sigma-data --- .../src/main/scala/sigma/data/js/Isos.scala | 152 ++++++++++ data/js/src/main/scala/sigma/js/Box.scala | 61 ++++ data/js/src/main/scala/sigma/js/Value.scala | 266 ++++++++++++++++++ .../scala/org/ergoplatform/sdk/js/Isos.scala | 204 ++------------ .../ergoplatform/sdk/js/ProverBuilder.scala | 9 +- .../org/ergoplatform/sdk/js/SigmaProver.scala | 4 +- .../org/ergoplatform/sdk/js/IsosSpec.scala | 22 +- 7 files changed, 521 insertions(+), 197 deletions(-) create mode 100644 data/js/src/main/scala/sigma/data/js/Isos.scala create mode 100644 data/js/src/main/scala/sigma/js/Box.scala create mode 100644 data/js/src/main/scala/sigma/js/Value.scala diff --git a/data/js/src/main/scala/sigma/data/js/Isos.scala b/data/js/src/main/scala/sigma/data/js/Isos.scala new file mode 100644 index 0000000000..95bbce8bbe --- /dev/null +++ b/data/js/src/main/scala/sigma/data/js/Isos.scala @@ -0,0 +1,152 @@ +package sigma.data.js + +import org.ergoplatform.{ErgoBox, ErgoBoxCandidate} +import org.ergoplatform.ErgoBox._ +import scorex.crypto.authds.ADKey +import scorex.util.ModifierId +import scorex.util.encode.Base16 +import sigma.{Coll, Colls} +import sigmastate.fleetSdkCommon.distEsmTypesBoxesMod.{Box => FBox} +import sigmastate.fleetSdkCommon.distEsmTypesCommonMod.{Amount, HexString} +import sigmastate.fleetSdkCommon.distEsmTypesRegistersMod.NonMandatoryRegisters +import sigmastate.fleetSdkCommon.{distEsmTypesBoxesMod => boxesMod, distEsmTypesCommonMod => commonMod, distEsmTypesRegistersMod => registersMod, distEsmTypesTokenMod => tokenMod} +import sigma.Extensions._ +import sigma.ast.syntax.GroupElementConstant +import sigma.ast.{Constant, GroupElementConstant, SType} +import sigma.data.Iso.isoStringToArray +import sigma.data.{CGroupElement, Digest32Coll, Iso} +import sigma.js.GroupElement +import sigma.serialization.{ErgoTreeSerializer, ValueSerializer} + +import scala.scalajs.js + +/** Definitions of isomorphisms for sigma-data module. */ +object Isos { + + val isoStringToGroupElement: Iso[String, sigma.GroupElement] = new Iso[String, sigma.GroupElement] { + override def to(x: String): sigma.GroupElement = { + val bytes = Base16.decode(x).get + ValueSerializer.deserialize(bytes).asInstanceOf[GroupElementConstant].value + } + override def from(x: sigma.GroupElement): String = { + val bytes = ValueSerializer.serialize(GroupElementConstant(x)) + Base16.encode(bytes) + } + } + + val isoGroupElement: Iso[GroupElement, sigma.GroupElement] = new Iso[GroupElement, sigma.GroupElement] { + override def to(x: GroupElement): sigma.GroupElement = { + CGroupElement(x.point) + } + override def from(x: sigma.GroupElement): GroupElement = { + new GroupElement(x.asInstanceOf[CGroupElement].wrappedValue) + } + } + + implicit val isoBoxId: Iso[boxesMod.BoxId, ErgoBox.BoxId] = new Iso[boxesMod.BoxId, ErgoBox.BoxId] { + override def to(x: boxesMod.BoxId): ErgoBox.BoxId = ADKey @@@ isoStringToArray.to(x) + + override def from(x: ErgoBox.BoxId): boxesMod.BoxId = isoStringToArray.from(x) + } + + implicit val isoHexStringToConstant: Iso[HexString, Constant[SType]] = new Iso[HexString, Constant[SType]] { + override def to(x: HexString): Constant[SType] = { + val bytes = isoStringToArray.to(x) + val value = ValueSerializer.deserialize(bytes) + value.asInstanceOf[Constant[SType]] + } + override def from(x: Constant[SType]): HexString = { + val bytes = ValueSerializer.serialize(x) + isoStringToArray.from(bytes) + } + } + + + implicit val isoAmount: Iso[commonMod.Amount, Long] = new Iso[commonMod.Amount, Long] { + override def to(x: commonMod.Amount): Long = x.asInstanceOf[Any] match { + case s: String => BigInt(s).toLong + case _ => java.lang.Long.parseLong(x.asInstanceOf[js.BigInt].toString(10)) + } + override def from(x: Long): commonMod.Amount = x.toString + } + + implicit val isoToken: Iso[tokenMod.TokenAmount[commonMod.Amount], Token] = + new Iso[tokenMod.TokenAmount[commonMod.Amount], Token] { + override def to(x: tokenMod.TokenAmount[commonMod.Amount]): Token = + (Digest32Coll @@@ Colls.fromArray(Base16.decode(x.tokenId).get), isoAmount.to(x.amount)) + + override def from(x: Token): tokenMod.TokenAmount[commonMod.Amount] = + tokenMod.TokenAmount[commonMod.Amount](isoAmount.from(x._2), x._1.toHex) + } + + val isoTokenArray: Iso[js.Array[tokenMod.TokenAmount[commonMod.Amount]], Coll[Token]] = + new Iso[js.Array[tokenMod.TokenAmount[commonMod.Amount]], Coll[Token]] { + override def to(x: js.Array[tokenMod.TokenAmount[commonMod.Amount]]): Coll[Token] = { + sigma.js.Isos.isoArrayToColl(isoToken).to(x) + } + override def from(x: Coll[Token]): js.Array[tokenMod.TokenAmount[commonMod.Amount]] = { + sigma.js.Isos.isoArrayToColl(isoToken).from(x) + } + } + + val isoNonMandatoryRegisters: Iso[registersMod.NonMandatoryRegisters, AdditionalRegisters] = + new Iso[registersMod.NonMandatoryRegisters, AdditionalRegisters] { + override def to(x: registersMod.NonMandatoryRegisters): AdditionalRegisters = { + val regs = Seq( + x.R4 -> R4, + x.R5 -> R5, + x.R6 -> R6, + x.R7 -> R7, + x.R8 -> R8, + x.R9 -> R9 + ).collect { + case (regOpt, id) if regOpt.isDefined => id -> isoHexStringToConstant.to(regOpt.get) + } + Map(regs:_*) + } + override def from(regs: AdditionalRegisters): registersMod.NonMandatoryRegisters = { + def regHexOpt(t: NonMandatoryRegisterId): Option[HexString] = + regs.get(t).map(v => isoHexStringToConstant.from(v.asInstanceOf[Constant[SType]])) + + val resRegs = NonMandatoryRegisters() + regHexOpt(R4).foreach(resRegs.setR4(_)) + regHexOpt(R5).foreach(resRegs.setR5(_)) + regHexOpt(R6).foreach(resRegs.setR6(_)) + regHexOpt(R7).foreach(resRegs.setR7(_)) + regHexOpt(R8).foreach(resRegs.setR8(_)) + regHexOpt(R9).foreach(resRegs.setR9(_)) + resRegs + } + } + + implicit val isoBoxCandidate: Iso[boxesMod.BoxCandidate[commonMod.Amount, NonMandatoryRegisters], ErgoBoxCandidate] = new Iso[boxesMod.BoxCandidate[commonMod.Amount, NonMandatoryRegisters], ErgoBoxCandidate] { + override def to(x: boxesMod.BoxCandidate[commonMod.Amount, NonMandatoryRegisters]): ErgoBoxCandidate = { + val ergoBoxCandidate = new ErgoBoxCandidate( + value = isoAmount.to(x.value), + ergoTree = { + val bytes = Base16.decode(x.ergoTree).get + ErgoTreeSerializer.DefaultSerializer.deserializeErgoTree(bytes) + }, + x.creationHeight.toInt, + additionalTokens = isoTokenArray.to(x.assets), + additionalRegisters = isoNonMandatoryRegisters.to(x.additionalRegisters) + ) + ergoBoxCandidate + } + + override def from(x: ErgoBoxCandidate): boxesMod.BoxCandidate[commonMod.Amount, NonMandatoryRegisters] = { + val ergoTree = ErgoTreeSerializer.DefaultSerializer.serializeErgoTree(x.ergoTree) + val ergoTreeStr = Base16.encode(ergoTree) + val assets = isoTokenArray.from(x.additionalTokens) + boxesMod.BoxCandidate[commonMod.Amount, NonMandatoryRegisters]( + ergoTree = ergoTreeStr, + value = isoAmount.from(x.value), + assets = assets, + creationHeight = x.creationHeight, + additionalRegisters = isoNonMandatoryRegisters.from(x.additionalRegisters) + ) + } + } + + +} diff --git a/data/js/src/main/scala/sigma/js/Box.scala b/data/js/src/main/scala/sigma/js/Box.scala new file mode 100644 index 0000000000..209e15d489 --- /dev/null +++ b/data/js/src/main/scala/sigma/js/Box.scala @@ -0,0 +1,61 @@ +package sigma.js + +import org.ergoplatform.ErgoBox +import scorex.util.ModifierId +import scorex.util.encode.Base16 +import sigma.data.Iso +import sigma.data.js.Isos.{isoAmount, isoNonMandatoryRegisters, isoTokenArray} +import sigma.serialization.ErgoTreeSerializer +import sigmastate.fleetSdkCommon.distEsmTypesBoxesMod.{Box => FBox} +import sigmastate.fleetSdkCommon.distEsmTypesCommonMod.Amount +import sigmastate.fleetSdkCommon.distEsmTypesRegistersMod.NonMandatoryRegisters +import sigmastate.fleetSdkCommon.{distEsmTypesCommonMod => commonMod} + +import scala.scalajs.js +import scala.scalajs.js.annotation.JSExportTopLevel + +/** Equivalent of [[sigma.Box]] available from JS. */ +@JSExportTopLevel("Box") +class Box(val box: FBox[Amount, NonMandatoryRegisters]) extends js.Object { +} + +@JSExportTopLevel("Box$") +object Box extends js.Object { + + /** Converts Fleet box to ErgoBox and back. */ + val isoBox: Iso[FBox[commonMod.Amount, NonMandatoryRegisters], ErgoBox] = new Iso[FBox[commonMod.Amount, NonMandatoryRegisters], ErgoBox] { + override def to(x: FBox[commonMod.Amount, NonMandatoryRegisters]): ErgoBox = { + val ergoBox = new ErgoBox( + value = isoAmount.to(x.value), + ergoTree = { + val bytes = Base16.decode(x.ergoTree).get + ErgoTreeSerializer.DefaultSerializer.deserializeErgoTree(bytes) + }, + creationHeight = x.creationHeight.toInt, + additionalTokens = isoTokenArray.to(x.assets), + additionalRegisters = isoNonMandatoryRegisters.to(x.additionalRegisters), + transactionId = ModifierId @@ x.transactionId, + index = x.index.toShort + ) + ergoBox + } + + override def from(x: ErgoBox): FBox[commonMod.Amount, NonMandatoryRegisters] = { + val ergoTree = ErgoTreeSerializer.DefaultSerializer.serializeErgoTree(x.ergoTree) + val ergoTreeStr = Base16.encode(ergoTree) + val assets = isoTokenArray.from(x.additionalTokens) + FBox[commonMod.Amount, NonMandatoryRegisters]( + boxId = Base16.encode(x.id), + ergoTree = ergoTreeStr, + value = isoAmount.from(x.value), + assets = assets, + creationHeight = x.creationHeight, + additionalRegisters = isoNonMandatoryRegisters.from(x.additionalRegisters), + transactionId = x.transactionId, + index = x.index + ) + } + } + + +} \ No newline at end of file diff --git a/data/js/src/main/scala/sigma/js/Value.scala b/data/js/src/main/scala/sigma/js/Value.scala new file mode 100644 index 0000000000..785f9e04db --- /dev/null +++ b/data/js/src/main/scala/sigma/js/Value.scala @@ -0,0 +1,266 @@ +package sigma +package js + +import scorex.util.Extensions.{IntOps, LongOps} +import scorex.util.encode.Base16 +import sigma.ast.SType +import sigma.crypto.Platform +import sigma.data._ +import sigma.js.Value.toRuntimeData +import sigma.serialization.{CoreSerializer, DataSerializer} +import sigma.util.Extensions.BigIntOps +import sigma.{Coll, Colls, Evaluation} + +import java.math.BigInteger +import scala.scalajs.js +import scala.scalajs.js.annotation.JSExportTopLevel + +/** + * This class is used to represent any valid value of ErgoScript language. + * Any such value comes equipped with {@link Type} descriptor. + * Note, there is a distinction between JS types and ErgoScript types. + * Each Value instance represents the concrete ErgoScript type given by `tpe`. + * The implementation is based on the pre-defined mapping between JS and ES types. + * This mapping is applied recursively and is given by the following: + * + * JS type | ErgoScript Type + * -------------------------------------- + * Number | Byte + * Number | Short + * Number | Int + * BigInt | Long + * BigInt | BigInt + * array [A, B] | (A, B) - pair + * array [a1, a2 ..] | Coll[A] - collection + * + * @param data JS value wrapped in this value + * @param tpe type descriptor of the ErgoScript type + */ +@JSExportTopLevel("Value") +class Value(val data: Any, val tpe: Type) extends js.Object { + + /** Get Sigma runtime value which can be passed to interpreter, saved in register and + * [[sigma.ast.Constant]] nodes. + */ + final def runtimeData: Any = toRuntimeData(data, tpe.rtype) + + /** + * Encode this value as Base16 hex string. + * 1) it transforms this value into {@link sigma.ast.ConstantNode} of sigma. + * 2) it serializes the constant into byte array using {@link sigmastate.serialization.ConstantSerializer} + * 3) the bytes are encoded using Base16 encoder into string + * + * @return hex string of serialized bytes + */ + def toHex(): String = { + val stype = Evaluation.rtypeToSType(tpe.rtype) + val value = runtimeData.asInstanceOf[SType#WrappedType] + val w = CoreSerializer.startWriter() + w.putType(stype) + DataSerializer.serialize(value, stype, w) + Base16.encode(w.toBytes) + } +} + +@JSExportTopLevel("Value$") +object Value extends js.Object { + /** Maximal positive value of ES type Long */ + val MaxLong = js.BigInt("0x7fffffffffffffff") + + /** Minimal negative value of ES type Long */ + val MinLong = -js.BigInt("0x8000000000000000") + + /** Helper method to get Sigma runtime value which can be passed to interpreter, saved + * in register and [[sigma.ast.Constant]] nodes. + */ + final private[js] def toRuntimeData(data: Any, rtype: RType[_]): Any = rtype match { + case sigma.BooleanType => data + case sigma.ByteType | sigma.ShortType | sigma.IntType => data + case sigma.LongType => java.lang.Long.parseLong(data.asInstanceOf[js.BigInt].toString(10)) + case sigma.BigIntRType => + val v = data.asInstanceOf[js.BigInt] + CBigInt(new BigInteger(v.toString(16), 16)) + case sigma.GroupElementRType => + val ge = data.asInstanceOf[GroupElement] + CGroupElement(ge.point) + case sigma.SigmaPropRType => + val p = data.asInstanceOf[SigmaProp] + CSigmaProp(p.sigmaBoolean) + case sigma.AvlTreeRType => + val t = data.asInstanceOf[AvlTree] + AvlTree.isoAvlTree.to(t) + case sigma.BoxRType => + val t = data.asInstanceOf[Box] + CBox(Box.isoBox.to(t.box)) + case ct: CollType[a] => + val xs = data.asInstanceOf[js.Array[Any]] + implicit val cT = ct.tItem.classTag + val items = xs.map(x => toRuntimeData(x, ct.tItem).asInstanceOf[a]).toArray[a] + Colls.fromItems(items:_*)(ct.tItem) + case pt: PairType[a, b] => + val p = data.asInstanceOf[js.Array[Any]] + val x = toRuntimeData(p(0), pt.tFst).asInstanceOf[a] + val y = toRuntimeData(p(1), pt.tSnd).asInstanceOf[b] + (x, y) + case sigma.UnitType => data + case _ => + throw new IllegalArgumentException(s"Unsupported type $rtype") + } + + /** Helper method to extract JS data value from Sigma runtime value. + * This should be inverse to `toRuntimeData`. + * + * @param value runtime value of type given by `rtype` + * @param rtype type descriptor of Sigma runtime value + */ + final def fromRuntimeData(value: Any, rtype: RType[_]): Any = rtype match { + case sigma.BooleanType => value + case sigma.ByteType | sigma.ShortType | sigma.IntType => value + case sigma.LongType => js.BigInt(value.asInstanceOf[Long].toString) + case sigma.BigIntRType => + val hex = value.asInstanceOf[sigma.BigInt].toBigInteger.toString(10) + js.BigInt(hex) + case sigma.GroupElementRType => + val point = value.asInstanceOf[CGroupElement].wrappedValue.asInstanceOf[Platform.Ecp] + new GroupElement(point) + case sigma.SigmaPropRType => + new SigmaProp(value.asInstanceOf[CSigmaProp].wrappedValue) + case sigma.AvlTreeRType => + AvlTree.isoAvlTree.from(value.asInstanceOf[CAvlTree]) + case sigma.BoxRType => + AvlTree.isoAvlTree.from(value.asInstanceOf[CAvlTree]) + case ct: CollType[a] => + val arr = value.asInstanceOf[Coll[a]].toArray + js.Array(arr.map(x => fromRuntimeData(x, ct.tItem)):_*) + case pt: PairType[a, b] => + val p = value.asInstanceOf[(a, b)] + js.Array(fromRuntimeData(p._1, pt.tFst), fromRuntimeData(p._2, pt.tSnd)) + case sigma.UnitType => value + case _ => + throw new IllegalArgumentException(s"Unsupported type $rtype") + } + + /** Helper method to check validity of JS data value against the given runtime type. + * + * @param data js value + * @param rtype type descriptor of Sigma runtime value + */ + final private def checkJsData[T](data: T, rtype: RType[_]): Any = rtype match { + case sigma.ByteType => data.asInstanceOf[Int].toByteExact + case sigma.ShortType => data.asInstanceOf[Int].toShortExact + case sigma.IntType => data.asInstanceOf[Int].toLong.toIntExact + case sigma.LongType => + val n = data.asInstanceOf[js.BigInt] + if (n < MinLong || n > MaxLong) + throw new ArithmeticException(s"value $n is out of long range") + n + case sigma.BigIntRType => + data.asInstanceOf[js.BigInt] + case sigma.GroupElementRType => + data.asInstanceOf[GroupElement] + case sigma.SigmaPropRType => + data.asInstanceOf[SigmaProp] + case PairType(l, r) => data match { + case arr: js.Array[Any @unchecked] => + checkJsData(arr(0), l) + checkJsData(arr(1), r) + data + case _ => + throw new ArithmeticException(s"$data cannot represent pair value") + } + case CollType(elemType) => data match { + case arr: js.Array[Any @unchecked] => + arr.foreach(x => checkJsData(x, elemType)) + data + case _ => + throw new ArithmeticException(s"$data cannot represent Coll value") + } + case _ => + throw new IllegalArgumentException(s"Unsupported type $rtype") + } + + /** Create Byte value from JS number. */ + def ofByte(n: Int): Value = { + checkJsData(n, Type.Byte.rtype) + new Value(n, Type.Byte) + } + + /** Create Short value from JS number. */ + def ofShort(n: Int): Value = { + checkJsData(n, Type.Short.rtype) + new Value(n, Type.Short) + } + + /** Create Int value from JS number. */ + def ofInt(n: Int): Value = { + checkJsData(n, Type.Int.rtype) + new Value(n, Type.Int) + } + + /** Create Long value from JS BigInt. */ + def ofLong(n: js.BigInt): Value = { + checkJsData(n, Type.Long.rtype) + new Value(n, Type.Long) + } + + /** Create BigInt value from JS BigInt. */ + def ofBigInt(n: js.BigInt): Value = { + checkJsData(n, Type.BigInt.rtype) + new Value(n, Type.BigInt) + } + + /** Creates a Value of GroupElement type from [[sigmastate.crypto.Platform.Point]] hex. + * @param pointHex hex of ASN representation of [[sigmastate.crypto.Platform.Point]] + */ + def ofGroupElement(pointHex: String): Value = { + val ge = GroupElement.fromPointHex(pointHex) + new Value(ge, Type.GroupElement) + } + + /** Creates a Value of SigmaProp type from [[sigmastate.crypto.Platform.Point]] hex. + * @param pointHex hex of ASN representation of [[sigmastate.crypto.Platform.Point]] + */ + def ofSigmaProp(pointHex: String): Value = { + val sp = SigmaProp.fromPointHex(pointHex) + new Value(sp, Type.SigmaProp) + } + + /** Create Pair value from two values. */ + def pairOf(l: Value, r: Value): Value = { + val data = js.Array(l.data, r.data) // the l and r data have been validated + new Value(data, Type.pairType(l.tpe, r.tpe)) + } + + /** Create Coll value from array and element type descriptor. + * @param items collection elements which should be valid JS representation of `elemType` + * @param elemType descriptor of types for collection elements + */ + def collOf(items: js.Array[Any], elemType: Type): Value = { + val t = Type.collType(elemType) + checkJsData(items, t.rtype) + new Value(items, t) + } + + /** + * Creates Value from hex encoded serialized bytes of Constant values. + *

+ * In order to create Value you need to provide both value instance and + * Type descriptor. This is similar to how values are represented in sigma + * ConstantNode. Each ConstantNode also have value instance and `tpe: SType` + * descriptor. + * @param hex the string is obtained as hex encoding of serialized ConstantNode. + * (The bytes obtained by ConstantSerializer in sigma) + * @return new deserialized Value instance containing: + * - suitable JS value in its `data` field + * - and [[Type]] descriptor in its `tpe` field + */ + def fromHex(hex: String): Value = { + val bytes = Base16.decode(hex).fold(t => throw t, identity) + val r = CoreSerializer.startReader(bytes) + val stype = r.getType() + val value = DataSerializer.deserialize(stype, r) + val rtype = Evaluation.stypeToRType(stype) + val jsvalue = Value.fromRuntimeData(value, rtype) + new Value(jsvalue, new Type(rtype)) + } +} diff --git a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala index f6393f62bb..f4085cf2a9 100644 --- a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala +++ b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala @@ -24,52 +24,14 @@ import sigmastate.fleetSdkCommon.distEsmTypesRegistersMod.NonMandatoryRegisters import sigmastate.fleetSdkCommon.distEsmTypesTokenMod.TokenAmount import sigmastate.fleetSdkCommon.distEsmTypesTransactionsMod.{SignedTransaction, UnsignedTransaction} import sigmastate.fleetSdkCommon.{distEsmTypesBoxesMod => boxesMod, distEsmTypesCommonMod => commonMod, distEsmTypesContextExtensionMod => contextExtensionMod, distEsmTypesInputsMod => inputsMod, distEsmTypesProverResultMod => proverResultMod, distEsmTypesRegistersMod => registersMod, distEsmTypesTokenMod => tokenMod} - +import sigma.data.js.{Isos => DataIsos} import java.math.BigInteger import scala.collection.immutable.ListMap import scala.scalajs.js import scala.scalajs.js.Object -/** Definitions of isomorphisms. */ +/** Definitions of isomorphisms for sigma-sdk module. */ object Isos { - val isoStringToGroupElement: Iso[String, sigma.GroupElement] = new Iso[String, sigma.GroupElement] { - override def to(x: String): sigma.GroupElement = { - val bytes = Base16.decode(x).get - ValueSerializer.deserialize(bytes).asInstanceOf[GroupElementConstant].value - } - override def from(x: sigma.GroupElement): String = { - val bytes = ValueSerializer.serialize(GroupElementConstant(x)) - Base16.encode(bytes) - } - } - - val isoGroupElement: Iso[GroupElement, sigma.GroupElement] = new Iso[GroupElement, sigma.GroupElement] { - override def to(x: GroupElement): sigma.GroupElement = { - CGroupElement(x.point) - } - override def from(x: sigma.GroupElement): GroupElement = { - new GroupElement(x.asInstanceOf[CGroupElement].wrappedValue) - } - } - - implicit val isoBoxId: Iso[boxesMod.BoxId, ErgoBox.BoxId] = new Iso[boxesMod.BoxId, ErgoBox.BoxId] { - override def to(x: boxesMod.BoxId): ErgoBox.BoxId = ADKey @@@ isoStringToArray.to(x) - - override def from(x: ErgoBox.BoxId): boxesMod.BoxId = isoStringToArray.from(x) - } - - implicit val isoHexStringToConstant: Iso[HexString, Constant[SType]] = new Iso[HexString, Constant[SType]] { - override def to(x: HexString): Constant[SType] = { - val bytes = isoStringToArray.to(x) - val value = ValueSerializer.deserialize(bytes) - value.asInstanceOf[Constant[SType]] - } - override def from(x: Constant[SType]): HexString = { - val bytes = ValueSerializer.serialize(x) - isoStringToArray.from(bytes) - } - } - implicit val isoHeader: Iso[Header, sigma.Header] = new Iso[Header, sigma.Header] { override def to(a: Header): sigma.Header = { CHeader( @@ -83,8 +45,8 @@ object Isos { nBits = sigma.js.Isos.isoBigIntToLong.to(a.nBits), height = a.height, extensionRoot = isoStringToColl.to(a.extensionRoot), - minerPk = isoGroupElement.to(a.minerPk), - powOnetimePk = isoGroupElement.to(a.powOnetimePk), + minerPk = DataIsos.isoGroupElement.to(a.minerPk), + powOnetimePk = DataIsos.isoGroupElement.to(a.powOnetimePk), powNonce = isoStringToColl.to(a.powNonce), powDistance = sigma.js.Isos.isoBigInt.to(a.powDistance), votes = isoStringToColl.to(a.votes) @@ -103,8 +65,8 @@ object Isos { nBits = sigma.js.Isos.isoBigIntToLong.from(header.nBits), height = header.height, extensionRoot = isoStringToColl.from(header.extensionRoot), - minerPk = isoGroupElement.from(header.minerPk), - powOnetimePk = isoGroupElement.from(header.powOnetimePk), + minerPk = DataIsos.isoGroupElement.from(header.minerPk), + powOnetimePk = DataIsos.isoGroupElement.from(header.powOnetimePk), powNonce = isoStringToColl.from(header.powNonce), powDistance = sigma.js.Isos.isoBigInt.from(header.powDistance), votes = isoStringToColl.from(header.votes) @@ -120,7 +82,7 @@ object Isos { timestamp = sigma.js.Isos.isoBigIntToLong.to(a.timestamp), nBits = sigma.js.Isos.isoBigIntToLong.to(a.nBits), height = a.height, - minerPk = isoGroupElement.to(a.minerPk), + minerPk = DataIsos.isoGroupElement.to(a.minerPk), votes = isoStringToColl.to(a.votes) ) } @@ -132,7 +94,7 @@ object Isos { timestamp = sigma.js.Isos.isoBigIntToLong.from(header.timestamp), nBits = sigma.js.Isos.isoBigIntToLong.from(header.nBits), height = header.height, - minerPk = isoGroupElement.from(header.minerPk), + minerPk = DataIsos.isoGroupElement.from(header.minerPk), votes = isoStringToColl.from(header.votes) ) } @@ -195,7 +157,7 @@ object Isos { val keys = js.Object.keys(x).sorted for ( k <- keys ) { val id = k.toInt.toByte - val c = isoHexStringToConstant.to(x.apply(id).get.get) + val c = DataIsos.isoHexStringToConstant.to(x.apply(id).get.get) map = map + (id -> c) } ContextExtension(map) @@ -204,7 +166,7 @@ object Isos { override def from(x: ContextExtension): contextExtensionMod.ContextExtension = { val res = new Object().asInstanceOf[contextExtensionMod.ContextExtension] x.values.foreach { case (k, v: Constant[_]) => - val hex = isoHexStringToConstant.from(v) + val hex = DataIsos.isoHexStringToConstant.from(v) res.update(k, hex) } res @@ -213,10 +175,10 @@ object Isos { implicit val isoUnsignedInput: Iso[inputsMod.UnsignedInput, UnsignedInput] = new Iso[inputsMod.UnsignedInput, UnsignedInput] { override def to(x: inputsMod.UnsignedInput): UnsignedInput = - new UnsignedInput(x.boxId.convertTo[ErgoBox.BoxId], isoContextExtension.to(x.extension)) + new UnsignedInput(DataIsos.isoBoxId.to(x.boxId), isoContextExtension.to(x.extension)) override def from(x: UnsignedInput): inputsMod.UnsignedInput = - inputsMod.UnsignedInput(x.boxId.convertTo[boxesMod.BoxId], isoContextExtension.from(x.extension)) + inputsMod.UnsignedInput(DataIsos.isoBoxId.from(x.boxId), isoContextExtension.from(x.extension)) } implicit val isoProverResult: Iso[proverResultMod.ProverResult, ProverResult] = new Iso[proverResultMod.ProverResult, ProverResult] { @@ -236,135 +198,17 @@ object Isos { implicit val isoSignedInput: Iso[inputsMod.SignedInput, Input] = new Iso[inputsMod.SignedInput, Input] { override def to(x: inputsMod.SignedInput): Input = - Input(x.boxId.convertTo[ErgoBox.BoxId], isoProverResult.to(x.spendingProof)) + Input(DataIsos.isoBoxId.to(x.boxId), isoProverResult.to(x.spendingProof)) override def from(x: Input): inputsMod.SignedInput = - inputsMod.SignedInput(x.boxId.convertTo[boxesMod.BoxId], isoProverResult.from(x.spendingProof)) + inputsMod.SignedInput(DataIsos.isoBoxId.from(x.boxId), isoProverResult.from(x.spendingProof)) } implicit val isoDataInput: Iso[inputsMod.DataInput, DataInput] = new Iso[inputsMod.DataInput, DataInput] { - override def to(x: inputsMod.DataInput): DataInput = DataInput(x.boxId.convertTo[ErgoBox.BoxId]) - - override def from(x: DataInput): inputsMod.DataInput = inputsMod.DataInput(x.boxId.convertTo[boxesMod.BoxId]) - } + override def to(x: inputsMod.DataInput): DataInput = + DataInput(DataIsos.isoBoxId.to(x.boxId)) - implicit val isoAmount: Iso[commonMod.Amount, Long] = new Iso[commonMod.Amount, Long] { - override def to(x: commonMod.Amount): Long = x.asInstanceOf[Any] match { - case s: String => BigInt(s).toLong - case _ => java.lang.Long.parseLong(x.asInstanceOf[js.BigInt].toString(10)) - } - override def from(x: Long): commonMod.Amount = x.toString - } - - implicit val isoToken: Iso[tokenMod.TokenAmount[commonMod.Amount], Token] = - new Iso[tokenMod.TokenAmount[commonMod.Amount], Token] { - override def to(x: tokenMod.TokenAmount[commonMod.Amount]): Token = - (Digest32Coll @@@ Colls.fromArray(Base16.decode(x.tokenId).get), isoAmount.to(x.amount)) - - override def from(x: Token): tokenMod.TokenAmount[commonMod.Amount] = - tokenMod.TokenAmount[commonMod.Amount](isoAmount.from(x._2), x._1.toHex) - } - - val isoTokenArray: Iso[js.Array[tokenMod.TokenAmount[commonMod.Amount]], Coll[Token]] = - new Iso[js.Array[tokenMod.TokenAmount[commonMod.Amount]], Coll[Token]] { - override def to(x: js.Array[tokenMod.TokenAmount[commonMod.Amount]]): Coll[Token] = { - sigma.js.Isos.isoArrayToColl(isoToken).to(x) - } - override def from(x: Coll[Token]): js.Array[tokenMod.TokenAmount[commonMod.Amount]] = { - sigma.js.Isos.isoArrayToColl(isoToken).from(x) - } - } - - val isoNonMandatoryRegisters: Iso[registersMod.NonMandatoryRegisters, AdditionalRegisters] = - new Iso[registersMod.NonMandatoryRegisters, AdditionalRegisters] { - override def to(x: registersMod.NonMandatoryRegisters): AdditionalRegisters = { - val regs = Seq( - x.R4 -> R4, - x.R5 -> R5, - x.R6 -> R6, - x.R7 -> R7, - x.R8 -> R8, - x.R9 -> R9 - ).collect { - case (regOpt, id) if regOpt.isDefined => id -> isoHexStringToConstant.to(regOpt.get) - } - Map(regs:_*) - } - override def from(regs: AdditionalRegisters): registersMod.NonMandatoryRegisters = { - def regHexOpt(t: NonMandatoryRegisterId): Option[HexString] = - regs.get(t).map(v => isoHexStringToConstant.from(v.asInstanceOf[Constant[SType]])) - - val resRegs = NonMandatoryRegisters() - regHexOpt(R4).foreach(resRegs.setR4(_)) - regHexOpt(R5).foreach(resRegs.setR5(_)) - regHexOpt(R6).foreach(resRegs.setR6(_)) - regHexOpt(R7).foreach(resRegs.setR7(_)) - regHexOpt(R8).foreach(resRegs.setR8(_)) - regHexOpt(R9).foreach(resRegs.setR9(_)) - resRegs - } - } - - implicit val isoBoxCandidate: Iso[boxesMod.BoxCandidate[commonMod.Amount, NonMandatoryRegisters], ErgoBoxCandidate] = new Iso[boxesMod.BoxCandidate[commonMod.Amount, NonMandatoryRegisters], ErgoBoxCandidate] { - override def to(x: boxesMod.BoxCandidate[commonMod.Amount, NonMandatoryRegisters]): ErgoBoxCandidate = { - val ergoBoxCandidate = new ErgoBoxCandidate( - value = isoAmount.to(x.value), - ergoTree = { - val bytes = Base16.decode(x.ergoTree).get - ErgoTreeSerializer.DefaultSerializer.deserializeErgoTree(bytes) - }, - x.creationHeight.toInt, - additionalTokens = isoTokenArray.to(x.assets), - additionalRegisters = isoNonMandatoryRegisters.to(x.additionalRegisters) - ) - ergoBoxCandidate - } - - override def from(x: ErgoBoxCandidate): boxesMod.BoxCandidate[commonMod.Amount, NonMandatoryRegisters] = { - val ergoTree = ErgoTreeSerializer.DefaultSerializer.serializeErgoTree(x.ergoTree) - val ergoTreeStr = Base16.encode(ergoTree) - val assets = isoTokenArray.from(x.additionalTokens) - boxesMod.BoxCandidate[commonMod.Amount, NonMandatoryRegisters]( - ergoTree = ergoTreeStr, - value = isoAmount.from(x.value), - assets = assets, - creationHeight = x.creationHeight, - additionalRegisters = isoNonMandatoryRegisters.from(x.additionalRegisters) - ) - } - } - - val isoBox: Iso[Box[commonMod.Amount, NonMandatoryRegisters], ErgoBox] = new Iso[Box[commonMod.Amount, NonMandatoryRegisters], ErgoBox] { - override def to(x: Box[commonMod.Amount, NonMandatoryRegisters]): ErgoBox = { - val ergoBox = new ErgoBox( - value = isoAmount.to(x.value), - ergoTree = { - val bytes = Base16.decode(x.ergoTree).get - ErgoTreeSerializer.DefaultSerializer.deserializeErgoTree(bytes) - }, - creationHeight = x.creationHeight.toInt, - additionalTokens = isoTokenArray.to(x.assets), - additionalRegisters = isoNonMandatoryRegisters.to(x.additionalRegisters), - transactionId = ModifierId @@ x.transactionId, - index = x.index.toShort - ) - ergoBox - } - - override def from(x: ErgoBox): Box[commonMod.Amount, NonMandatoryRegisters] = { - val ergoTree = ErgoTreeSerializer.DefaultSerializer.serializeErgoTree(x.ergoTree) - val ergoTreeStr = Base16.encode(ergoTree) - val assets = isoTokenArray.from(x.additionalTokens) - Box[commonMod.Amount, NonMandatoryRegisters]( - boxId = Base16.encode(x.id), - ergoTree = ergoTreeStr, - value = isoAmount.from(x.value), - assets = assets, - creationHeight = x.creationHeight, - additionalRegisters = isoNonMandatoryRegisters.from(x.additionalRegisters), - transactionId = x.transactionId, - index = x.index - ) - } + override def from(x: DataInput): inputsMod.DataInput = + inputsMod.DataInput(DataIsos.isoBoxId.from(x.boxId)) } val isoEIP12UnsignedInput: Iso[inputsMod.EIP12UnsignedInput, ExtendedInputBox] = @@ -380,12 +224,12 @@ object Isos { transactionId = x.transactionId, index = x.index ) - val ergoBox = isoBox.to(box) + val ergoBox = sigma.js.Box.isoBox.to(box) val extendedInputBox = ExtendedInputBox(ergoBox, isoContextExtension.to(x.extension)) extendedInputBox } override def from(x: ExtendedInputBox): inputsMod.EIP12UnsignedInput = { - val box = isoBox.from(x.box) + val box = sigma.js.Box.isoBox.from(x.box) val ext = isoContextExtension.from(x.extension) inputsMod.EIP12UnsignedInput( boxId = box.boxId, @@ -407,7 +251,7 @@ object Isos { new UnsignedErgoLikeTransaction( inputs = sigma.js.Isos.isoArrayToIndexed(isoUnsignedInput).to(a.inputs), dataInputs = sigma.js.Isos.isoArrayToIndexed(isoDataInput).to(a.dataInputs), - outputCandidates = sigma.js.Isos.isoArrayToIndexed(isoBoxCandidate).to(a.outputs), + outputCandidates = sigma.js.Isos.isoArrayToIndexed(DataIsos.isoBoxCandidate).to(a.outputs), ) } @@ -415,7 +259,7 @@ object Isos { UnsignedTransaction( inputs = sigma.js.Isos.isoArrayToIndexed(isoUnsignedInput).from(b.inputs), dataInputs = sigma.js.Isos.isoArrayToIndexed(isoDataInput).from(b.dataInputs), - outputs = sigma.js.Isos.isoArrayToIndexed(isoBoxCandidate).from(b.outputCandidates) + outputs = sigma.js.Isos.isoArrayToIndexed(DataIsos.isoBoxCandidate).from(b.outputCandidates) ) } } @@ -426,14 +270,14 @@ object Isos { new ErgoLikeTransaction( inputs = sigma.js.Isos.isoArrayToIndexed(isoSignedInput).to(a.inputs), dataInputs = sigma.js.Isos.isoArrayToIndexed(isoDataInput).to(a.dataInputs), - outputCandidates = sigma.js.Isos.isoArrayToIndexed(isoBox).to(a.outputs), + outputCandidates = sigma.js.Isos.isoArrayToIndexed(sigma.js.Box.isoBox).to(a.outputs), ) } override def from(tx: ErgoLikeTransaction): SignedTransaction = { val inputs = sigma.js.Isos.isoArrayToIndexed(isoSignedInput).from(tx.inputs) val dataInputs = sigma.js.Isos.isoArrayToIndexed(isoDataInput).from(tx.dataInputs) - val outputs = sigma.js.Isos.isoArrayToIndexed(isoBox).from(tx.outputs) + val outputs = sigma.js.Isos.isoArrayToIndexed(sigma.js.Box.isoBox).from(tx.outputs) SignedTransaction(dataInputs, tx.id, inputs, outputs) } } diff --git a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/ProverBuilder.scala b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/ProverBuilder.scala index 12ecf1d03f..7ab95c187e 100644 --- a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/ProverBuilder.scala +++ b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/ProverBuilder.scala @@ -6,6 +6,7 @@ import org.ergoplatform.sdk.SecretString import scala.scalajs.js import scala.scalajs.js.annotation.JSExportTopLevel import Isos._ +import sigma.data.js.{Isos => DataIsos} import sigma.eval.SigmaDsl /** Equivalent of [[sdk.ProverBuilder]] available from JS. @@ -66,10 +67,10 @@ class ProverBuilder(parameters: BlockchainParameters, network: Byte) extends js. */ def withDHTSecret(g: String, h: String, u: String, v: String, x: js.BigInt): ProverBuilder = { _builder.withDHTData( - isoStringToGroupElement.to(g), - isoStringToGroupElement.to(h), - isoStringToGroupElement.to(u), - isoStringToGroupElement.to(v), + DataIsos.isoStringToGroupElement.to(g), + DataIsos.isoStringToGroupElement.to(h), + DataIsos.isoStringToGroupElement.to(u), + DataIsos.isoStringToGroupElement.to(v), SigmaDsl.toBigInteger(sigma.js.Isos.isoBigInt.to(x)) ) this diff --git a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/SigmaProver.scala b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/SigmaProver.scala index 0a6aca4830..693c0717bb 100644 --- a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/SigmaProver.scala +++ b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/SigmaProver.scala @@ -51,8 +51,8 @@ class SigmaProver(_prover: sdk.SigmaProver) extends js.Object { val unreducedTx = sdk.UnreducedTransaction( unsignedTx = isoUnsignedTransaction.to(unsignedTx), boxesToSpend = sigma.js.Isos.isoArrayToIndexed(isoEIP12UnsignedInput).to(boxesToSpend), - dataInputs = sigma.js.Isos.isoArrayToIndexed(isoBox).to(dataInputs), - tokensToBurn = sigma.js.Isos.isoArrayToIndexed(isoToken.andThen(sdk.SdkIsos.isoErgoTokenToPair.inverse)).to(tokensToBurn) + dataInputs = sigma.js.Isos.isoArrayToIndexed(sigma.js.Box.isoBox).to(dataInputs), + tokensToBurn = sigma.js.Isos.isoArrayToIndexed(sigma.data.js.Isos.isoToken.andThen(sdk.SdkIsos.isoErgoTokenToPair.inverse)).to(tokensToBurn) ) val ctx = isoBlockchainStateContext.to(stateCtx) val reducedTx = _prover.reduce(ctx, unreducedTx, baseCost) diff --git a/sdk/js/src/test/scala/org/ergoplatform/sdk/js/IsosSpec.scala b/sdk/js/src/test/scala/org/ergoplatform/sdk/js/IsosSpec.scala index a366e33d3c..a040731b20 100644 --- a/sdk/js/src/test/scala/org/ergoplatform/sdk/js/IsosSpec.scala +++ b/sdk/js/src/test/scala/org/ergoplatform/sdk/js/IsosSpec.scala @@ -10,7 +10,7 @@ import sigma.data.Iso import sigma.interpreter.{ContextExtension, ProverResult} import sigma.js.AvlTree import sigma.{Coll, GroupElement} - +import sigma.data.js.{Isos => DataIsos} import scala.scalajs.js class IsosSpec extends IsosSpecBase with sdk.generators.ObjectGenerators { @@ -31,19 +31,19 @@ class IsosSpec extends IsosSpecBase with sdk.generators.ObjectGenerators { property("Iso.isoStringToGroupElement") { forAll() { (bytes: GroupElement) => - roundtrip(Isos.isoStringToGroupElement)(bytes) + roundtrip(DataIsos.isoStringToGroupElement)(bytes) } } property("Iso.isoBoxId") { forAll(boxIdGen) { (id: BoxId) => - roundtrip(Isos.isoBoxId)(id) + roundtrip(DataIsos.isoBoxId)(id) } } property("Iso.isoHexStringToConstant") { forAll(constantGen, MinSuccessful(100)) { (c: Constant[SType]) => - roundtrip(Isos.isoHexStringToConstant)(c) + roundtrip(DataIsos.isoHexStringToConstant)(c) } } @@ -115,20 +115,20 @@ class IsosSpec extends IsosSpecBase with sdk.generators.ObjectGenerators { property("Iso.isoAmount") { forAll { (c: Long) => - roundtrip(Isos.isoAmount)(c) - Isos.isoAmount.to(js.BigInt(c.toString)) shouldBe c + roundtrip(DataIsos.isoAmount)(c) + DataIsos.isoAmount.to(js.BigInt(c.toString)) shouldBe c } } property("Iso.isoToken") { forAll(tokenIdGen, Arbitrary.arbLong.arbitrary) { (id: TokenId, amount: Long) => - roundtrip(Isos.isoToken)((id, amount)) + roundtrip(DataIsos.isoToken)((id, amount)) } } property("Iso.isoTokenArray") { forAll(ergoBoxTokens(tokensGen.sample.get)) { tokens => - roundtrip(Isos.isoTokenArray)(tokens) + roundtrip(DataIsos.isoTokenArray)(tokens) } } @@ -140,19 +140,19 @@ class IsosSpec extends IsosSpecBase with sdk.generators.ObjectGenerators { property("Iso.isoNonMandatoryRegisters") { forAll(additionalRegistersGen) { (x: AdditionalRegisters) => - roundtrip(Isos.isoNonMandatoryRegisters)(x) + roundtrip(DataIsos.isoNonMandatoryRegisters)(x) } } property("Iso.isoBoxCandidate") { forAll { (box: ErgoBoxCandidate) => - roundtrip(Isos.isoBoxCandidate)(box) + roundtrip(DataIsos.isoBoxCandidate)(box) } } property("Iso.isoBox") { forAll { (b: ErgoBox) => - roundtrip(Isos.isoBox)(b) + roundtrip(sigma.js.Box.isoBox)(b) } } From 1177d09640f4db75708edc70cb8bff805bd6de4c Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 2 May 2024 18:25:37 +0100 Subject: [PATCH 31/65] i956-box-in-register: tests for Box Value toHex/fromHex --- core/js/src/main/scala/sigma/js/Value.scala | 261 -------------------- data/js/src/main/scala/sigma/js/Box.scala | 12 +- data/js/src/main/scala/sigma/js/Value.scala | 17 +- sigma-js/package-lock.json | 4 +- sigma-js/sigmastate-js.d.ts | 10 +- sigma-js/tests/js/Box.spec.js | 29 +++ 6 files changed, 58 insertions(+), 275 deletions(-) delete mode 100644 core/js/src/main/scala/sigma/js/Value.scala create mode 100644 sigma-js/tests/js/Box.spec.js diff --git a/core/js/src/main/scala/sigma/js/Value.scala b/core/js/src/main/scala/sigma/js/Value.scala deleted file mode 100644 index 13b63c2abc..0000000000 --- a/core/js/src/main/scala/sigma/js/Value.scala +++ /dev/null @@ -1,261 +0,0 @@ -package sigma -package js - -import scorex.util.Extensions.{IntOps, LongOps} -import scorex.util.encode.Base16 -import sigma.ast.SType -import sigma.crypto.Platform -import sigma.data._ -import sigma.js.Value.toRuntimeData -import sigma.serialization.{CoreDataSerializer, CoreSerializer} -import sigma.util.Extensions.BigIntOps -import sigma.{Coll, Colls, Evaluation} - -import java.math.BigInteger -import scala.scalajs.js -import scala.scalajs.js.annotation.JSExportTopLevel - -/** - * This class is used to represent any valid value of ErgoScript language. - * Any such value comes equipped with {@link Type} descriptor. - * Note, there is a distinction between JS types and ErgoScript types. - * Each Value instance represents the concrete ErgoScript type given by `tpe`. - * The implementation is based on the pre-defined mapping between JS and ES types. - * This mapping is applied recursively and is given by the following: - * - * JS type | ErgoScript Type - * -------------------------------------- - * Number | Byte - * Number | Short - * Number | Int - * BigInt | Long - * BigInt | BigInt - * array [A, B] | (A, B) - pair - * array [a1, a2 ..] | Coll[A] - collection - * - * @param data JS value wrapped in this value - * @param tpe type descriptor of the ErgoScript type - */ -@JSExportTopLevel("Value") -class Value(val data: Any, val tpe: Type) extends js.Object { - - /** Get Sigma runtime value which can be passed to interpreter, saved in register and - * [[sigma.ast.Constant]] nodes. - */ - final def runtimeData: Any = toRuntimeData(data, tpe.rtype) - - /** - * Encode this value as Base16 hex string. - * 1) it transforms this value into {@link sigma.ast.ConstantNode} of sigma. - * 2) it serializes the constant into byte array using {@link sigmastate.serialization.ConstantSerializer} - * 3) the bytes are encoded using Base16 encoder into string - * - * @return hex string of serialized bytes - */ - def toHex(): String = { - val stype = Evaluation.rtypeToSType(tpe.rtype) - val value = runtimeData.asInstanceOf[SType#WrappedType] - val w = CoreSerializer.startWriter() - w.putType(stype) - CoreDataSerializer.serialize(value, stype, w) - Base16.encode(w.toBytes) - } -} - -@JSExportTopLevel("Value$") -object Value extends js.Object { - /** Maximal positive value of ES type Long */ - val MaxLong = js.BigInt("0x7fffffffffffffff") - - /** Minimal negative value of ES type Long */ - val MinLong = -js.BigInt("0x8000000000000000") - - /** Helper method to get Sigma runtime value which can be passed to interpreter, saved - * in register and [[sigma.ast.Constant]] nodes. - */ - final private[js] def toRuntimeData(data: Any, rtype: RType[_]): Any = rtype match { - case sigma.BooleanType => data - case sigma.ByteType | sigma.ShortType | sigma.IntType => data - case sigma.LongType => java.lang.Long.parseLong(data.asInstanceOf[js.BigInt].toString(10)) - case sigma.BigIntRType => - val v = data.asInstanceOf[js.BigInt] - CBigInt(new BigInteger(v.toString(16), 16)) - case sigma.GroupElementRType => - val ge = data.asInstanceOf[GroupElement] - CGroupElement(ge.point) - case sigma.SigmaPropRType => - val p = data.asInstanceOf[SigmaProp] - CSigmaProp(p.sigmaBoolean) - case sigma.AvlTreeRType => - val t = data.asInstanceOf[AvlTree] - AvlTree.isoAvlTree.to(t) - case ct: CollType[a] => - val xs = data.asInstanceOf[js.Array[Any]] - implicit val cT = ct.tItem.classTag - val items = xs.map(x => toRuntimeData(x, ct.tItem).asInstanceOf[a]).toArray[a] - Colls.fromItems(items:_*)(ct.tItem) - case pt: PairType[a, b] => - val p = data.asInstanceOf[js.Array[Any]] - val x = toRuntimeData(p(0), pt.tFst).asInstanceOf[a] - val y = toRuntimeData(p(1), pt.tSnd).asInstanceOf[b] - (x, y) - case sigma.UnitType => data - case _ => - throw new IllegalArgumentException(s"Unsupported type $rtype") - } - - /** Helper method to extract JS data value from Sigma runtime value. - * This should be inverse to `toRuntimeData`. - * - * @param value runtime value of type given by `rtype` - * @param rtype type descriptor of Sigma runtime value - */ - final def fromRuntimeData(value: Any, rtype: RType[_]): Any = rtype match { - case sigma.BooleanType => value - case sigma.ByteType | sigma.ShortType | sigma.IntType => value - case sigma.LongType => js.BigInt(value.asInstanceOf[Long].toString) - case sigma.BigIntRType => - val hex = value.asInstanceOf[sigma.BigInt].toBigInteger.toString(10) - js.BigInt(hex) - case sigma.GroupElementRType => - val point = value.asInstanceOf[CGroupElement].wrappedValue.asInstanceOf[Platform.Ecp] - new GroupElement(point) - case sigma.SigmaPropRType => - new SigmaProp(value.asInstanceOf[CSigmaProp].wrappedValue) - case sigma.AvlTreeRType => - AvlTree.isoAvlTree.from(value.asInstanceOf[CAvlTree]) - case ct: CollType[a] => - val arr = value.asInstanceOf[Coll[a]].toArray - js.Array(arr.map(x => fromRuntimeData(x, ct.tItem)):_*) - case pt: PairType[a, b] => - val p = value.asInstanceOf[(a, b)] - js.Array(fromRuntimeData(p._1, pt.tFst), fromRuntimeData(p._2, pt.tSnd)) - case sigma.UnitType => value - case _ => - throw new IllegalArgumentException(s"Unsupported type $rtype") - } - - /** Helper method to check validity of JS data value against the given runtime type. - * - * @param data js value - * @param rtype type descriptor of Sigma runtime value - */ - final private def checkJsData[T](data: T, rtype: RType[_]): Any = rtype match { - case sigma.ByteType => data.asInstanceOf[Int].toByteExact - case sigma.ShortType => data.asInstanceOf[Int].toShortExact - case sigma.IntType => data.asInstanceOf[Int].toLong.toIntExact - case sigma.LongType => - val n = data.asInstanceOf[js.BigInt] - if (n < MinLong || n > MaxLong) - throw new ArithmeticException(s"value $n is out of long range") - n - case sigma.BigIntRType => - data.asInstanceOf[js.BigInt] - case sigma.GroupElementRType => - data.asInstanceOf[GroupElement] - case sigma.SigmaPropRType => - data.asInstanceOf[SigmaProp] - case PairType(l, r) => data match { - case arr: js.Array[Any @unchecked] => - checkJsData(arr(0), l) - checkJsData(arr(1), r) - data - case _ => - throw new ArithmeticException(s"$data cannot represent pair value") - } - case CollType(elemType) => data match { - case arr: js.Array[Any @unchecked] => - arr.foreach(x => checkJsData(x, elemType)) - data - case _ => - throw new ArithmeticException(s"$data cannot represent Coll value") - } - case _ => - throw new IllegalArgumentException(s"Unsupported type $rtype") - } - - /** Create Byte value from JS number. */ - def ofByte(n: Int): Value = { - checkJsData(n, Type.Byte.rtype) - new Value(n, Type.Byte) - } - - /** Create Short value from JS number. */ - def ofShort(n: Int): Value = { - checkJsData(n, Type.Short.rtype) - new Value(n, Type.Short) - } - - /** Create Int value from JS number. */ - def ofInt(n: Int): Value = { - checkJsData(n, Type.Int.rtype) - new Value(n, Type.Int) - } - - /** Create Long value from JS BigInt. */ - def ofLong(n: js.BigInt): Value = { - checkJsData(n, Type.Long.rtype) - new Value(n, Type.Long) - } - - /** Create BigInt value from JS BigInt. */ - def ofBigInt(n: js.BigInt): Value = { - checkJsData(n, Type.BigInt.rtype) - new Value(n, Type.BigInt) - } - - /** Creates a Value of GroupElement type from [[sigmastate.crypto.Platform.Point]] hex. - * @param pointHex hex of ASN representation of [[sigmastate.crypto.Platform.Point]] - */ - def ofGroupElement(pointHex: String): Value = { - val ge = GroupElement.fromPointHex(pointHex) - new Value(ge, Type.GroupElement) - } - - /** Creates a Value of SigmaProp type from [[sigmastate.crypto.Platform.Point]] hex. - * @param pointHex hex of ASN representation of [[sigmastate.crypto.Platform.Point]] - */ - def ofSigmaProp(pointHex: String): Value = { - val sp = SigmaProp.fromPointHex(pointHex) - new Value(sp, Type.SigmaProp) - } - - /** Create Pair value from two values. */ - def pairOf(l: Value, r: Value): Value = { - val data = js.Array(l.data, r.data) // the l and r data have been validated - new Value(data, Type.pairType(l.tpe, r.tpe)) - } - - /** Create Coll value from array and element type descriptor. - * @param items collection elements which should be valid JS representation of `elemType` - * @param elemType descriptor of types for collection elements - */ - def collOf(items: js.Array[Any], elemType: Type): Value = { - val t = Type.collType(elemType) - checkJsData(items, t.rtype) - new Value(items, t) - } - - /** - * Creates Value from hex encoded serialized bytes of Constant values. - *

- * In order to create Value you need to provide both value instance and - * Type descriptor. This is similar to how values are represented in sigma - * ConstantNode. Each ConstantNode also have value instance and `tpe: SType` - * descriptor. - * @param hex the string is obtained as hex encoding of serialized ConstantNode. - * (The bytes obtained by ConstantSerializer in sigma) - * @return new deserialized Value instance containing: - * - suitable JS value in its `data` field - * - and [[Type]] descriptor in its `tpe` field - */ - def fromHex(hex: String): Value = { - val bytes = Base16.decode(hex).fold(t => throw t, identity) - val r = CoreSerializer.startReader(bytes) - val stype = r.getType() - val value = CoreDataSerializer.deserialize(stype, r) - val rtype = Evaluation.stypeToRType(stype) - val jsvalue = Value.fromRuntimeData(value, rtype) - new Value(jsvalue, new Type(rtype)) - } -} diff --git a/data/js/src/main/scala/sigma/js/Box.scala b/data/js/src/main/scala/sigma/js/Box.scala index 209e15d489..70155633d5 100644 --- a/data/js/src/main/scala/sigma/js/Box.scala +++ b/data/js/src/main/scala/sigma/js/Box.scala @@ -16,15 +16,15 @@ import scala.scalajs.js.annotation.JSExportTopLevel /** Equivalent of [[sigma.Box]] available from JS. */ @JSExportTopLevel("Box") -class Box(val box: FBox[Amount, NonMandatoryRegisters]) extends js.Object { -} +class Box(val box: FBox[Amount, NonMandatoryRegisters]) extends js.Object -@JSExportTopLevel("Box$") object Box extends js.Object { + /** Represents a box in Fleet SDK. */ + type FleetBox = FBox[commonMod.Amount, NonMandatoryRegisters] /** Converts Fleet box to ErgoBox and back. */ - val isoBox: Iso[FBox[commonMod.Amount, NonMandatoryRegisters], ErgoBox] = new Iso[FBox[commonMod.Amount, NonMandatoryRegisters], ErgoBox] { - override def to(x: FBox[commonMod.Amount, NonMandatoryRegisters]): ErgoBox = { + val isoBox: Iso[FleetBox, ErgoBox] = new Iso[FleetBox, ErgoBox] { + override def to(x: FleetBox): ErgoBox = { val ergoBox = new ErgoBox( value = isoAmount.to(x.value), ergoTree = { @@ -40,7 +40,7 @@ object Box extends js.Object { ergoBox } - override def from(x: ErgoBox): FBox[commonMod.Amount, NonMandatoryRegisters] = { + override def from(x: ErgoBox): FleetBox = { val ergoTree = ErgoTreeSerializer.DefaultSerializer.serializeErgoTree(x.ergoTree) val ergoTreeStr = Base16.encode(ergoTree) val assets = isoTokenArray.from(x.additionalTokens) diff --git a/data/js/src/main/scala/sigma/js/Value.scala b/data/js/src/main/scala/sigma/js/Value.scala index 785f9e04db..fea6cd9b8b 100644 --- a/data/js/src/main/scala/sigma/js/Value.scala +++ b/data/js/src/main/scala/sigma/js/Value.scala @@ -7,9 +7,10 @@ import sigma.ast.SType import sigma.crypto.Platform import sigma.data._ import sigma.js.Value.toRuntimeData -import sigma.serialization.{CoreSerializer, DataSerializer} +import sigma.serialization.{CoreDataSerializer, CoreSerializer, DataSerializer, SigmaSerializer} import sigma.util.Extensions.BigIntOps import sigma.{Coll, Colls, Evaluation} +import sigmastate.fleetSdkCommon.distEsmTypesBoxesMod.{Box => FBox} import java.math.BigInteger import scala.scalajs.js @@ -55,7 +56,7 @@ class Value(val data: Any, val tpe: Type) extends js.Object { def toHex(): String = { val stype = Evaluation.rtypeToSType(tpe.rtype) val value = runtimeData.asInstanceOf[SType#WrappedType] - val w = CoreSerializer.startWriter() + val w = SigmaSerializer.startWriter() w.putType(stype) DataSerializer.serialize(value, stype, w) Base16.encode(w.toBytes) @@ -128,7 +129,8 @@ object Value extends js.Object { case sigma.AvlTreeRType => AvlTree.isoAvlTree.from(value.asInstanceOf[CAvlTree]) case sigma.BoxRType => - AvlTree.isoAvlTree.from(value.asInstanceOf[CAvlTree]) + val fleetBox = Box.isoBox.from(value.asInstanceOf[CBox].wrappedValue) + new Box(fleetBox) case ct: CollType[a] => val arr = value.asInstanceOf[Coll[a]].toArray js.Array(arr.map(x => fromRuntimeData(x, ct.tItem)):_*) @@ -225,6 +227,13 @@ object Value extends js.Object { new Value(sp, Type.SigmaProp) } + /** Creates a Value of Box type from a [[FBox]] instance. + * @param fleetBox a Fleet box to be wrapped in a [[Value]] + */ + def ofBox(fleetBox: Box.FleetBox): Value = { + new Value(new Box(fleetBox), Type.Box) + } + /** Create Pair value from two values. */ def pairOf(l: Value, r: Value): Value = { val data = js.Array(l.data, r.data) // the l and r data have been validated @@ -256,7 +265,7 @@ object Value extends js.Object { */ def fromHex(hex: String): Value = { val bytes = Base16.decode(hex).fold(t => throw t, identity) - val r = CoreSerializer.startReader(bytes) + val r = SigmaSerializer.startReader(bytes) val stype = r.getType() val value = DataSerializer.deserialize(stype, r) val rtype = Evaluation.stypeToRType(stype) diff --git a/sigma-js/package-lock.json b/sigma-js/package-lock.json index 893a0ee141..c34f802f6e 100644 --- a/sigma-js/package-lock.json +++ b/sigma-js/package-lock.json @@ -1,12 +1,12 @@ { "name": "sigmastate-js", - "version": "0.3.0", + "version": "0.4.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "sigmastate-js", - "version": "0.3.0", + "version": "0.4.0", "license": "MIT", "dependencies": { "@fleet-sdk/common": "0.1.3", diff --git a/sigma-js/sigmastate-js.d.ts b/sigma-js/sigmastate-js.d.ts index b70ca39258..53baa3b026 100644 --- a/sigma-js/sigmastate-js.d.ts +++ b/sigma-js/sigmastate-js.d.ts @@ -1,7 +1,7 @@ declare module "sigmastate-js/main" { import { Amount, - Box, + Box as FBox, EIP12UnsignedInput, NonMandatoryRegisters, SignedTransaction, TokenAmount, UnsignedTransaction @@ -173,6 +173,10 @@ declare module "sigmastate-js/main" { valueLengthOpt: number | undefined; } + export declare class Box { + box: FBox; + } + export declare class PreHeader { /** Block version, to be increased on every soft and hardfork. */ version: number; @@ -301,6 +305,8 @@ declare module "sigmastate-js/main" { static ofSigmaProp(pointHex: string): Value; + static ofBox(box: FBox): Value; + static pairOf(left: Value, right: Value): Value<[R, L]>; static collOf(items: T[], elemType: Type): Value; @@ -498,7 +504,7 @@ declare module "sigmastate-js/main" { stateCtx: BlockchainStateContext, unsignedTx: UnsignedTransaction, boxesToSpend: EIP12UnsignedInput[], - dataInputs: Box[], + dataInputs: FBox[], tokensToBurn: TokenAmount[], baseCost: number): ReducedTransaction; diff --git a/sigma-js/tests/js/Box.spec.js b/sigma-js/tests/js/Box.spec.js new file mode 100644 index 0000000000..5782507ae4 --- /dev/null +++ b/sigma-js/tests/js/Box.spec.js @@ -0,0 +1,29 @@ +const {Box$, Value$} = require("sigmastate-js/main"); + +describe("Box", () => { + it("should deserialize from hex", () => { + let boxHex = "63b96000d1968302010100ff83020193040204020100c0843d000401010e32297000800b80f1d56c809a8c6affbed864b87f007f6f007f00ac00018c01c4fdff011088807f0100657f00f9ab0101ff6d6505a4a7b5a2e7a4a4dd3a05feffffffffffffffff01003bd5c630803cfff6c1ff7f7fb980ff136afc011f8080b8b04ad4dbda2d7f4e01" + let deserialized = Value$.fromHex(boxHex); + // console.log(b.data) + let expected = { + additionalRegisters: { + R4: '0101', + R5: '0e32297000800b80f1d56c809a8c6affbed864b87f007f6f007f00ac00018c01c4fdff011088807f0100657f00f9ab0101ff6d65', + R6: '05a4a7b5a2e7a4a4dd3a', + R7: '05feffffffffffffffff01' + }, + assets: [], + boxId: '3a0089be265460e29ca47d26e5b55a6f3e3ffaf5b4aed941410a2437913848ad', + creationHeight: 1000000, + ergoTree: '00d1968302010100ff83020193040204020100', + index: 1, + transactionId: '003bd5c630803cfff6c1ff7f7fb980ff136afc011f8080b8b04ad4dbda2d7f4e', + value: '12345' + } + let fleetBox = deserialized.data.box + expect(fleetBox).toEqual(expected) + + let newBoxValue = Value$.ofBox(fleetBox) + expect(newBoxValue.toHex()).toEqual(boxHex) + }); +}); \ No newline at end of file From 42e79d7887d71904d5c6d13ea8c943d87997628b Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 2 May 2024 18:34:48 +0100 Subject: [PATCH 32/65] i956-box-in-register: cleanup --- sigma-js/tests/js/Box.spec.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sigma-js/tests/js/Box.spec.js b/sigma-js/tests/js/Box.spec.js index 5782507ae4..24238013ba 100644 --- a/sigma-js/tests/js/Box.spec.js +++ b/sigma-js/tests/js/Box.spec.js @@ -1,10 +1,9 @@ const {Box$, Value$} = require("sigmastate-js/main"); describe("Box", () => { - it("should deserialize from hex", () => { + it("should serialize from/to hex", () => { let boxHex = "63b96000d1968302010100ff83020193040204020100c0843d000401010e32297000800b80f1d56c809a8c6affbed864b87f007f6f007f00ac00018c01c4fdff011088807f0100657f00f9ab0101ff6d6505a4a7b5a2e7a4a4dd3a05feffffffffffffffff01003bd5c630803cfff6c1ff7f7fb980ff136afc011f8080b8b04ad4dbda2d7f4e01" let deserialized = Value$.fromHex(boxHex); - // console.log(b.data) let expected = { additionalRegisters: { R4: '0101', From 83a7e701445c53918c877c01d1a93eb5d1d84ac1 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Fri, 3 May 2024 21:09:37 +0100 Subject: [PATCH 33/65] i956-box-in-register: Iso ScalaDoc + imports cleanup --- core/js/src/main/scala/sigma/js/Isos.scala | 3 +++ .../src/main/scala/sigma/data/Iso.scala | 10 +++++-- .../src/main/scala/sigma/data/js/Isos.scala | 16 ++++++------ data/js/src/main/scala/sigma/js/Value.scala | 2 +- .../scala/org/ergoplatform/sdk/js/Isos.scala | 26 +++++++------------ 5 files changed, 29 insertions(+), 28 deletions(-) diff --git a/core/js/src/main/scala/sigma/js/Isos.scala b/core/js/src/main/scala/sigma/js/Isos.scala index b28a3337b8..767a358d62 100644 --- a/core/js/src/main/scala/sigma/js/Isos.scala +++ b/core/js/src/main/scala/sigma/js/Isos.scala @@ -8,6 +8,9 @@ import scala.reflect.ClassTag import scala.scalajs.js import scala.scalajs.js.JSConverters.JSRichOption +/** Definitions of isomorphisms for sigma-core module. + * @see sigma.data.Iso + */ object Isos { implicit def isoUndefOr[A, B](implicit iso: Iso[A, B]): Iso[js.UndefOr[A], Option[B]] = new Iso[js.UndefOr[A], Option[B]] { diff --git a/core/shared/src/main/scala/sigma/data/Iso.scala b/core/shared/src/main/scala/sigma/data/Iso.scala index 9b90d63bb0..0e463bdd04 100644 --- a/core/shared/src/main/scala/sigma/data/Iso.scala +++ b/core/shared/src/main/scala/sigma/data/Iso.scala @@ -7,14 +7,20 @@ import sigma.{Coll, Colls} /** Type-class of isomorphisms between types. * Isomorphism between two types `A` and `B` essentially say that both types * represents the same information (entity) but in a different way. + * + * Each isomorphism defined by two functions: + * - `to: A => B` - conversion from `A` to `B` + * - `from: B => A` - conversion from `B` to `A` + * *

- * The information is not lost so that both are true: + * such that the information is not lost during conversion, so that both are true: * 1) a == from(to(a)) * 2) b == to(from(b)) *

* It is used to define type-full conversions: * - different conversions between Java and Scala data types. - * - conversion between Ergo representations and generated API representations + * - conversion between internal Ergo representations and API representations + * - conversions between exported JS classes and internal Ergo representations */ abstract class Iso[A, B] { def to(a: A): B diff --git a/data/js/src/main/scala/sigma/data/js/Isos.scala b/data/js/src/main/scala/sigma/data/js/Isos.scala index 95bbce8bbe..22300b1fd8 100644 --- a/data/js/src/main/scala/sigma/data/js/Isos.scala +++ b/data/js/src/main/scala/sigma/data/js/Isos.scala @@ -1,15 +1,9 @@ package sigma.data.js -import org.ergoplatform.{ErgoBox, ErgoBoxCandidate} import org.ergoplatform.ErgoBox._ +import org.ergoplatform.{ErgoBox, ErgoBoxCandidate} import scorex.crypto.authds.ADKey -import scorex.util.ModifierId import scorex.util.encode.Base16 -import sigma.{Coll, Colls} -import sigmastate.fleetSdkCommon.distEsmTypesBoxesMod.{Box => FBox} -import sigmastate.fleetSdkCommon.distEsmTypesCommonMod.{Amount, HexString} -import sigmastate.fleetSdkCommon.distEsmTypesRegistersMod.NonMandatoryRegisters -import sigmastate.fleetSdkCommon.{distEsmTypesBoxesMod => boxesMod, distEsmTypesCommonMod => commonMod, distEsmTypesRegistersMod => registersMod, distEsmTypesTokenMod => tokenMod} import sigma.Extensions._ import sigma.ast.syntax.GroupElementConstant import sigma.ast.{Constant, GroupElementConstant, SType} @@ -17,10 +11,16 @@ import sigma.data.Iso.isoStringToArray import sigma.data.{CGroupElement, Digest32Coll, Iso} import sigma.js.GroupElement import sigma.serialization.{ErgoTreeSerializer, ValueSerializer} +import sigma.{Coll, Colls} +import sigmastate.fleetSdkCommon.distEsmTypesCommonMod.HexString +import sigmastate.fleetSdkCommon.distEsmTypesRegistersMod.NonMandatoryRegisters +import sigmastate.fleetSdkCommon.{distEsmTypesBoxesMod => boxesMod, distEsmTypesCommonMod => commonMod, distEsmTypesRegistersMod => registersMod, distEsmTypesTokenMod => tokenMod} import scala.scalajs.js -/** Definitions of isomorphisms for sigma-data module. */ +/** Definitions of isomorphisms for sigma-data module. + * @see sigma.data.Iso + */ object Isos { val isoStringToGroupElement: Iso[String, sigma.GroupElement] = new Iso[String, sigma.GroupElement] { diff --git a/data/js/src/main/scala/sigma/js/Value.scala b/data/js/src/main/scala/sigma/js/Value.scala index fea6cd9b8b..a65156bd43 100644 --- a/data/js/src/main/scala/sigma/js/Value.scala +++ b/data/js/src/main/scala/sigma/js/Value.scala @@ -7,7 +7,7 @@ import sigma.ast.SType import sigma.crypto.Platform import sigma.data._ import sigma.js.Value.toRuntimeData -import sigma.serialization.{CoreDataSerializer, CoreSerializer, DataSerializer, SigmaSerializer} +import sigma.serialization.{DataSerializer, SigmaSerializer} import sigma.util.Extensions.BigIntOps import sigma.{Coll, Colls, Evaluation} import sigmastate.fleetSdkCommon.distEsmTypesBoxesMod.{Box => FBox} diff --git a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala index f4085cf2a9..0f50a52686 100644 --- a/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala +++ b/sdk/js/src/main/scala/org/ergoplatform/sdk/js/Isos.scala @@ -1,36 +1,28 @@ package org.ergoplatform.sdk.js -import org.ergoplatform.ErgoBox._ import org.ergoplatform._ import org.ergoplatform.sdk.ExtendedInputBox -import org.ergoplatform.sdk.JavaHelpers.UniversalConverter import org.ergoplatform.sdk.wallet.protocol.context -import scorex.crypto.authds.ADKey -import scorex.util.ModifierId -import scorex.util.encode.Base16 -import sigma.Extensions.CollBytesOps -import sigma.ast.syntax.GroupElementConstant -import sigma.ast.{Constant, GroupElementConstant, SType} +import sigma.ast.{Constant, SType} +import sigma.data.Iso import sigma.data.Iso.{isoStringToArray, isoStringToColl} -import sigma.data.{CBigInt, CGroupElement, Digest32Coll, Digest32CollRType, Iso} +import sigma.data.js.{Isos => DataIsos} import sigma.interpreter.{ContextExtension, ProverResult} -import sigma.js.{AvlTree, GroupElement} -import sigma.serialization.{ErgoTreeSerializer, ValueSerializer} -import sigma.{Coll, Colls} +import sigma.js.AvlTree import sigmastate.eval.{CHeader, CPreHeader} import sigmastate.fleetSdkCommon.distEsmTypesBoxesMod.Box -import sigmastate.fleetSdkCommon.distEsmTypesCommonMod.HexString import sigmastate.fleetSdkCommon.distEsmTypesRegistersMod.NonMandatoryRegisters import sigmastate.fleetSdkCommon.distEsmTypesTokenMod.TokenAmount import sigmastate.fleetSdkCommon.distEsmTypesTransactionsMod.{SignedTransaction, UnsignedTransaction} -import sigmastate.fleetSdkCommon.{distEsmTypesBoxesMod => boxesMod, distEsmTypesCommonMod => commonMod, distEsmTypesContextExtensionMod => contextExtensionMod, distEsmTypesInputsMod => inputsMod, distEsmTypesProverResultMod => proverResultMod, distEsmTypesRegistersMod => registersMod, distEsmTypesTokenMod => tokenMod} -import sigma.data.js.{Isos => DataIsos} -import java.math.BigInteger +import sigmastate.fleetSdkCommon.{distEsmTypesCommonMod => commonMod, distEsmTypesContextExtensionMod => contextExtensionMod, distEsmTypesInputsMod => inputsMod, distEsmTypesProverResultMod => proverResultMod} + import scala.collection.immutable.ListMap import scala.scalajs.js import scala.scalajs.js.Object -/** Definitions of isomorphisms for sigma-sdk module. */ +/** Definitions of isomorphisms for sigma-sdk module. + * @see sigma.data.Iso + */ object Isos { implicit val isoHeader: Iso[Header, sigma.Header] = new Iso[Header, sigma.Header] { override def to(a: Header): sigma.Header = { From acecce014884395b58fb532d6a095372681f0ae4 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Fri, 3 May 2024 21:52:38 +0100 Subject: [PATCH 34/65] [sigma-js]: bump version 0.4.2 + update sigma-js/README.md --- sigma-js/README.md | 3 ++- sigma-js/package.json | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/sigma-js/README.md b/sigma-js/README.md index ff867e1cb6..c1f30f3497 100644 --- a/sigma-js/README.md +++ b/sigma-js/README.md @@ -46,14 +46,15 @@ with `$` suffix, thus if X is the JS class, then X$ is the JS object, which corr ## The list of modules and their exported classes - [sigma-core module](../core/js) - contains core classes of Sigma.js library - [Type](../core/js/src/main/scala/sigma/js/Type.scala) - - [Value](../core/js/src/main/scala/sigma/js/Value.scala) - [GroupElement](../core/js/src/main/scala/sigma/js/GroupElement.scala) - [SigmaProp](../core/js/src/main/scala/sigma/js/SigmaProp.scala) - [AvlTree](../core/js/src/main/scala/sigma/js/AvlTree.scala) - [sigma-data module](../data/js) - contains classes for working with ErgoTree, addresses and all related serializers - all classes from sigma-core module + - [Value](../data/js/src/main/scala/sigma/js/Value.scala) - [ErgoTree](../data/js/src/main/scala/sigma/ast/js/ErgoTree.scala) + - [Box](../data/js/src/main/scala/sigma/js/Box.scala) - [Address](../data/js/src/main/scala/org/ergoplatform/js/Address.scala) - [Expr](../data/js/src/main/scala/sigma/ast/js/Expr.scala) diff --git a/sigma-js/package.json b/sigma-js/package.json index 77ff920585..f6900571bd 100644 --- a/sigma-js/package.json +++ b/sigma-js/package.json @@ -1,6 +1,6 @@ { "name": "sigmastate-js", - "version": "0.4.0", + "version": "0.4.2", "description": "Sigma.js library", "files": [ "dist/", From 92e2d77aa824e6a5b44d8b52913b6561deab8945 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Mon, 6 May 2024 13:39:05 +0300 Subject: [PATCH 35/65] close #974 : Header.bytes method implementation --- .../src/main/scala/sigma/SigmaDsl.scala | 1 + .../sigma/reflection/ReflectionData.scala | 3 + .../serialization/CoreDataSerializer.scala | 1 - .../scala/org/ergoplatform/ErgoHeader.scala | 12 ++- .../org/ergoplatform/HeaderWithoutPow.scala | 2 +- .../src/main/scala/sigma/ast/methods.scala | 7 +- .../src/main/scala/sigma/data/CHeader.scala | 10 +- .../MethodCallSerializerSpecification.scala | 26 ++++- .../special/sigma/SigmaTestingData.scala | 7 +- .../scala/sigmastate/eval/GraphBuilding.scala | 2 + .../scala/special/sigma/SigmaDslUnit.scala | 1 + .../special/sigma/impl/SigmaDslImpl.scala | 14 +++ .../TestingInterpreterSpecification.scala | 97 +++++++++++-------- .../org/ergoplatform/sdk/JsonCodecs.scala | 4 +- 14 files changed, 127 insertions(+), 60 deletions(-) diff --git a/core/shared/src/main/scala/sigma/SigmaDsl.scala b/core/shared/src/main/scala/sigma/SigmaDsl.scala index a2894515a2..0ac4f266df 100644 --- a/core/shared/src/main/scala/sigma/SigmaDsl.scala +++ b/core/shared/src/main/scala/sigma/SigmaDsl.scala @@ -466,6 +466,7 @@ trait Header { def checkPow: Boolean + def bytes: Coll[Byte] } /** Runtime representation of Context ErgoTree type. diff --git a/core/shared/src/main/scala/sigma/reflection/ReflectionData.scala b/core/shared/src/main/scala/sigma/reflection/ReflectionData.scala index 2a5e74e659..381bd4faf8 100644 --- a/core/shared/src/main/scala/sigma/reflection/ReflectionData.scala +++ b/core/shared/src/main/scala/sigma/reflection/ReflectionData.scala @@ -349,6 +349,9 @@ object ReflectionData { }, mkMethod(clazz, "checkPow", Array[Class[_]]()) { (obj, _) => obj.asInstanceOf[Header].checkPow + }, + mkMethod(clazz, "bytes", Array[Class[_]]()) { (obj, _) => + obj.asInstanceOf[Header].bytes } ) ) diff --git a/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala b/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala index 56872cd68e..0c7a991662 100644 --- a/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala +++ b/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala @@ -69,7 +69,6 @@ class CoreDataSerializer { } // TODO v6.0 : support Option[T] (see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/659) - // TODO v6.0 : support Header case _ => CheckSerializableTypeCode(tpe.typeCode) throw new SerializerException(s"Don't know how to serialize ($v, $tpe)") diff --git a/data/shared/src/main/scala/org/ergoplatform/ErgoHeader.scala b/data/shared/src/main/scala/org/ergoplatform/ErgoHeader.scala index cc678003d6..7d70d67d25 100644 --- a/data/shared/src/main/scala/org/ergoplatform/ErgoHeader.scala +++ b/data/shared/src/main/scala/org/ergoplatform/ErgoHeader.scala @@ -5,7 +5,7 @@ import scorex.crypto.authds.ADDigest import scorex.crypto.hash.{Blake2b256, Digest32} import scorex.util.ModifierId import sigma.Colls -import sigma.crypto.{CryptoConstants, CryptoFacade, EcPointType} +import sigma.crypto.{CryptoConstants, EcPointType} import sigma.serialization.{GroupElementSerializer, SigmaByteReader, SigmaByteWriter, SigmaSerializer} @@ -90,7 +90,7 @@ object AutolykosSolution { * @param votes - votes for changing system parameters * @param _bytes - serialized bytes of the header when not `null` */ -case class ErgoHeader(override val version: ErgoHeader.Version, +class ErgoHeader(override val version: ErgoHeader.Version, override val parentId: ModifierId, override val ADProofsRoot: Digest32, override val stateRoot: ADDigest, //33 bytes! extra byte with tree height here! @@ -99,7 +99,7 @@ case class ErgoHeader(override val version: ErgoHeader.Version, override val nBits: Long, //actually it is unsigned int override val height: Int, override val extensionRoot: Digest32, - powSolution: AutolykosSolution, + val powSolution: AutolykosSolution, override val votes: Array[Byte], //3 bytes override val unparsedBytes: Array[Byte], _bytes: Array[Byte]) extends @@ -116,6 +116,12 @@ case class ErgoHeader(override val version: ErgoHeader.Version, lazy val id = Colls.fromArray(serializedId) + override def hashCode(): Int = id.hashCode() + + override def equals(other: Any): Boolean = other match { + case h: ErgoHeader => h.id == this.id + case _ => false + } } diff --git a/data/shared/src/main/scala/org/ergoplatform/HeaderWithoutPow.scala b/data/shared/src/main/scala/org/ergoplatform/HeaderWithoutPow.scala index 56e2eafb1b..0ea6617b2a 100644 --- a/data/shared/src/main/scala/org/ergoplatform/HeaderWithoutPow.scala +++ b/data/shared/src/main/scala/org/ergoplatform/HeaderWithoutPow.scala @@ -23,7 +23,7 @@ class HeaderWithoutPow(val version: Byte, // 1 byte val votes: Array[Byte], //3 bytes val unparsedBytes: Array[Byte]) { def toHeader(powSolution: AutolykosSolution, bytes: Array[Byte]): ErgoHeader = - ErgoHeader(version, parentId, ADProofsRoot, stateRoot, transactionsRoot, timestamp, + new ErgoHeader(version, parentId, ADProofsRoot, stateRoot, transactionsRoot, timestamp, nBits, height, extensionRoot, powSolution, votes, unparsedBytes, bytes) } diff --git a/data/shared/src/main/scala/sigma/ast/methods.scala b/data/shared/src/main/scala/sigma/ast/methods.scala index 97c2302b2d..07b3bc3b7c 100644 --- a/data/shared/src/main/scala/sigma/ast/methods.scala +++ b/data/shared/src/main/scala/sigma/ast/methods.scala @@ -1457,11 +1457,14 @@ case object SHeaderMethods extends MonoTypeMethods { lazy val powDistanceMethod = propertyCall("powDistance", SBigInt, 14, FixedCost(JitCost(10))) lazy val votesMethod = propertyCall("votes", SByteArray, 15, FixedCost(JitCost(10))) + // methods added in 6.0 below lazy val checkPowMethod = SMethod( this, "checkPow", SFunc(Array(SHeader), SBoolean), 16, GroupGenerator.costKind) // todo: cost .withIRInfo(MethodCallIrBuilder) .withInfo(Xor, "Check PoW of this header") // todo: desc + lazy val bytesMethod = propertyCall("bytes", SByteArray, 17, FixedCost(JitCost(10))) + def checkPow_eval(mc: MethodCall, G: SigmaDslBuilder, header: Header) (implicit E: ErgoTreeEvaluator): Boolean = { E.checkPow_eval(mc, header) @@ -1469,11 +1472,11 @@ case object SHeaderMethods extends MonoTypeMethods { protected override def getMethods() = { if (VersionContext.current.isV6SoftForkActivated) { - // 6.0 : checkPow method added + // 6.0 : checkPow & bytes methods added super.getMethods() ++ Seq( idMethod, versionMethod, parentIdMethod, ADProofsRootMethod, stateRootMethod, transactionsRootMethod, timestampMethod, nBitsMethod, heightMethod, extensionRootMethod, minerPkMethod, powOnetimePkMethod, - powNonceMethod, powDistanceMethod, votesMethod, checkPowMethod) + powNonceMethod, powDistanceMethod, votesMethod, checkPowMethod, bytesMethod) } else { super.getMethods() ++ Seq( idMethod, versionMethod, parentIdMethod, ADProofsRootMethod, stateRootMethod, transactionsRootMethod, diff --git a/data/shared/src/main/scala/sigma/data/CHeader.scala b/data/shared/src/main/scala/sigma/data/CHeader.scala index ed75fee4be..1a0d5b37ed 100644 --- a/data/shared/src/main/scala/sigma/data/CHeader.scala +++ b/data/shared/src/main/scala/sigma/data/CHeader.scala @@ -11,7 +11,7 @@ import sigma.{AvlTree, BigInt, Coll, Colls, GroupElement, Header} * * @see [[Header]] for detailed descriptions */ -class CHeader(val ergoHeader: ErgoHeader) extends Header with WrapperOf[ErgoHeader] { +case class CHeader(ergoHeader: ErgoHeader) extends Header with WrapperOf[ErgoHeader] { /** Bytes representation of ModifierId of this Header */ override lazy val id: Coll[Byte] = ergoHeader.id @@ -81,12 +81,8 @@ class CHeader(val ergoHeader: ErgoHeader) extends Header with WrapperOf[ErgoHead } } - override def hashCode(): Int = id.hashCode() + override def bytes: Coll[Byte] = Colls.fromArray(ergoHeader.bytes) - override def equals(other: Any): Boolean = other match { - case ch: CHeader => ch.id == this.id - case _ => false - } } object CHeader { @@ -115,7 +111,7 @@ object CHeader { powNonce.toArray, powDistance.asInstanceOf[CBigInt].wrappedValue) - val h = ErgoHeader(version, bytesToId(parentId.toArray), Digest32 @@ ADProofsRoot.toArray, + val h = new ErgoHeader(version, bytesToId(parentId.toArray), Digest32 @@ ADProofsRoot.toArray, ADDigest @@ stateRoot.digest.toArray, Digest32 @@ transactionsRoot.toArray, timestamp, nBits, height, Digest32 @@ extensionRoot.toArray, solution, votes.toArray, unparsedBytes.toArray, null) diff --git a/interpreter/shared/src/test/scala/sigma/serialization/MethodCallSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/MethodCallSerializerSpecification.scala index 2332aaccaa..e8a7ba7a2f 100644 --- a/interpreter/shared/src/test/scala/sigma/serialization/MethodCallSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/MethodCallSerializerSpecification.scala @@ -4,9 +4,6 @@ import sigma.VersionContext import sigma.ast._ import sigma.validation.ValidationException -import scala.util.Try - - class MethodCallSerializerSpecification extends SerializationSpecification { property("MethodCall deserialization round trip") { @@ -72,4 +69,27 @@ class MethodCallSerializerSpecification extends SerializationSpecification { ) } + + property("MethodCall deserialization round trip for Header.bytes") { + def code = { + val h = HeaderConstant(headerGen.sample.get) + val expr = MethodCall(h, + SHeaderMethods.bytesMethod, + Vector(), + Map() + ) + roundTripTest(expr) + } + + VersionContext.withVersions(VersionContext.V6SoftForkVersion, 1) { + code + } + + // sigma.serialization.SerializerException: Don't know how to serialize (sigma.data.CHeader@51dbec76, SHeader) + an[SerializerException] should be thrownBy ( + VersionContext.withVersions((VersionContext.V6SoftForkVersion - 1).toByte, 1) { + code + } + ) + } } diff --git a/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala b/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala index d1253d4686..97aa432c51 100644 --- a/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala +++ b/interpreter/shared/src/test/scala/special/sigma/SigmaTestingData.scala @@ -1,6 +1,6 @@ package sigma -import org.ergoplatform.ErgoBox +import org.ergoplatform.{ErgoBox, ErgoHeader} import org.ergoplatform.settings.ErgoAlgos import org.scalacheck.Arbitrary.arbitrary import org.scalacheck.Gen.containerOfN @@ -268,7 +268,10 @@ trait SigmaTestingData extends TestingCommons with ObjectGenerators { val h1: Header = create_h1() - val h2: Header = new CHeader(h1.asInstanceOf[CHeader].wrappedValue.copy(height = 2)) + val eh1 = h1.asInstanceOf[CHeader].ergoHeader + val h2: Header = new CHeader(new ErgoHeader(eh1.version, eh1.parentId, eh1.ADProofsRoot, eh1.stateRoot, + eh1.transactionsRoot, eh1.timestamp, eh1.nBits, 2, eh1.extensionRoot, + eh1.powSolution, eh1.votes, eh1.unparsedBytes, null)) val dlog_instances = new CloneSet(1000, ProveDlog( SigmaDsl.toECPoint(create_ge1()).asInstanceOf[EcPointType] diff --git a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala index a35a44ee23..3657a13a5c 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala @@ -1126,6 +1126,8 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => h.votes case SHeaderMethods.checkPowMethod.name if VersionContext.current.isV6SoftForkActivated => h.checkPow + case SHeaderMethods.bytesMethod.name if VersionContext.current.isV6SoftForkActivated => + h.bytes case _ => throwError } case (g: Ref[SigmaDslBuilder]@unchecked, SGlobalMethods) => method.name match { diff --git a/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala b/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala index d84bf40c4f..3ab2c86efc 100644 --- a/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala +++ b/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala @@ -77,6 +77,7 @@ package sigma { def powDistance: Ref[BigInt]; def votes: Ref[Coll[Byte]] def checkPow: Ref[Boolean] + def bytes: Ref[Coll[Byte]] }; trait Context extends Def[Context] { def OUTPUTS: Ref[Coll[Box]]; diff --git a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala index 100e0777ce..407394001d 100644 --- a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala +++ b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala @@ -1371,6 +1371,13 @@ object Header extends EntityObject("Header") { ArraySeq.empty, true, false, element[Boolean])) } + + override def bytes: Ref[Coll[Byte]] = { + asRep[Coll[Byte]](mkMethodCall(self, + HeaderClass.getMethod("bytes"), + ArraySeq.empty, + true, false, element[Coll[Byte]])) + } } implicit object LiftableHeader @@ -1502,6 +1509,13 @@ object Header extends EntityObject("Header") { ArraySeq.empty, true, true, element[Boolean])) } + + def bytes: Ref[Coll[Byte]] = { + asRep[Coll[Byte]](mkMethodCall(source, + HeaderClass.getMethod("bytes"), + ArraySeq.empty, + true, true, element[Coll[Byte]])) + } } // entityUnref: single unref method for each type family diff --git a/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala b/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala index 4948f70c23..a9c8fff5f8 100644 --- a/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/TestingInterpreterSpecification.scala @@ -10,10 +10,9 @@ import io.circe.parser.parse import org.ergoplatform._ import org.ergoplatform.sdk.JsonCodecs import org.scalatest.BeforeAndAfterAll -import scorex.util.encode.Base58 +import scorex.util.encode.{Base16, Base58} import sigma.Colls import sigma.VersionContext.V6SoftForkVersion -import sigma.crypto.CryptoConstants import sigma.data.{CAND, CAvlTree, ProveDlog, SigmaBoolean, TrivialProp} import sigma.interpreter.ContextExtension import sigma.util.Extensions.IntOps @@ -36,47 +35,47 @@ class TestingInterpreterSpecification extends CompilerTestingCommons lazy val prover = new ErgoLikeTestProvingInterpreter() lazy val verifier = new ErgoLikeTestInterpreter - - def testingContext(h: Int = 614401) = { - // valid header from Ergo blockchain - val headerJson = - """ - |{ - | "extensionId" : "00cce45975d87414e8bdd8146bc88815be59cd9fe37a125b5021101e05675a18", - | "votes" : "000000", - | "timestamp" : 4928911477310178288, - | "size" : 223, - | "unparsedBytes" : "", - | "stateRoot" : { - | "digest" : "5c8c00b8403d3701557181c8df800001b6d5009e2201c6ff807d71808c00019780", - | "treeFlags" : "0", - | "keyLength" : "32" - | }, - | "height" : 614400, - | "nBits" : 37748736, - | "version" : 2, - | "id" : "5603a937ec1988220fc44fb5022fb82d5565b961f005ebb55d85bd5a9e6f801f", - | "adProofsRoot" : "5d3f80dcff7f5e7f59007294c180808d0158d1ff6ba10000f901c7f0ef87dcff", - | "transactionsRoot" : "f17fffacb6ff7f7f1180d2ff7f1e24ffffe1ff937f807f0797b9ff6ebdae007e", - | "extensionRoot" : "1480887f80007f4b01cf7f013ff1ffff564a0000b9a54f00770e807f41ff88c0", - | "minerPk" : "03bedaee069ff4829500b3c07c4d5fe6b3ea3d3bf76c5c28c1d4dcdb1bed0ade0c", - | "powOnetimePk" : "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", - | "powNonce" : "0000000000003105", - | "powDistance" : 0, - | "adProofsId" : "dec129290a763f4de41f04e87e2b661dd59758af6bdd00dd51f5d97c3a8cb9b5", - | "transactionsId" : "eba1dd82cf51147232e09c1f72b37c554c30f63274d5093bff36849a83472a42", - | "parentId" : "ac2101807f0000ca01ff0119db227f202201007f62000177a080005d440896d0" - |} - |""".stripMargin - - object JsonCodecs extends JsonCodecs - val header1 = JsonCodecs.headerDecoder.decodeJson(parse(headerJson).toOption.get).toOption.get + // valid header from Ergo blockchain + val headerJson = + """ + |{ + | "extensionId" : "00cce45975d87414e8bdd8146bc88815be59cd9fe37a125b5021101e05675a18", + | "votes" : "000000", + | "timestamp" : 4928911477310178288, + | "size" : 223, + | "unparsedBytes" : "", + | "stateRoot" : { + | "digest" : "5c8c00b8403d3701557181c8df800001b6d5009e2201c6ff807d71808c00019780", + | "treeFlags" : "0", + | "keyLength" : "32" + | }, + | "height" : 614400, + | "nBits" : 37748736, + | "version" : 2, + | "id" : "5603a937ec1988220fc44fb5022fb82d5565b961f005ebb55d85bd5a9e6f801f", + | "adProofsRoot" : "5d3f80dcff7f5e7f59007294c180808d0158d1ff6ba10000f901c7f0ef87dcff", + | "transactionsRoot" : "f17fffacb6ff7f7f1180d2ff7f1e24ffffe1ff937f807f0797b9ff6ebdae007e", + | "extensionRoot" : "1480887f80007f4b01cf7f013ff1ffff564a0000b9a54f00770e807f41ff88c0", + | "minerPk" : "03bedaee069ff4829500b3c07c4d5fe6b3ea3d3bf76c5c28c1d4dcdb1bed0ade0c", + | "powOnetimePk" : "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + | "powNonce" : "0000000000003105", + | "powDistance" : 0, + | "adProofsId" : "dec129290a763f4de41f04e87e2b661dd59758af6bdd00dd51f5d97c3a8cb9b5", + | "transactionsId" : "eba1dd82cf51147232e09c1f72b37c554c30f63274d5093bff36849a83472a42", + | "parentId" : "ac2101807f0000ca01ff0119db227f202201007f62000177a080005d440896d0" + |} + |""".stripMargin + + object JsonCodecs extends JsonCodecs + val contextHeader = JsonCodecs.headerDecoder.decodeJson(parse(headerJson).toOption.get).toOption.get + + def testingContext(h: Int = 614401) = { val boxesToSpend = IndexedSeq(fakeSelf) val preHeader = CPreHeader(activatedVersionInTests, - parentId = header1.id, + parentId = contextHeader.id, timestamp = 3, nBits = 0, height = h, @@ -85,7 +84,7 @@ class TestingInterpreterSpecification extends CompilerTestingCommons ) new ErgoLikeContext( - header1.stateRoot.asInstanceOf[CAvlTree].treeData, Colls.fromArray(Array(header1)), + contextHeader.stateRoot.asInstanceOf[CAvlTree].treeData, Colls.fromArray(Array(contextHeader)), preHeader, noBoxes, boxesToSpend, ErgoLikeTransaction(IndexedSeq.empty, IndexedSeq.empty), boxesToSpend.indexOf(fakeSelf), ContextExtension.empty, vs, DefaultEvalSettings.scriptCostLimitInEvaluator, @@ -455,6 +454,26 @@ class TestingInterpreterSpecification extends CompilerTestingCommons } } + property("bytes") { + + val headerBytes = Base16.encode(contextHeader.bytes.toArray) + + // checking hash of bytes(id) against known value + val source = s""" { + | val h = CONTEXT.headers(0) + | h.bytes == fromBase16("$headerBytes") && + | blake2b256(h.bytes) == h.id && + | h.id == fromBase16("5603a937ec1988220fc44fb5022fb82d5565b961f005ebb55d85bd5a9e6f801f") + | } + | """.stripMargin + + if (activatedVersionInTests < V6SoftForkVersion) { + an [sigmastate.exceptions.MethodNotFound] should be thrownBy testEval(source) + } else { + testEval(source) + } + } + override protected def afterAll(): Unit = { } diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/JsonCodecs.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/JsonCodecs.scala index f3ece3a894..e10c2a0f9b 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/JsonCodecs.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/JsonCodecs.scala @@ -20,7 +20,7 @@ import sigma.serialization.{ErgoTreeSerializer, ValueSerializer} import sigma.validation.SigmaValidationSettings import sigma.{AnyValue, Coll, Colls, Header, PreHeader, SigmaException} import sigmastate.eval.{CPreHeader, _} -import sigmastate.utils.Helpers._ +import sigmastate.utils.Helpers._ // required for Scala 2.11 import java.math.BigInteger import scala.collection.mutable @@ -148,7 +148,7 @@ trait JsonCodecs { powDistance <- cursor.downField("powDistance").as[sigma.BigInt] votes <- cursor.downField("votes").as[Coll[Byte]] unparsedBytes <- cursor.downField("unparsedBytes").as[Option[Coll[Byte]]] - } yield new CHeader(id, version, parentId, adProofsRoot, stateRoot, transactionsRoot, timestamp, nBits, + } yield CHeader(id, version, parentId, adProofsRoot, stateRoot, transactionsRoot, timestamp, nBits, height, extensionRoot, SigmaDsl.decodePoint(minerPk), SigmaDsl.decodePoint(powOnetimePk), powNonce, powDistance, votes, unparsedBytes.getOrElse(Colls.emptyColl)) }) From 2ad11dfcbbf1dd25df1705ba565289516e222466 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 9 May 2024 20:13:58 +0100 Subject: [PATCH 36/65] i966-template-compiler: use default values of parameters in compiler env --- .../sigmastate/lang/ContractParser.scala | 6 +- .../sigmastate/lang/ContractParserSpec.scala | 4 +- .../lang/SigmaTemplateCompiler.scala | 12 ++- .../lang/SigmaTemplateCompilerTest.scala | 83 +++++++++++++++++-- 4 files changed, 89 insertions(+), 16 deletions(-) diff --git a/parsers/shared/src/main/scala/sigmastate/lang/ContractParser.scala b/parsers/shared/src/main/scala/sigmastate/lang/ContractParser.scala index 87dd20ab0c..69136c5a91 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/ContractParser.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/ContractParser.scala @@ -3,7 +3,7 @@ package sigmastate.lang import fastparse._ import fastparse.NoWhitespace._ import SigmaParser._ -import sigma.ast.SType +import sigma.ast.{Constant, SType} import sigma.ast.syntax.SValue import sigmastate.lang.parsers.Basic @@ -105,7 +105,7 @@ object ContractDoc { * @param tpe The type of the parameter. * @param defaultValue The default value assigned to the parameter, if it exists. */ -case class ContractParam(name: String, tpe: SType, defaultValue: Option[SType#WrappedType]) +case class ContractParam(name: String, tpe: SType, defaultValue: Option[Constant[SType]]) /** * Represents the signature of a contract. @@ -187,7 +187,7 @@ object ContractParser { def annotation[_: P] = P("@contract") - def paramDefault[_: P] = P(WL.? ~ `=` ~ WL.? ~ ExprLiteral).map(s => s.asWrappedType) + def paramDefault[_: P] = P(WL.? ~ `=` ~ WL.? ~ ExprLiteral) def param[_: P] = P(WL.? ~ Id.! ~ ":" ~ Type ~ paramDefault.?).map(s => ContractParam(s._1, s._2, s._3)) diff --git a/parsers/shared/src/test/scala/sigmastate/lang/ContractParserSpec.scala b/parsers/shared/src/test/scala/sigmastate/lang/ContractParserSpec.scala index 9a412b7100..a4c535ac8f 100644 --- a/parsers/shared/src/test/scala/sigmastate/lang/ContractParserSpec.scala +++ b/parsers/shared/src/test/scala/sigmastate/lang/ContractParserSpec.scala @@ -34,8 +34,8 @@ class ContractParserSpec extends AnyPropSpec with ScalaCheckPropertyChecks with parsed.name shouldBe "contractName" parsed.params should contain theSameElementsInOrderAs Seq( - ContractParam("p1", SInt, Some(IntConstant(5).asWrappedType)), - ContractParam("p2", SString, Some(StringConstant("default string").asWrappedType)), + ContractParam("p1", SInt, Some(IntConstant(5))), + ContractParam("p2", SString, Some(StringConstant("default string"))), ContractParam("param3", SLong, None) ) } diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala index ec94bdfd3a..c751962826 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala @@ -2,9 +2,9 @@ package sigmastate.lang import fastparse.Parsed import org.ergoplatform.sdk.ContractTemplate -import sigmastate.eval.CompiletimeIRContext +import sigmastate.eval.{CompiletimeIRContext, msgCostLimitError} import org.ergoplatform.sdk.Parameter -import sigma.ast.SourceContext +import sigma.ast.{Constant, SType, SourceContext} import sigma.ast.syntax.SValue import sigmastate.interpreter.Interpreter.ScriptEnv import sigmastate.lang.parsers.ParserException @@ -23,7 +23,11 @@ class SigmaTemplateCompiler(networkPrefix: Byte) { ContractParser.parse(source) match { case Parsed.Success(template, _) => { implicit val ir = new CompiletimeIRContext - val result = sigmaCompiler.compileParsed(env, template.body) + val mergedEnv = template.signature.params + .collect { case ContractParam(name, tpe, Some(defaultValue)) => + name -> defaultValue + }.toMap ++ env + val result = sigmaCompiler.compileParsed(mergedEnv, template.body) assemble(template, result.buildTree) } case f: Parsed.Failure => @@ -46,7 +50,7 @@ class SigmaTemplateCompiler(networkPrefix: Byte) { name = parsed.signature.name, description = parsed.docs.description, constTypes = constTypes.toIndexedSeq, - constValues = constValues, + constValues = constValues.map(_.map(_.map(_.value))), parameters = contractParams.toIndexedSeq, expressionTree = expr.toSigmaProp ) diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala index df8f644172..168815452d 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala @@ -2,13 +2,14 @@ package sigmastate.lang import org.ergoplatform.ErgoAddressEncoder import org.ergoplatform.sdk.Parameter -import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -import sigma.ast.{IntConstant, SInt, SLong, SString, StringConstant} +import sigma.ast.{SBoolean, SInt, SLong, SString} +import sigma.exceptions.TyperException import sigmastate.eval.CompiletimeIRContext +import sigmastate.interpreter.Interpreter.ScriptEnv -class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyChecks with Matchers { +class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyChecks with LangTests { property("compiles full contract template") { val source = """/** This is my contracts description. @@ -36,8 +37,8 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck ) template.constTypes should contain theSameElementsInOrderAs Seq(SInt, SString, SLong) template.constValues.get should contain theSameElementsInOrderAs IndexedSeq( - Some(IntConstant(5).asWrappedType), - Some(StringConstant("default string").asWrappedType), + Some(5), + Some("default string"), None ) @@ -73,8 +74,8 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck ) template.constTypes should contain theSameElementsInOrderAs Seq(SInt, SString) template.constValues.get should contain theSameElementsInOrderAs IndexedSeq( - Some(IntConstant(5).asWrappedType), - Some(StringConstant("default string").asWrappedType) + Some(5), + Some("default string") ) val sigmaCompiler = new SigmaCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) @@ -83,6 +84,74 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck template.expressionTree shouldBe result.buildTree } + + property("uses default value from parameter definition") { + val source = + """/**/ + |@contract def contractName(p: Boolean = true) = sigmaProp(p) + |""".stripMargin + val compiler = SigmaTemplateCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) + val template = compiler.compile(Map.empty, source) + + template.parameters should contain theSameElementsInOrderAs IndexedSeq( + Parameter("p", "", 0), + ) + template.constTypes should contain theSameElementsInOrderAs Seq(SBoolean) + template.constValues.get should contain theSameElementsInOrderAs IndexedSeq( + Some(true), + ) + + val sigmaCompiler = new SigmaCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) + implicit val ir = new CompiletimeIRContext + val result = sigmaCompiler.compile(Map("p" -> true), "sigmaProp(p)") + + template.expressionTree shouldBe result.buildTree + } + + property("uses given environment when provided (overriding default value)") { + val explicitEnv = Map("low" -> 10, "high" -> 100) + val source = + """/**/ + |@contract def contractName(low: Int = 0, high: Int) = sigmaProp(low < HEIGHT && HEIGHT < high) + |""".stripMargin + val compiler = SigmaTemplateCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) + val template = compiler.compile(explicitEnv, source) + + template.parameters should contain theSameElementsInOrderAs IndexedSeq( + Parameter("low", "", 0), + Parameter("high", "", 1), + ) + template.constTypes should contain theSameElementsInOrderAs Seq(SInt, SInt) + // check parsed default values + template.constValues.get should contain theSameElementsInOrderAs IndexedSeq( + Some(0), + None, + ) + + val sigmaCompiler = new SigmaCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) + implicit val ir = new CompiletimeIRContext + val result = sigmaCompiler.compile( + env = explicitEnv, + code = "sigmaProp(low < HEIGHT && HEIGHT < high)" + ) + + template.expressionTree shouldBe result.buildTree + } + + property("fails when constant value in not provided") { + // NOTE: parameter `high` without default value */ + val source = + """/**/ + |@contract def contractName(low: Int = 0, high: Int) = sigmaProp(low < HEIGHT && HEIGHT < high) + |""".stripMargin + val compiler = SigmaTemplateCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) + val env: ScriptEnv = Map.empty // no value for "high" + assertExceptionThrown( + compiler.compile(env, source), + exceptionLike[TyperException]("Cannot assign type for variable 'high' because it is not found in env") + ) + } + } From 98fd5b7d0bf93fc87ebc4a8e98d7e31eefa8c678 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 9 May 2024 20:20:30 +0100 Subject: [PATCH 37/65] i966-template-compiler: fix type of ContractParam field --- .../src/main/scala/sigmastate/lang/ContractParser.scala | 4 ++-- .../src/test/scala/sigmastate/lang/ContractParserSpec.scala | 5 +++-- .../main/scala/sigmastate/lang/SigmaTemplateCompiler.scala | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/parsers/shared/src/main/scala/sigmastate/lang/ContractParser.scala b/parsers/shared/src/main/scala/sigmastate/lang/ContractParser.scala index 69136c5a91..a192a789b9 100644 --- a/parsers/shared/src/main/scala/sigmastate/lang/ContractParser.scala +++ b/parsers/shared/src/main/scala/sigmastate/lang/ContractParser.scala @@ -105,7 +105,7 @@ object ContractDoc { * @param tpe The type of the parameter. * @param defaultValue The default value assigned to the parameter, if it exists. */ -case class ContractParam(name: String, tpe: SType, defaultValue: Option[Constant[SType]]) +case class ContractParam(name: String, tpe: SType, defaultValue: Option[SType#WrappedType]) /** * Represents the signature of a contract. @@ -189,7 +189,7 @@ object ContractParser { def paramDefault[_: P] = P(WL.? ~ `=` ~ WL.? ~ ExprLiteral) - def param[_: P] = P(WL.? ~ Id.! ~ ":" ~ Type ~ paramDefault.?).map(s => ContractParam(s._1, s._2, s._3)) + def param[_: P] = P(WL.? ~ Id.! ~ ":" ~ Type ~ paramDefault.?).map(s => ContractParam(s._1, s._2, s._3.map(_.value))) def params[_: P] = P("(" ~ param.rep(1, ",").? ~ ")") } diff --git a/parsers/shared/src/test/scala/sigmastate/lang/ContractParserSpec.scala b/parsers/shared/src/test/scala/sigmastate/lang/ContractParserSpec.scala index a4c535ac8f..bce252d866 100644 --- a/parsers/shared/src/test/scala/sigmastate/lang/ContractParserSpec.scala +++ b/parsers/shared/src/test/scala/sigmastate/lang/ContractParserSpec.scala @@ -3,6 +3,7 @@ package sigmastate.lang import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import sigma.ast.SType.AnyOps import sigma.ast._ class ContractParserSpec extends AnyPropSpec with ScalaCheckPropertyChecks with Matchers { @@ -34,8 +35,8 @@ class ContractParserSpec extends AnyPropSpec with ScalaCheckPropertyChecks with parsed.name shouldBe "contractName" parsed.params should contain theSameElementsInOrderAs Seq( - ContractParam("p1", SInt, Some(IntConstant(5))), - ContractParam("p2", SString, Some(StringConstant("default string"))), + ContractParam("p1", SInt, Some(5.asWrappedType)), + ContractParam("p2", SString, Some("default string".asWrappedType)), ContractParam("param3", SLong, None) ) } diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala index c751962826..b124684d50 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala @@ -50,7 +50,7 @@ class SigmaTemplateCompiler(networkPrefix: Byte) { name = parsed.signature.name, description = parsed.docs.description, constTypes = constTypes.toIndexedSeq, - constValues = constValues.map(_.map(_.map(_.value))), + constValues = constValues, parameters = contractParams.toIndexedSeq, expressionTree = expr.toSigmaProp ) From 232c25d56ccd2ed035bbe55a426a7a59d96445b7 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 9 May 2024 22:16:52 +0100 Subject: [PATCH 38/65] i966-template-compiler: fix for Scala 2.11 --- .../scala/sigmastate/lang/SigmaTemplateCompilerTest.scala | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala index 168815452d..82a080cf1a 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala @@ -94,11 +94,11 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck val template = compiler.compile(Map.empty, source) template.parameters should contain theSameElementsInOrderAs IndexedSeq( - Parameter("p", "", 0), + Parameter("p", "", 0) ) template.constTypes should contain theSameElementsInOrderAs Seq(SBoolean) template.constValues.get should contain theSameElementsInOrderAs IndexedSeq( - Some(true), + Some(true) ) val sigmaCompiler = new SigmaCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) @@ -119,13 +119,13 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck template.parameters should contain theSameElementsInOrderAs IndexedSeq( Parameter("low", "", 0), - Parameter("high", "", 1), + Parameter("high", "", 1) ) template.constTypes should contain theSameElementsInOrderAs Seq(SInt, SInt) // check parsed default values template.constValues.get should contain theSameElementsInOrderAs IndexedSeq( Some(0), - None, + None ) val sigmaCompiler = new SigmaCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) From eb6270c88e5687a6d0b88000b05bee311b7d3fa5 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Sun, 12 May 2024 12:44:41 +0100 Subject: [PATCH 39/65] i966-template-compiler: create ConstantPlaceholder for each parameter in the compiled expression --- .../scala/sigmastate/eval/GraphBuilding.scala | 14 ++++ .../scala/sigmastate/eval/TreeBuilding.scala | 4 ++ .../scala/sigmastate/lang/SigmaCompiler.scala | 10 ++- .../lang/SigmaTemplateCompiler.scala | 23 +++---- .../scala/sigmastate/lang/SigmaTyper.scala | 8 ++- .../lang/SigmaTemplateCompilerTest.scala | 67 ++++++++----------- .../sigmastate/lang/SigmaTyperTest.scala | 6 +- 7 files changed, 73 insertions(+), 59 deletions(-) diff --git a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala index 5ddcdfa946..4a126754a5 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala @@ -381,6 +381,18 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => def error(msg: String) = throw new GraphBuildingException(msg, None) def error(msg: String, srcCtx: Option[SourceContext]) = throw new GraphBuildingException(msg, srcCtx) + /** Graph node to represent a placeholder of a constant in ErgoTree. + * @param id Zero based index in ErgoTree.constants array. + * @param resultType type descriptor of the constant value. + */ + case class ConstantPlaceholder[T](id: Int, resultType: Elem[T]) extends Def[T] + + /** Smart constructor method for [[ConstantPlaceholder]], should be used instead of the + * class constructor. + */ + @inline def constantPlaceholder[T](id: Int, eT: Elem[T]): Ref[T] = ConstantPlaceholder(id, eT) + + /** Translates the given typed expression to IR graph representing a function from * Context to some type T. * @param env contains values for each named constant used @@ -465,6 +477,8 @@ trait GraphBuilding extends SigmaLibrary { IR: IRContext => val resV = toRep(v)(e) resV } + case sigma.ast.ConstantPlaceholder(id, tpe) => + constantPlaceholder(id, stypeToElem(tpe)) case sigma.ast.Context => ctx case Global => sigmaDslBuilder case Height => ctx.HEIGHT diff --git a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala index 27f659c1ed..11ae0b85f4 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala @@ -183,6 +183,10 @@ trait TreeBuilding extends SigmaLibrary { IR: IRContext => case None => mkConstant[tpe.type](x.asInstanceOf[tpe.WrappedType], tpe) } + case Def(IR.ConstantPlaceholder(id, elem)) => + val tpe = elemToSType(elem) + mkConstantPlaceholder[tpe.type](id, tpe) + case Def(wc: LiftedConst[a,_]) => val tpe = elemToSType(s.elem) mkConstant[tpe.type](wc.constValue.asInstanceOf[tpe.WrappedType], tpe) diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala index 849167e159..3e83aa866c 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala @@ -72,7 +72,8 @@ class SigmaCompiler private(settings: CompilerSettings) { val predefinedFuncRegistry = new PredefinedFuncRegistry(builder) val binder = new SigmaBinder(env, builder, networkPrefix, predefinedFuncRegistry) val bound = binder.bind(parsed) - val typer = new SigmaTyper(builder, predefinedFuncRegistry, settings.lowerMethodCalls) + val typeEnv = env.collect { case (k, v: SType) => k -> v } + val typer = new SigmaTyper(builder, predefinedFuncRegistry, typeEnv, settings.lowerMethodCalls) val typed = typer.typecheck(bound) typed } @@ -91,7 +92,12 @@ class SigmaCompiler private(settings: CompilerSettings) { /** Compiles the given typed expression. */ def compileTyped(env: ScriptEnv, typedExpr: SValue)(implicit IR: IRContext): CompilerResult[IR.type] = { - val compiledGraph = IR.buildGraph(env, typedExpr) + val placeholdersEnv = env + .collect { case (name, t: SType) => name -> t } + .zipWithIndex + .map { case ((name, t), index) => name -> ConstantPlaceholder(index, t) } + .toMap + val compiledGraph = IR.buildGraph(env ++ placeholdersEnv, typedExpr) val compiledTree = IR.buildTree(compiledGraph) CompilerResult(env, "", compiledGraph, compiledTree) } diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala index b124684d50..f77735118c 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala @@ -1,12 +1,10 @@ package sigmastate.lang import fastparse.Parsed -import org.ergoplatform.sdk.ContractTemplate -import sigmastate.eval.{CompiletimeIRContext, msgCostLimitError} -import org.ergoplatform.sdk.Parameter -import sigma.ast.{Constant, SType, SourceContext} +import org.ergoplatform.sdk.{ContractTemplate, Parameter} +import sigma.ast.SourceContext import sigma.ast.syntax.SValue -import sigmastate.interpreter.Interpreter.ScriptEnv +import sigmastate.eval.CompiletimeIRContext import sigmastate.lang.parsers.ParserException /** Compiler which compiles Ergo contract templates into a [[ContractTemplate]]. */ @@ -19,17 +17,14 @@ class SigmaTemplateCompiler(networkPrefix: Byte) { * @param source The ErgoScript contract source code. * @return The contract template. */ - def compile(env: ScriptEnv, source: String): ContractTemplate = { + def compile(source: String): ContractTemplate = { ContractParser.parse(source) match { - case Parsed.Success(template, _) => { + case Parsed.Success(parsedTemplate, _) => implicit val ir = new CompiletimeIRContext - val mergedEnv = template.signature.params - .collect { case ContractParam(name, tpe, Some(defaultValue)) => - name -> defaultValue - }.toMap ++ env - val result = sigmaCompiler.compileParsed(mergedEnv, template.body) - assemble(template, result.buildTree) - } + val parEnv = parsedTemplate.signature.params.map { p => p.name -> p.tpe }.toMap + val result = sigmaCompiler.compileParsed(parEnv, parsedTemplate.body) + assemble(parsedTemplate, result.buildTree) + case f: Parsed.Failure => throw new ParserException(s"Contract template syntax error: $f", Some(SourceContext.fromParserFailure(f))) } diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala index 7fd6dadd45..857ed66338 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala @@ -1,6 +1,5 @@ package sigmastate.lang -import org.ergoplatform._ import sigma.ast.SCollection.{SBooleanArray, SByteArray} import sigma.ast._ import sigma.ast.syntax.SValue @@ -19,6 +18,7 @@ import scala.collection.mutable.ArrayBuffer */ class SigmaTyper(val builder: SigmaBuilder, predefFuncRegistry: PredefinedFuncRegistry, + typeEnv: Map[String, SType], lowerMethodCalls: Boolean) { import SigmaTyper._ import builder._ @@ -28,8 +28,10 @@ class SigmaTyper(val builder: SigmaBuilder, import SType.tT - private val predefinedEnv: Map[String, SType] = - predefFuncRegistry.funcs.map { case (k, f) => k -> f.declaration.tpe }.toMap + private val predefinedEnv: Map[String, SType] = { + val predefFuncs = predefFuncRegistry.funcs.map { case (k, f) => k -> f.declaration.tpe }.toMap + predefFuncs ++ typeEnv + } private def processGlobalMethod(srcCtx: Nullable[SourceContext], method: SMethod, diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala index 82a080cf1a..a0f9c7d8aa 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala @@ -4,12 +4,14 @@ import org.ergoplatform.ErgoAddressEncoder import org.ergoplatform.sdk.Parameter import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -import sigma.ast.{SBoolean, SInt, SLong, SString} +import sigma.ast.{BinAnd, BoolToSigmaProp, ConstantPlaceholder, Height, LT, SBoolean, SInt, SLong, SString, TrueLeaf} import sigma.exceptions.TyperException -import sigmastate.eval.CompiletimeIRContext +import sigmastate.helpers.SigmaPPrint import sigmastate.interpreter.Interpreter.ScriptEnv class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyChecks with LangTests { + val templateCompiler = SigmaTemplateCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) + property("compiles full contract template") { val source = """/** This is my contracts description. @@ -25,8 +27,7 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck |@contract def contractName(p1: Int = 5, p2: String = "default string", param3: Long) = { | sigmaProp(true) |}""".stripMargin - val compiler = SigmaTemplateCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) - val template = compiler.compile(Map.empty, source) + val template = templateCompiler.compile(source) template.name shouldBe "contractName" template.description shouldBe "This is my contracts description. Here is another line describing what it does in more detail." @@ -42,11 +43,8 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck None ) - val sigmaCompiler = new SigmaCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) - implicit val ir = new CompiletimeIRContext - val result = sigmaCompiler.compile(Map.empty, "{ sigmaProp(true) }") - - template.expressionTree shouldBe result.buildTree + val expectedExpr = BoolToSigmaProp(TrueLeaf) + template.expressionTree shouldBe expectedExpr } property("compiles contract template without braces") { @@ -63,8 +61,7 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck |*/ |@contract def contractName(p1: Int = 5, p2: String = "default string") = sigmaProp(true) |""".stripMargin - val compiler = SigmaTemplateCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) - val template = compiler.compile(Map.empty, source) + val template = templateCompiler.compile(source) template.name shouldBe "contractName" template.description shouldBe "This is my contracts description. Here is another line describing what it does in more detail." @@ -78,11 +75,8 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck Some("default string") ) - val sigmaCompiler = new SigmaCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) - implicit val ir = new CompiletimeIRContext - val result = sigmaCompiler.compile(Map.empty, "sigmaProp(true)") - - template.expressionTree shouldBe result.buildTree + val expectedExpr = BoolToSigmaProp(TrueLeaf) + template.expressionTree shouldBe expectedExpr } property("uses default value from parameter definition") { @@ -90,8 +84,7 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck """/**/ |@contract def contractName(p: Boolean = true) = sigmaProp(p) |""".stripMargin - val compiler = SigmaTemplateCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) - val template = compiler.compile(Map.empty, source) + val template = templateCompiler.compile(source) template.parameters should contain theSameElementsInOrderAs IndexedSeq( Parameter("p", "", 0) @@ -101,21 +94,16 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck Some(true) ) - val sigmaCompiler = new SigmaCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) - implicit val ir = new CompiletimeIRContext - val result = sigmaCompiler.compile(Map("p" -> true), "sigmaProp(p)") - - template.expressionTree shouldBe result.buildTree + val expectedExpr = BoolToSigmaProp(ConstantPlaceholder(0, SBoolean)) + template.expressionTree shouldBe expectedExpr } property("uses given environment when provided (overriding default value)") { - val explicitEnv = Map("low" -> 10, "high" -> 100) val source = """/**/ |@contract def contractName(low: Int = 0, high: Int) = sigmaProp(low < HEIGHT && HEIGHT < high) |""".stripMargin - val compiler = SigmaTemplateCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) - val template = compiler.compile(explicitEnv, source) + val template = templateCompiler.compile(source) template.parameters should contain theSameElementsInOrderAs IndexedSeq( Parameter("low", "", 0), @@ -128,27 +116,30 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck None ) - val sigmaCompiler = new SigmaCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) - implicit val ir = new CompiletimeIRContext - val result = sigmaCompiler.compile( - env = explicitEnv, - code = "sigmaProp(low < HEIGHT && HEIGHT < high)" + SigmaPPrint.pprintln(template.expressionTree, 100) + + val expectedExpr = BoolToSigmaProp( + BinAnd( + LT(ConstantPlaceholder(0, SInt), Height), + LT(Height, ConstantPlaceholder(1, SInt)) + ) ) + template.expressionTree shouldBe expectedExpr + + val explicitEnv = Map("low" -> 10, "high" -> 100) - template.expressionTree shouldBe result.buildTree } - property("fails when constant value in not provided") { - // NOTE: parameter `high` without default value */ + property("fails when the parameter is not provided") { + // NOTE: parameter `condition` is not provided */ val source = """/**/ - |@contract def contractName(low: Int = 0, high: Int) = sigmaProp(low < HEIGHT && HEIGHT < high) + |@contract def contractName(low: Int = 0, high: Int) = sigmaProp(low < HEIGHT && HEIGHT < high) && condition |""".stripMargin - val compiler = SigmaTemplateCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) val env: ScriptEnv = Map.empty // no value for "high" assertExceptionThrown( - compiler.compile(env, source), - exceptionLike[TyperException]("Cannot assign type for variable 'high' because it is not found in env") + templateCompiler.compile(source), + exceptionLike[TyperException]("Cannot assign type for variable 'condition' because it is not found in env") ) } diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala index a474727943..5bb38c7998 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala @@ -34,7 +34,8 @@ class SigmaTyperTest extends AnyPropSpec val predefinedFuncRegistry = new PredefinedFuncRegistry(builder) val binder = new SigmaBinder(env, builder, TestnetNetworkPrefix, predefinedFuncRegistry) val bound = binder.bind(parsed) - val typer = new SigmaTyper(builder, predefinedFuncRegistry, lowerMethodCalls = true) + val typeEnv = env.collect { case (k, v: SType) => k -> v } + val typer = new SigmaTyper(builder, predefinedFuncRegistry, typeEnv, lowerMethodCalls = true) val typed = typer.typecheck(bound) assertSrcCtxForAllNodes(typed) if (expected != null) typed shouldBe expected @@ -51,7 +52,8 @@ class SigmaTyperTest extends AnyPropSpec val predefinedFuncRegistry = new PredefinedFuncRegistry(builder) val binder = new SigmaBinder(env, builder, TestnetNetworkPrefix, predefinedFuncRegistry) val bound = binder.bind(parsed) - val typer = new SigmaTyper(builder, predefinedFuncRegistry, lowerMethodCalls = true) + val typeEnv = env.collect { case (k, v: SType) => k -> v } + val typer = new SigmaTyper(builder, predefinedFuncRegistry, typeEnv, lowerMethodCalls = true) typer.typecheck(bound) }, { case te: TyperException => From 6abf2925bf441d39bbb6807d0491864f2fc15f55 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Sun, 12 May 2024 13:53:31 +0100 Subject: [PATCH 40/65] i966-template-compiler: added ErgoTreeUtils.explainTreeHeader --- .../sdk/utils/ErgoTreeUtils.scala | 26 +++++++++++++++++++ .../sdk/utils/ErgoTreeUtilsSpec.scala | 23 ++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/ErgoTreeUtils.scala create mode 100644 sdk/shared/src/test/scala/org/ergoplatform/sdk/utils/ErgoTreeUtilsSpec.scala diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/ErgoTreeUtils.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/ErgoTreeUtils.scala new file mode 100644 index 0000000000..8feccb2dfc --- /dev/null +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/ErgoTreeUtils.scala @@ -0,0 +1,26 @@ +package org.ergoplatform.sdk.utils + +import sigma.ast.ErgoTree +import sigma.ast.ErgoTree.HeaderType +import sigma.util.Extensions.BooleanOps + +/** SDK level utilities and helper methods to work with ErgoTrees. */ +object ErgoTreeUtils { + /** Prints description of the bits in the given ErgoTree header. */ + def explainTreeHeader(header: HeaderType): String = { + // convert byte to hex and decimal string + val byteToHex = (b: Byte) => f"Ox${b & 0xff}%02x" + val hasSize = ErgoTree.hasSize(header) + s""" + |Header: ${byteToHex(header)} (${header.toString}) + |Bit 0: ${header.toByte & 0x01} \\ + |Bit 1: ${(header.toByte & 0x02) >> 1}\t-- ErgoTree version ${ErgoTree.getVersion(header)} + |Bit 2: ${(header.toByte & 0x04) >> 2} / + |Bit 3: ${hasSize.toByte} \t-- size of the whole tree is serialized after the header byte + |Bit 4: ${ErgoTree.isConstantSegregation(header).toByte} \t-- constant segregation is used for this ErgoTree + |Bit 5: ${header.toByte & 0x20} \t-- reserved (should be 0) + |Bit 6: ${header.toByte & 0x40} \t-- reserved for GZIP compression (should be 0) + |Bit 7: ${header.toByte & 0x80} \t-- header contains more than 1 byte (default == 0) + |""".stripMargin + } +} diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/utils/ErgoTreeUtilsSpec.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/utils/ErgoTreeUtilsSpec.scala new file mode 100644 index 0000000000..cb3321d28e --- /dev/null +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/utils/ErgoTreeUtilsSpec.scala @@ -0,0 +1,23 @@ +package org.ergoplatform.sdk.utils + +import org.scalatest.matchers.should.Matchers +import org.scalatest.propspec.AnyPropSpec +import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks +import sigma.ast.ErgoTree.HeaderType + +class ErgoTreeUtilsSpec extends AnyPropSpec with ScalaCheckPropertyChecks with Matchers { + property("explainTreeHeader") { + ErgoTreeUtils.explainTreeHeader(HeaderType @@ 26.toByte) shouldBe + """| + |Header: Ox1a (26) + |Bit 0: 0 \ + |Bit 1: 1 -- ErgoTree version 2 + |Bit 2: 0 / + |Bit 3: 1 -- size of the whole tree is serialized after the header byte + |Bit 4: 1 -- constant segregation is used for this ErgoTree + |Bit 5: 0 -- reserved (should be 0) + |Bit 6: 0 -- reserved for GZIP compression (should be 0) + |Bit 7: 0 -- header contains more than 1 byte (default == 0) + |""".stripMargin + } +} From efabf245052c77cd4c386bdbc5ce0ba147e79199 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Sun, 12 May 2024 14:33:30 +0100 Subject: [PATCH 41/65] i966-template-compiler: test ContractTemplate.applyTemplate method --- .../src/main/scala/sigma/ast/ErgoTree.scala | 4 +-- .../lang/SigmaTemplateCompilerTest.scala | 27 ++++++++++++++++--- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/data/shared/src/main/scala/sigma/ast/ErgoTree.scala b/data/shared/src/main/scala/sigma/ast/ErgoTree.scala index d6ed6118dc..68d69abd91 100644 --- a/data/shared/src/main/scala/sigma/ast/ErgoTree.scala +++ b/data/shared/src/main/scala/sigma/ast/ErgoTree.scala @@ -25,13 +25,13 @@ case class UnparsedErgoTree(bytes: mutable.WrappedArray[Byte], error: Validation * ErgoTreeSerializer defines top-level serialization format of the scripts. * The interpretation of the byte array depend on the first `header` byte, which uses VLQ encoding up to 30 bits. * Currently we define meaning for only first byte, which may be extended in future versions. - * 7 6 5 4 3 2 1 0 + * 7 6 5 4 3 2 1 0 * ------------------------- * | | | | | | | | | * ------------------------- * Bit 7 == 1 if the header contains more than 1 byte (default == 0) * Bit 6 - reserved for GZIP compression (should be 0) - * Bit 5 == 1 - reserved for context dependent costing (should be = 0) + * Bit 5 == 1 - reserved (should be = 0) * Bit 4 == 1 if constant segregation is used for this ErgoTree (default = 0) * (see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/264) * Bit 3 == 1 if size of the whole tree is serialized after the header byte (default = 0) diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala index a0f9c7d8aa..d3e08a700f 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala @@ -4,7 +4,9 @@ import org.ergoplatform.ErgoAddressEncoder import org.ergoplatform.sdk.Parameter import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks -import sigma.ast.{BinAnd, BoolToSigmaProp, ConstantPlaceholder, Height, LT, SBoolean, SInt, SLong, SString, TrueLeaf} +import sigma.VersionContext +import sigma.ast.ErgoTree.HeaderType +import sigma.ast.{BinAnd, BoolToSigmaProp, ConstantPlaceholder, ErgoTree, FalseLeaf, Height, LT, SBoolean, SInt, SLong, SString, TrueLeaf} import sigma.exceptions.TyperException import sigmastate.helpers.SigmaPPrint import sigmastate.interpreter.Interpreter.ScriptEnv @@ -96,6 +98,27 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck val expectedExpr = BoolToSigmaProp(ConstantPlaceholder(0, SBoolean)) template.expressionTree shouldBe expectedExpr + + val expectedTree = new ErgoTree( + HeaderType @@ 26.toByte, // use ErgoTreeUtils to get explanation + Vector(TrueLeaf), + Right(BoolToSigmaProp(ConstantPlaceholder(0, SBoolean)))) + + expectedTree.version shouldBe VersionContext.JitActivationVersion + expectedTree.hasSize shouldBe true + expectedTree.isConstantSegregation shouldBe true + + // apply using default values declared in the parameters + template.applyTemplate( + version = Some(VersionContext.JitActivationVersion), + paramValues = Map.empty + ) shouldBe expectedTree + + // apply overriding the default values + template.applyTemplate( + version = Some(VersionContext.JitActivationVersion), + paramValues = Map("p" -> FalseLeaf) + ) shouldBe expectedTree.copy(constants = Vector(FalseLeaf)) } property("uses given environment when provided (overriding default value)") { @@ -116,8 +139,6 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck None ) - SigmaPPrint.pprintln(template.expressionTree, 100) - val expectedExpr = BoolToSigmaProp( BinAnd( LT(ConstantPlaceholder(0, SInt), Height), From dcee25851110f0241445f83da95f3baceff40806 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Sun, 12 May 2024 17:47:43 +0100 Subject: [PATCH 42/65] i966-template-compiler: more tests for CompilerTemplate.applyTemplate --- .../scala/sigmastate/lang/LangTests.scala | 3 +- .../scala/sigmastate/CompilerTestsBase.scala | 11 ++- .../lang/SigmaTemplateCompilerTest.scala | 90 +++++++++++++------ .../ergoplatform/sdk/ContractTemplate.scala | 2 +- .../sdk/utils/ErgoTreeUtils.scala | 4 +- 5 files changed, 79 insertions(+), 31 deletions(-) diff --git a/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala b/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala index 498c3934bf..32943bca44 100644 --- a/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala +++ b/parsers/shared/src/test/scala/sigmastate/lang/LangTests.scala @@ -1,16 +1,15 @@ package sigmastate.lang import org.scalatest.matchers.should.Matchers -import sigma.{Coll, _} import sigma.ast.SCollection.SByteArray import sigma.ast.syntax.{SValue, ValueOps} import sigma.ast._ import sigma.crypto.CryptoConstants import sigma.data.{CAnyValue, CSigmaDslBuilder, ProveDHTuple, ProveDlog, SigmaBoolean} import sigma.util.Extensions.BigIntegerOps +import sigma._ import sigmastate.helpers.NegativeTesting import sigmastate.interpreter.Interpreter.ScriptEnv -import sigma.ast.{Ident, MethodCallLike} import java.math.BigInteger diff --git a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala index 28f907c199..0b2951b92f 100644 --- a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala +++ b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala @@ -9,8 +9,9 @@ import sigma.ast.syntax.{SValue, SigmaPropValue} import sigma.serialization.ValueSerializer import sigmastate.eval.IRContext import sigma.ast.syntax.ValueOps +import sigmastate.helpers.{NegativeTesting, SigmaPPrint} -trait CompilerTestsBase extends TestsBase { +trait CompilerTestsBase extends TestsBase with NegativeTesting { protected val _lowerMethodCalls = new DynamicVariable[Boolean](true) /** Returns true if MethodCall nodes should be lowered by TypeChecker to the @@ -63,4 +64,12 @@ trait CompilerTestsBase extends TestsBase { val tree = mkTestErgoTree(prop) (tree, prop) } + + /** Checks expectation pretty printing the actual value if there is a difference. */ + def checkEquals[T](actual: T, expected: T): Unit = { + if (expected != actual) { + SigmaPPrint.pprintln(actual, width = 100) + } + actual shouldBe expected + } } diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala index d3e08a700f..35f16618ec 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala @@ -6,12 +6,12 @@ import org.scalatest.propspec.AnyPropSpec import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import sigma.VersionContext import sigma.ast.ErgoTree.HeaderType -import sigma.ast.{BinAnd, BoolToSigmaProp, ConstantPlaceholder, ErgoTree, FalseLeaf, Height, LT, SBoolean, SInt, SLong, SString, TrueLeaf} +import sigma.ast.{BinAnd, BoolToSigmaProp, ConstantPlaceholder, ErgoTree, FalseLeaf, GT, Height, IntConstant, LT, SBoolean, SInt, SLong, SString, TrueLeaf} import sigma.exceptions.TyperException -import sigmastate.helpers.SigmaPPrint +import sigmastate.CompilerTestsBase import sigmastate.interpreter.Interpreter.ScriptEnv -class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyChecks with LangTests { +class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyChecks with CompilerTestsBase { val templateCompiler = SigmaTemplateCompiler(ErgoAddressEncoder.MainnetNetworkPrefix) property("compiles full contract template") { @@ -45,8 +45,7 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck None ) - val expectedExpr = BoolToSigmaProp(TrueLeaf) - template.expressionTree shouldBe expectedExpr + checkEquals(template.expressionTree, BoolToSigmaProp(TrueLeaf)) } property("compiles contract template without braces") { @@ -77,14 +76,13 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck Some("default string") ) - val expectedExpr = BoolToSigmaProp(TrueLeaf) - template.expressionTree shouldBe expectedExpr + checkEquals(template.expressionTree, BoolToSigmaProp(TrueLeaf)) } property("uses default value from parameter definition") { val source = """/**/ - |@contract def contractName(p: Boolean = true) = sigmaProp(p) + |@contract def contractName(p: Boolean = true) = sigmaProp(p && HEIGHT > 1000) |""".stripMargin val template = templateCompiler.compile(source) @@ -96,29 +94,35 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck Some(true) ) - val expectedExpr = BoolToSigmaProp(ConstantPlaceholder(0, SBoolean)) - template.expressionTree shouldBe expectedExpr + val expectedExpr = BoolToSigmaProp(BinAnd(ConstantPlaceholder(0, SBoolean), GT(Height, IntConstant(1000)))) + checkEquals(template.expressionTree, expectedExpr) val expectedTree = new ErgoTree( HeaderType @@ 26.toByte, // use ErgoTreeUtils to get explanation Vector(TrueLeaf), - Right(BoolToSigmaProp(ConstantPlaceholder(0, SBoolean)))) + Right(BoolToSigmaProp(BinAnd(ConstantPlaceholder(0, SBoolean), GT(Height, IntConstant(1000)))))) expectedTree.version shouldBe VersionContext.JitActivationVersion expectedTree.hasSize shouldBe true expectedTree.isConstantSegregation shouldBe true // apply using default values declared in the parameters - template.applyTemplate( - version = Some(VersionContext.JitActivationVersion), - paramValues = Map.empty - ) shouldBe expectedTree + checkEquals( + template.applyTemplate( + version = Some(VersionContext.JitActivationVersion), + paramValues = Map.empty + ), + expectedTree + ) // apply overriding the default values - template.applyTemplate( - version = Some(VersionContext.JitActivationVersion), - paramValues = Map("p" -> FalseLeaf) - ) shouldBe expectedTree.copy(constants = Vector(FalseLeaf)) + checkEquals( + template.applyTemplate( + version = Some(VersionContext.JitActivationVersion), + paramValues = Map("p" -> FalseLeaf) + ), + expectedTree.copy(constants = Vector(FalseLeaf)) + ) } property("uses given environment when provided (overriding default value)") { @@ -138,17 +142,53 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck Some(0), None ) + checkEquals( + template.expressionTree, + BoolToSigmaProp( + BinAnd( + LT(ConstantPlaceholder(0, SInt), Height), + LT(Height, ConstantPlaceholder(1, SInt)) + ) + ) + ) + + // incomplete application (missing `high` parameter) + assertExceptionThrown( + template.applyTemplate( + version = Some(VersionContext.JitActivationVersion), + paramValues = Map.empty + ), + exceptionLike[IllegalArgumentException]( + "requirement failed: value for parameter `high` was not provided while it does not have a default value.") + ) - val expectedExpr = BoolToSigmaProp( - BinAnd( - LT(ConstantPlaceholder(0, SInt), Height), - LT(Height, ConstantPlaceholder(1, SInt)) + val expectedTree = new ErgoTree( + HeaderType @@ 26.toByte, + Vector(IntConstant(0), IntConstant(100)), + Right( + BoolToSigmaProp( + BinAnd(LT(ConstantPlaceholder(0, SInt), Height), LT(Height, ConstantPlaceholder(1, SInt))) + ) ) ) - template.expressionTree shouldBe expectedExpr - val explicitEnv = Map("low" -> 10, "high" -> 100) + // apply providing the parameter without default value + checkEquals( + template.applyTemplate( + version = Some(VersionContext.JitActivationVersion), + paramValues = Map("high" -> IntConstant(100)) + ), + expectedTree + ) + // apply providing all parameters overriding the default values + checkEquals( + template.applyTemplate( + version = Some(VersionContext.JitActivationVersion), + paramValues = Map("low" -> IntConstant(10), "high" -> IntConstant(100)) + ), + expectedTree.copy(constants = Vector(IntConstant(10), IntConstant(100))) + ) } property("fails when the parameter is not provided") { diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/ContractTemplate.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/ContractTemplate.scala index 5e491630bd..8da420bee6 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/ContractTemplate.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/ContractTemplate.scala @@ -153,7 +153,7 @@ case class ContractTemplate( .map(p => p.name) requiredParameterNames.foreach(name => require( paramValues.contains(name), - s"value for parameter $name was not provided while it does not have a default value.")) + s"value for parameter `$name` was not provided while it does not have a default value.")) val parameterizedConstantIndices = this.parameters.map(p => p.constantIndex).toSet val constIndexToParamIndex = this.parameters.zipWithIndex.map(pi => pi._1.constantIndex -> pi._2).toMap diff --git a/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/ErgoTreeUtils.scala b/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/ErgoTreeUtils.scala index 8feccb2dfc..ffa6505377 100644 --- a/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/ErgoTreeUtils.scala +++ b/sdk/shared/src/main/scala/org/ergoplatform/sdk/utils/ErgoTreeUtils.scala @@ -8,7 +8,7 @@ import sigma.util.Extensions.BooleanOps object ErgoTreeUtils { /** Prints description of the bits in the given ErgoTree header. */ def explainTreeHeader(header: HeaderType): String = { - // convert byte to hex and decimal string + // convert byte to hex val byteToHex = (b: Byte) => f"Ox${b & 0xff}%02x" val hasSize = ErgoTree.hasSize(header) s""" @@ -19,7 +19,7 @@ object ErgoTreeUtils { |Bit 3: ${hasSize.toByte} \t-- size of the whole tree is serialized after the header byte |Bit 4: ${ErgoTree.isConstantSegregation(header).toByte} \t-- constant segregation is used for this ErgoTree |Bit 5: ${header.toByte & 0x20} \t-- reserved (should be 0) - |Bit 6: ${header.toByte & 0x40} \t-- reserved for GZIP compression (should be 0) + |Bit 6: ${header.toByte & 0x40} \t-- reserved (should be 0) |Bit 7: ${header.toByte & 0x80} \t-- header contains more than 1 byte (default == 0) |""".stripMargin } From ba6abadfc39ea7f2f6c77d71adaa6a0a93101b52 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Sun, 12 May 2024 17:56:15 +0100 Subject: [PATCH 43/65] i966-template-compiler: fix ErgoTreeUtilsSpec --- .../scala/org/ergoplatform/sdk/utils/ErgoTreeUtilsSpec.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/shared/src/test/scala/org/ergoplatform/sdk/utils/ErgoTreeUtilsSpec.scala b/sdk/shared/src/test/scala/org/ergoplatform/sdk/utils/ErgoTreeUtilsSpec.scala index cb3321d28e..8dd20ecf81 100644 --- a/sdk/shared/src/test/scala/org/ergoplatform/sdk/utils/ErgoTreeUtilsSpec.scala +++ b/sdk/shared/src/test/scala/org/ergoplatform/sdk/utils/ErgoTreeUtilsSpec.scala @@ -16,7 +16,7 @@ class ErgoTreeUtilsSpec extends AnyPropSpec with ScalaCheckPropertyChecks with M |Bit 3: 1 -- size of the whole tree is serialized after the header byte |Bit 4: 1 -- constant segregation is used for this ErgoTree |Bit 5: 0 -- reserved (should be 0) - |Bit 6: 0 -- reserved for GZIP compression (should be 0) + |Bit 6: 0 -- reserved (should be 0) |Bit 7: 0 -- header contains more than 1 byte (default == 0) |""".stripMargin } From 28f7e1534960e6e3e56cde16a78e900366170543 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Sun, 12 May 2024 21:06:31 +0100 Subject: [PATCH 44/65] i966-template-compiler: addressed review comments --- sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala | 7 +++++-- .../scala/sigmastate/lang/SigmaTemplateCompilerTest.scala | 1 - 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala index 857ed66338..416f2d7fbb 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala @@ -13,8 +13,11 @@ import sigma.serialization.OpCodes import scala.collection.mutable.ArrayBuffer -/** - * Type inference and analysis for Sigma expressions. +/** Type inference and analysis for Sigma expressions. + * @param builder SigmaBuilder instance to create new nodes + * @param predefFuncRegistry predefined functions registry used to resolve names + * @param typeEnv environment with types of variables/names + * @param lowerMethodCalls if true, then MethodCall nodes are lowered to the corresponding ErgoTree nodes */ class SigmaTyper(val builder: SigmaBuilder, predefFuncRegistry: PredefinedFuncRegistry, diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala index 35f16618ec..966a7c4c74 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala @@ -197,7 +197,6 @@ class SigmaTemplateCompilerTest extends AnyPropSpec with ScalaCheckPropertyCheck """/**/ |@contract def contractName(low: Int = 0, high: Int) = sigmaProp(low < HEIGHT && HEIGHT < high) && condition |""".stripMargin - val env: ScriptEnv = Map.empty // no value for "high" assertExceptionThrown( templateCompiler.compile(source), exceptionLike[TyperException]("Cannot assign type for variable 'condition' because it is not found in env") From d6efd22b61cda3e8ad6f1a14f619e813dddcb0f1 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Tue, 14 May 2024 15:40:16 +0100 Subject: [PATCH 45/65] v6.0.0-fix-tests: necessary changes due to MaxSupportedVersion upgrade --- .../src/test/scala/sigma/VersionTesting.scala | 4 +--- .../test/scala/sigma/SigmaDslSpecification.scala | 16 ++++++++-------- .../ScriptVersionSwitchSpecification.scala | 7 ++++--- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/core/shared/src/test/scala/sigma/VersionTesting.scala b/core/shared/src/test/scala/sigma/VersionTesting.scala index 69e15ff491..08053a6c48 100644 --- a/core/shared/src/test/scala/sigma/VersionTesting.scala +++ b/core/shared/src/test/scala/sigma/VersionTesting.scala @@ -39,9 +39,7 @@ trait VersionTesting { _ + 1) { j => val treeVersion = ergoTreeVers(j) // for each tree version up to currently activated, set it up and execute block - _currErgoTreeVersion.withValue(treeVersion) { - VersionContext.withVersions(activatedVersion, treeVersion)(block) - } + _currErgoTreeVersion.withValue(treeVersion)(block) } } } diff --git a/sc/shared/src/test/scala/sigma/SigmaDslSpecification.scala b/sc/shared/src/test/scala/sigma/SigmaDslSpecification.scala index 4dd576f03a..c820e65e73 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslSpecification.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslSpecification.scala @@ -5081,7 +5081,7 @@ class SigmaDslSpecification extends SigmaDslTesting newCost = 1766, newVersionedResults = { val res = (ExpectedResult(Success(0), Some(1766)) -> Some(selfCostDetails)) - Seq(0, 1, 2).map(version => version -> res) + Seq(0, 1, 2, 3).map(version => version -> res) })) ), changedFeature({ (x: Context) => x.selfBoxIndex }, @@ -5280,7 +5280,7 @@ class SigmaDslSpecification extends SigmaDslTesting Seq( ctx -> Expected(Failure(expectedError), 0, CostDetails.ZeroCost, 1793, newVersionedResults = { - Seq.tabulate(3)(v => v -> (ExpectedResult(Success(true), Some(1793)) -> None)) + Seq.tabulate(4)(v => v -> (ExpectedResult(Success(true), Some(1793)) -> None)) } ) ), @@ -6233,7 +6233,7 @@ class SigmaDslSpecification extends SigmaDslTesting cost = c, expectedDetails = CostDetails.ZeroCost, newCost = 1766, - newVersionedResults = Seq(0, 1, 2).map(i => i -> (ExpectedResult(Success(newV), Some(1766)) -> Some(cd))) + newVersionedResults = Seq(0, 1, 2, 3).map(i => i -> (ExpectedResult(Success(newV), Some(1766)) -> Some(cd))) ) Seq( (Coll[Boolean](), successNew(false, 1766, newV = false, costDetails(0))), @@ -6511,7 +6511,7 @@ class SigmaDslSpecification extends SigmaDslTesting newCost = 1769, newVersionedResults = { val res = (ExpectedResult(Success(Helpers.decodeBytes("00")), Some(1769)), Some(costDetails(1))) - Seq(0, 1, 2).map(version => version -> res) + Seq(0, 1, 2, 3).map(version => version -> res) } )), ((Helpers.decodeBytes("800136fe89afff802acea67128a0ff007fffe3498c8001806080012b"), @@ -9120,7 +9120,7 @@ class SigmaDslSpecification extends SigmaDslTesting cost = 0, expectedDetails = CostDetails.ZeroCost, newCost = 1766, - newVersionedResults = Seq.tabulate(3)(v => v -> (ExpectedResult(Success(5L), Some(1766)) -> Some(costDetails1))) + newVersionedResults = Seq.tabulate(4)(v => v -> (ExpectedResult(Success(5L), Some(1766)) -> Some(costDetails1))) )), (Some(0L) -> Expected( Success(1L), @@ -9679,7 +9679,7 @@ class SigmaDslSpecification extends SigmaDslTesting newCost = 1783, newVersionedResults = { val res = (ExpectedResult(Success(Helpers.decodeBytes("0008d3")), Some(1783)) -> Some(costDetails(0))) - Seq(0, 1, 2).map(version => version -> res) + Seq(0, 1, 2, 3).map(version => version -> res) }), (Helpers.decodeBytes("000008d3"), 0) -> Expected( @@ -9690,7 +9690,7 @@ class SigmaDslSpecification extends SigmaDslTesting newVersionedResults = { // since the tree without constant segregation, substitution has no effect val res = (ExpectedResult(Success(Helpers.decodeBytes("000008d3")), Some(1783)) -> Some(costDetails(0))) - Seq(0, 1, 2).map(version => version -> res) + Seq(0, 1, 2, 3).map(version => version -> res) }), // tree with segregation flag, empty constants array (Coll(t2.bytes:_*), 0) -> success(Helpers.decodeBytes("100008d3"), costDetails(0), 1783), @@ -9761,7 +9761,7 @@ class SigmaDslSpecification extends SigmaDslTesting cost = 1776, expectedDetails = CostDetails.ZeroCost, newCost = 1776, - newVersionedResults = (0 to 2).map(i => i -> (ExpectedResult(Success(true), Some(1776)) -> Some(costDetails))) + newVersionedResults = Seq(0, 1, 2, 3).map(i => i -> (ExpectedResult(Success(true), Some(1776)) -> Some(costDetails))) ) ), changedFeature( diff --git a/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala b/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala index b0206fa464..aedf35e914 100644 --- a/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala @@ -276,13 +276,14 @@ class ScriptVersionSwitchSpecification extends SigmaDslTesting { * 20 | 4 | mined | Script v3 | v5.0 | skip-accept (rely on majority) */ property("Rules 19,20 | Block v4 | candidate or mined block | Script v3") { - forEachActivatedScriptVersion(activatedVers = Array[Byte](3)) // version for Block v4 + forEachActivatedScriptVersion(activatedVers = Array[Byte](4)) // activated version is greater then MaxSupported { - forEachErgoTreeVersion(ergoTreeVers = Array[Byte](3, 4)) { // scripts >= v3 + forEachErgoTreeVersion(ergoTreeVers = Array[Byte](4, 5)) { // tree version >= activated val headerFlags = ErgoTree.defaultHeaderWithVersion(ergoTreeVersionInTests) val ergoTree = createErgoTree(headerFlags) - // prover is rejecting, because such context parameters doesn't make sense + // prover is rejecting, because it cannot generate proofs for ErgoTrees with version + // higher than max supported by the interpreter assertExceptionThrown( testProve(ergoTree, activatedScriptVersion = activatedVersionInTests), exceptionLike[InterpreterException](s"Both ErgoTree version ${ergoTree.version} and activated version $activatedVersionInTests is greater than MaxSupportedScriptVersion $MaxSupportedScriptVersion") From 302b09d494c3bdc449b6e83f0bbaf1112463caf8 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Tue, 14 May 2024 16:48:50 +0100 Subject: [PATCH 46/65] refactor-ir-cake: removed Library trait (merged with Scalan) --- .../InterpreterReflectionGeneratorTests.scala | 2 +- .../main/scala/scalan/GraphIRReflection.scala | 6 +- sc/shared/src/main/scala/scalan/Library.scala | 120 ------------------ sc/shared/src/main/scala/scalan/Scalan.scala | 118 ++++++++++++++++- .../scala/sigmastate/eval/SigmaLibrary.scala | 4 +- .../scala/special/collection/CollsUnit.scala | 2 +- .../special/collection/impl/CollsImpl.scala | 6 +- .../sigma/wrappers/WrappersModule.scala | 4 +- .../special/wrappers/WrappersModule.scala | 3 +- .../main/scala/wrappers/scala/WOptions.scala | 2 +- .../wrappers/scala/impl/WOptionsImpl.scala | 6 +- .../main/scala/wrappers/scalan/WRTypes.scala | 3 +- .../wrappers/scalan/impl/WRTypesImpl.scala | 14 +- .../wrappers/special/WSpecialPredefs.scala | 4 +- .../special/impl/WSpecialPredefsImpl.scala | 6 +- .../src/test/scala/scalan/TestLibrary.scala | 2 +- .../test/scala/sigma/CollsStagingTests.scala | 4 +- .../scala/special/wrappers/WOptionTests.scala | 1 - 18 files changed, 152 insertions(+), 155 deletions(-) delete mode 100644 sc/shared/src/main/scala/scalan/Library.scala diff --git a/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala b/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala index aaa1d6c424..5d81e0d19a 100644 --- a/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala +++ b/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala @@ -37,7 +37,7 @@ class InterpreterReflectionGeneratorTests extends AnyPropSpec with Matchers { } property("inner class") { - val ctx = null.asInstanceOf[scalan.Library] // ok! type level only + val ctx = null.asInstanceOf[scalan.Scalan] // ok! type level only val clazz = classOf[ctx.Coll.CollElem[_, _]] registerClassEntry(clazz, constructors = Array( diff --git a/sc/shared/src/main/scala/scalan/GraphIRReflection.scala b/sc/shared/src/main/scala/scalan/GraphIRReflection.scala index 0eaba9d8a3..787873035d 100644 --- a/sc/shared/src/main/scala/scalan/GraphIRReflection.scala +++ b/sc/shared/src/main/scala/scalan/GraphIRReflection.scala @@ -24,7 +24,7 @@ object GraphIRReflection { val reflection = ReflectionData { val clazz = classOf[wrappers.scala.WOptions#WOption[_]] - val ctx = null.asInstanceOf[scalan.Library] // ok! type level only + val ctx = null.asInstanceOf[scalan.Scalan] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "filter", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => @@ -123,7 +123,7 @@ object GraphIRReflection { } { val clazz = classOf[Colls#CollBuilder] - val ctx = null.asInstanceOf[Library] // ok! type level only + val ctx = null.asInstanceOf[Scalan] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "xor", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => @@ -145,7 +145,7 @@ object GraphIRReflection { { val clazz = classOf[Colls#Coll[_]] - val ctx = null.asInstanceOf[Library] // ok! type level only + val ctx = null.asInstanceOf[Scalan] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "append", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => diff --git a/sc/shared/src/main/scala/scalan/Library.scala b/sc/shared/src/main/scala/scalan/Library.scala deleted file mode 100644 index 43f20813f0..0000000000 --- a/sc/shared/src/main/scala/scalan/Library.scala +++ /dev/null @@ -1,120 +0,0 @@ -package scalan - -import scala.language.implicitConversions -import sigma._ -import sigma.data.{Nullable, RType} -import special.wrappers.WrappersModule -import sigma.util.MemoizedFunc - -trait Library extends Scalan - with WrappersModule - with CollsModule -{ - import WOption._ - import WRType._ - import Coll._; import CollBuilder._; - import WSpecialPredef._ - - type LazyRep[T] = MutableLazy[Ref[T]] - - private val _liftElemMemo = new MemoizedFunc({ - case eT: Elem[t] => - val lT = Liftables.asLiftable[Any, t](eT.liftable) - liftableRType(lT).lift(eT.sourceType.asInstanceOf[RType[Any]]) - }) - implicit def liftElem[T](eT: Elem[T]): Ref[WRType[T]] = { - _liftElemMemo(eT).asInstanceOf[Ref[WRType[T]]] // asRep cannot be used for AnyRef - } - - private val _specialPredef: LazyRep[WSpecialPredefCompanionCtor] = MutableLazy(RWSpecialPredef.value) - def specialPredef: Ref[WSpecialPredefCompanionCtor] = _specialPredef.value - - override protected def onReset(): Unit = { - _specialPredef.reset() - _liftElemMemo.reset() - super.onReset() - } - - val CM = CollMethods - private val CBM = CollBuilderMethods - private val WOptionM = WOptionMethods - private val SPCM = WSpecialPredefCompanionMethods - - def colBuilder: Ref[CollBuilder] - - object IsNumericToInt { - def unapply(d: Def[_]): Nullable[Ref[A] forSome {type A}] = d match { - case ApplyUnOp(_: NumericToInt[_], x) => Nullable(x.asInstanceOf[Ref[A] forSome {type A}]) - case _ => Nullable.None - } - } - object IsNumericToLong { - def unapply(d: Def[_]): Nullable[Ref[A] forSome {type A}] = d match { - case ApplyUnOp(_: NumericToLong[_], x) => Nullable(x.asInstanceOf[Ref[A] forSome {type A}]) - case _ => Nullable.None - } - } - - override def rewriteDef[T](d: Def[T]) = d match { - case CM.length(ys) => ys.node match { - // Rule: xs.map(f).length ==> xs.length - case CM.map(xs, _) => - xs.length - // Rule: replicate(len, v).length => len - case CBM.replicate(_, len, _) => - len - // Rule: Const[Coll[T]](coll).length => - case CollConst(coll, _) => - coll.length - // Rule: Coll(items @ Seq(x1, x2, x3)).length => items.length - case CBM.fromItems(_, items, _) => - items.length - case _ => super.rewriteDef(d) - } - - // Rule: replicate(l, x).zip(replicate(l, y)) ==> replicate(l, (x,y)) - case CM.zip(CBM.replicate(b1, l1, v1), CBM.replicate(b2, l2, v2)) if b1 == b2 && l1 == l2 => - b1.replicate(l1, Pair(v1, v2)) - - case CM.map(xs, _f) => _f.node match { - case IdentityLambda() => xs - case _ => xs.node match { - // Rule: replicate(l, v).map(f) ==> replicate(l, f(v)) - case CBM.replicate(b, l, v: Ref[a]) => - val f = asRep[a => Any](_f) - b.replicate(l, Apply(f, v, false)) - - // Rule: xs.map(f).map(g) ==> xs.map(x => g(f(x))) - case CM.map(_xs, f: RFunc[a, b]) => - implicit val ea = f.elem.eDom - val xs = asRep[Coll[a]](_xs) - val g = asRep[b => Any](_f) - xs.map[Any](fun { x: Ref[a] => g(f(x)) }) - - case _ => super.rewriteDef(d) - } - } - - case WOptionM.getOrElse(opt, _) => opt.node match { - // Rule: Some(x).getOrElse(_) ==> x - case SPCM.some(x) => x - case WOptionConst(Some(x), lA) => lA.lift(x) - case _ => super.rewriteDef(d) - } - - case _ => super.rewriteDef(d) - } - - override def invokeUnlifted(e: Elem[_], mc: MethodCall, dataEnv: DataEnv): Any = e match { - case _: CollElem[_,_] => mc match { - case CollMethods.map(_, f) => - val newMC = mc.copy(args = mc.args :+ f.elem.eRange)(mc.resultType, mc.isAdapterCall) - super.invokeUnlifted(e, newMC, dataEnv) - case _ => - super.invokeUnlifted(e, mc, dataEnv) - } - case _ => - super.invokeUnlifted(e, mc, dataEnv) - } - -} diff --git a/sc/shared/src/main/scala/scalan/Scalan.scala b/sc/shared/src/main/scala/scalan/Scalan.scala index c2e9359261..a466df29fa 100644 --- a/sc/shared/src/main/scala/scalan/Scalan.scala +++ b/sc/shared/src/main/scala/scalan/Scalan.scala @@ -2,6 +2,10 @@ package scalan import scalan.primitives._ import scalan.staged.Transforming +import sigma.CollsModule +import sigma.data.{Nullable, RType} +import sigma.util.MemoizedFunc +import special.wrappers.WrappersModule /** Aggregate cake with all inter-dependent modules assembled together. * Each instance of this class contains independent IR context, thus many @@ -16,7 +20,7 @@ import scalan.staged.Transforming * in classed derived from `Scalan`, this is significant benefit over * *everything is global* design. */ -class Scalan + trait Scalan extends TypeDescs with MethodCalls with Tuples @@ -33,4 +37,116 @@ class Scalan with Entities with Modules with DefRewriting + with WrappersModule + with CollsModule { + + import WOption._ + import WRType._ + import Coll._; import CollBuilder._; + import WSpecialPredef._ + + type LazyRep[T] = MutableLazy[Ref[T]] + + private val _liftElemMemo = new MemoizedFunc({ + case eT: Elem[t] => + val lT = Liftables.asLiftable[Any, t](eT.liftable) + liftableRType(lT).lift(eT.sourceType.asInstanceOf[RType[Any]]) + }) + implicit def liftElem[T](eT: Elem[T]): Ref[WRType[T]] = { + _liftElemMemo(eT).asInstanceOf[Ref[WRType[T]]] // asRep cannot be used for AnyRef + } + + private val _specialPredef: LazyRep[WSpecialPredefCompanionCtor] = MutableLazy(RWSpecialPredef.value) + def specialPredef: Ref[WSpecialPredefCompanionCtor] = _specialPredef.value + + override protected def onReset(): Unit = { + _specialPredef.reset() + _liftElemMemo.reset() + super.onReset() + } + + val CM = CollMethods + private val CBM = CollBuilderMethods + private val WOptionM = WOptionMethods + private val SPCM = WSpecialPredefCompanionMethods + + def colBuilder: Ref[CollBuilder] + + object IsNumericToInt { + def unapply(d: Def[_]): Nullable[Ref[A] forSome {type A}] = d match { + case ApplyUnOp(_: NumericToInt[_], x) => Nullable(x.asInstanceOf[Ref[A] forSome {type A}]) + case _ => Nullable.None + } + } + object IsNumericToLong { + def unapply(d: Def[_]): Nullable[Ref[A] forSome {type A}] = d match { + case ApplyUnOp(_: NumericToLong[_], x) => Nullable(x.asInstanceOf[Ref[A] forSome {type A}]) + case _ => Nullable.None + } + } + + override def rewriteDef[T](d: Def[T]) = d match { + case CM.length(ys) => ys.node match { + // Rule: xs.map(f).length ==> xs.length + case CM.map(xs, _) => + xs.length + // Rule: replicate(len, v).length => len + case CBM.replicate(_, len, _) => + len + // Rule: Const[Coll[T]](coll).length => + case CollConst(coll, _) => + coll.length + // Rule: Coll(items @ Seq(x1, x2, x3)).length => items.length + case CBM.fromItems(_, items, _) => + items.length + case _ => super.rewriteDef(d) + } + + // Rule: replicate(l, x).zip(replicate(l, y)) ==> replicate(l, (x,y)) + case CM.zip(CBM.replicate(b1, l1, v1), CBM.replicate(b2, l2, v2)) if b1 == b2 && l1 == l2 => + b1.replicate(l1, Pair(v1, v2)) + + case CM.map(xs, _f) => _f.node match { + case IdentityLambda() => xs + case _ => xs.node match { + // Rule: replicate(l, v).map(f) ==> replicate(l, f(v)) + case CBM.replicate(b, l, v: Ref[a]) => + val f = asRep[a => Any](_f) + b.replicate(l, Apply(f, v, false)) + + // Rule: xs.map(f).map(g) ==> xs.map(x => g(f(x))) + case CM.map(_xs, f: RFunc[a, b]) => + implicit val ea = f.elem.eDom + val xs = asRep[Coll[a]](_xs) + val g = asRep[b => Any](_f) + xs.map[Any](fun { x: Ref[a] => g(f(x)) }) + + case _ => super.rewriteDef(d) + } + } + + case WOptionM.getOrElse(opt, _) => opt.node match { + // Rule: Some(x).getOrElse(_) ==> x + case SPCM.some(x) => x + case WOptionConst(Some(x), lA) => lA.lift(x) + case _ => super.rewriteDef(d) + } + + case _ => super.rewriteDef(d) + } + + override def invokeUnlifted(e: Elem[_], mc: MethodCall, dataEnv: DataEnv): Any = e match { + case _: CollElem[_,_] => mc match { + case CollMethods.map(_, f) => + val newMC = mc.copy(args = mc.args :+ f.elem.eRange)(mc.resultType, mc.isAdapterCall) + super.invokeUnlifted(e, newMC, dataEnv) + case _ => + super.invokeUnlifted(e, mc, dataEnv) + } + case _ => + super.invokeUnlifted(e, mc, dataEnv) + } + + +} diff --git a/sc/shared/src/main/scala/sigmastate/eval/SigmaLibrary.scala b/sc/shared/src/main/scala/sigmastate/eval/SigmaLibrary.scala index 7745873620..ea0329e3db 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/SigmaLibrary.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/SigmaLibrary.scala @@ -1,10 +1,10 @@ package sigmastate.eval -import scalan.Library +import scalan.Scalan import sigma.SigmaDslModule /** Main trait which represents sigma operations in graph IR cake. */ -trait SigmaLibrary extends Library +trait SigmaLibrary extends Scalan with sigma.wrappers.WrappersModule with SigmaDslModule { diff --git a/sc/shared/src/main/scala/special/collection/CollsUnit.scala b/sc/shared/src/main/scala/special/collection/CollsUnit.scala index 90f0dca99e..db9922b82f 100644 --- a/sc/shared/src/main/scala/special/collection/CollsUnit.scala +++ b/sc/shared/src/main/scala/special/collection/CollsUnit.scala @@ -8,7 +8,7 @@ package sigma { * The semantics of each method is the same as in the original class, please look there * for details. */ - trait Colls extends Base { self: Library => + trait Colls extends Base { self: Scalan => trait Coll[A] extends Def[Coll[A]] { implicit def eA: Elem[A]; def length: Ref[Int]; diff --git a/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala b/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala index 239bfff4e5..382f5fe763 100644 --- a/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala +++ b/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala @@ -9,8 +9,8 @@ package impl { import sigma.reflection.{RClass, RMethod} // Abs ----------------------------------- -trait CollsDefs extends scalan.Scalan with Colls { - self: Library => +trait CollsDefs extends Base with Colls { + self: Scalan => registerModule(CollsModule) @@ -639,4 +639,4 @@ object CollsModule extends scalan.ModuleInfo("sigma", "Colls") { } } -trait CollsModule extends sigma.impl.CollsDefs {self: Library =>} +trait CollsModule extends sigma.impl.CollsDefs {self: Scalan =>} diff --git a/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala b/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala index 6696788621..50869cc4e1 100644 --- a/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala +++ b/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala @@ -1,4 +1,6 @@ package sigma.wrappers +import scalan.Scalan + trait WrappersModule - extends special.wrappers.WrappersModule + extends special.wrappers.WrappersModule { self: Scalan => } diff --git a/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala b/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala index b74bec314e..745413569a 100644 --- a/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala +++ b/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala @@ -1,5 +1,6 @@ package special.wrappers +import scalan.Scalan import wrappers.scala.WOptionsModule import wrappers.scalan.WRTypesModule import wrappers.special.WSpecialPredefsModule @@ -7,4 +8,4 @@ import wrappers.special.WSpecialPredefsModule trait WrappersModule extends WSpecialPredefsModule with WOptionsModule - with WRTypesModule \ No newline at end of file + with WRTypesModule { self: Scalan => } \ No newline at end of file diff --git a/sc/shared/src/main/scala/wrappers/scala/WOptions.scala b/sc/shared/src/main/scala/wrappers/scala/WOptions.scala index 4bd314c1de..445da52006 100644 --- a/sc/shared/src/main/scala/wrappers/scala/WOptions.scala +++ b/sc/shared/src/main/scala/wrappers/scala/WOptions.scala @@ -3,7 +3,7 @@ package wrappers.scala { import special.wrappers.WrappersModule - trait WOptions extends Base { self: WrappersModule => + trait WOptions extends Base { self: Scalan => trait WOption[A] extends Def[WOption[A]] { implicit def eA: Elem[A]; def isDefined: Ref[Boolean]; diff --git a/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala b/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala index 45d0a91ad6..62a0e0c10f 100644 --- a/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala +++ b/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala @@ -11,8 +11,8 @@ package impl { import sigma.reflection.{RClass, RMethod} // Abs ----------------------------------- -trait WOptionsDefs extends scalan.Scalan with WOptions { - self: WrappersModule => +trait WOptionsDefs extends Base with WOptions { + self: Scalan => class WOptionCls extends EntityObject("WOption") { // entityConst: single const for each entity @@ -240,4 +240,4 @@ object WOptionsModule extends scalan.ModuleInfo("wrappers.scala", "WOptions") { } } -trait WOptionsModule extends wrappers.scala.impl.WOptionsDefs {self: WrappersModule =>} +trait WOptionsModule extends wrappers.scala.impl.WOptionsDefs {self: Scalan =>} diff --git a/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala b/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala index 8c6bc48f8e..bc71b8ad26 100644 --- a/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala +++ b/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala @@ -1,9 +1,8 @@ package wrappers.scalan { import scalan._ - import special.wrappers.WrappersModule - trait WRTypes extends Base { self: WrappersModule => + trait WRTypes extends Base { self: Scalan => trait WRType[A] extends Def[WRType[A]] { implicit def eA: Elem[A]; def name: Ref[String] diff --git a/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala b/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala index 9b2676f70d..c78a2268bf 100644 --- a/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala +++ b/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala @@ -1,18 +1,20 @@ package wrappers.scalan -import scala.language.{existentials,implicitConversions} +import scalan.Scalan + +import scala.language.{existentials, implicitConversions} import sigma.data.RType -import special.wrappers.WrappersModule import special.wrappers.RTypeWrapSpec + import scala.collection.compat.immutable.ArraySeq package impl { - import scalan.GraphIRReflection + import scalan.{Base, GraphIRReflection, Scalan} import sigma.reflection.{RClass, RMethod} // Abs ----------------------------------- -trait WRTypesDefs extends scalan.Scalan with WRTypes { - self: WrappersModule => +trait WRTypesDefs extends Base with WRTypes { + self: Scalan => registerModule(WRTypesModule) @@ -116,4 +118,4 @@ object WRTypesModule extends scalan.ModuleInfo("wrappers.scalan", "WRTypes") { } } -trait WRTypesModule extends wrappers.scalan.impl.WRTypesDefs {self: WrappersModule =>} +trait WRTypesModule extends wrappers.scalan.impl.WRTypesDefs {self: Scalan =>} diff --git a/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala b/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala index 5abbab95e2..d1c1260391 100644 --- a/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala +++ b/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala @@ -1,9 +1,7 @@ package wrappers.special { import scalan._ - import special.wrappers.WrappersModule - - trait WSpecialPredefs extends Base { self: WrappersModule => + trait WSpecialPredefs extends Base { self: Scalan => trait WSpecialPredef extends Def[WSpecialPredef]; trait WSpecialPredefCompanion { def some[A](x: Ref[A]): Ref[WOption[A]]; diff --git a/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala b/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala index 1f80e71676..697de01802 100644 --- a/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala +++ b/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala @@ -9,8 +9,8 @@ package impl { import sigma.reflection.RClass // Abs ----------------------------------- -trait WSpecialPredefsDefs extends scalan.Scalan with WSpecialPredefs { - self: WrappersModule => +trait WSpecialPredefsDefs extends Base with WSpecialPredefs { + self: Scalan => registerModule(WSpecialPredefsModule) @@ -66,4 +66,4 @@ object WSpecialPredefsModule extends scalan.ModuleInfo("wrappers.special", "WSpe } } -trait WSpecialPredefsModule extends wrappers.special.impl.WSpecialPredefsDefs {self: WrappersModule =>} +trait WSpecialPredefsModule extends wrappers.special.impl.WSpecialPredefsDefs {self: Scalan =>} diff --git a/sc/shared/src/test/scala/scalan/TestLibrary.scala b/sc/shared/src/test/scala/scalan/TestLibrary.scala index efbce25e68..d78312317f 100644 --- a/sc/shared/src/test/scala/scalan/TestLibrary.scala +++ b/sc/shared/src/test/scala/scalan/TestLibrary.scala @@ -1,6 +1,6 @@ package scalan -trait TestLibrary extends Library { +trait TestLibrary extends Scalan { import CollBuilder._ val reflection = (GraphIRReflection) lazy val colBuilder: Ref[CollBuilder] = variable[CollBuilder] diff --git a/sc/shared/src/test/scala/sigma/CollsStagingTests.scala b/sc/shared/src/test/scala/sigma/CollsStagingTests.scala index 3b56920c8d..332c5e300c 100644 --- a/sc/shared/src/test/scala/sigma/CollsStagingTests.scala +++ b/sc/shared/src/test/scala/sigma/CollsStagingTests.scala @@ -41,7 +41,7 @@ class CollsStagingTests extends WrappersTests { } test("invokeUnlifted for Col") { - val ctx = new WrappersCtx with Library + val ctx = new WrappersCtx with Scalan import ctx._ import Coll._ import CollBuilder._ @@ -59,7 +59,7 @@ class CollsStagingTests extends WrappersTests { } test("invokeUnlifted for method of Ctor") { - val ctx = new WrappersCtx with Library + val ctx = new WrappersCtx with Scalan import ctx._ import Coll._ import CollBuilder._ diff --git a/sc/shared/src/test/scala/special/wrappers/WOptionTests.scala b/sc/shared/src/test/scala/special/wrappers/WOptionTests.scala index 7e046739f0..e952ba7c00 100644 --- a/sc/shared/src/test/scala/special/wrappers/WOptionTests.scala +++ b/sc/shared/src/test/scala/special/wrappers/WOptionTests.scala @@ -1,7 +1,6 @@ package special.wrappers import scala.language.reflectiveCalls -import scalan.Library class WOptionTests extends WrappersTests { From 3ffafe76a8bb42b948d8ba109aa6b03c44cdecdb Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Wed, 15 May 2024 20:12:39 +0100 Subject: [PATCH 47/65] refactor-ir-cake: removed SigmaLibrary.scala --- .../main/scala/scalan/GraphIRReflection.scala | 25 +++++++++---------- sc/shared/src/main/scala/scalan/Scalan.scala | 14 ++++++++--- .../scala/sigmastate/eval/GraphBuilding.scala | 4 +-- .../scala/sigmastate/eval/SigmaLibrary.scala | 17 ------------- .../scala/sigmastate/eval/TreeBuilding.scala | 3 ++- .../scala/special/sigma/SigmaDslUnit.scala | 3 +-- .../special/sigma/impl/SigmaDslImpl.scala | 8 +++--- .../src/test/scala/scalan/TestLibrary.scala | 2 ++ 8 files changed, 32 insertions(+), 44 deletions(-) delete mode 100644 sc/shared/src/main/scala/sigmastate/eval/SigmaLibrary.scala diff --git a/sc/shared/src/main/scala/scalan/GraphIRReflection.scala b/sc/shared/src/main/scala/scalan/GraphIRReflection.scala index 787873035d..86244fb675 100644 --- a/sc/shared/src/main/scala/scalan/GraphIRReflection.scala +++ b/sc/shared/src/main/scala/scalan/GraphIRReflection.scala @@ -3,7 +3,6 @@ package scalan import scalan.primitives.Thunks import sigma.reflection.ReflectionData.registerClassEntry import sigma.reflection.{ReflectionData, mkConstructor, mkMethod} -import sigmastate.eval.SigmaLibrary import sigma.Colls import sigma.SigmaDsl import sigma.data.RType @@ -211,7 +210,7 @@ object GraphIRReflection { } { val clazz = classOf[SigmaDsl#AvlTree] - val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + val ctx = null.asInstanceOf[Scalan] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "updateOperations", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => @@ -269,7 +268,7 @@ object GraphIRReflection { } { val clazz = classOf[SigmaDsl#Box] - val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + val ctx = null.asInstanceOf[Scalan] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "value", Array[Class[_]]()) { (obj, _) => @@ -302,7 +301,7 @@ object GraphIRReflection { { val clazz = classOf[SigmaDsl#Context] - val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + val ctx = null.asInstanceOf[Scalan] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "LastBlockUtxoRootHash", Array[Class[_]]()) { (obj, args) => @@ -343,7 +342,7 @@ object GraphIRReflection { } { val clazz = classOf[SigmaDsl#GroupElement] - val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + val ctx = null.asInstanceOf[Scalan] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "exp", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => @@ -363,7 +362,7 @@ object GraphIRReflection { } { val clazz = classOf[SigmaDsl#Header] - val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + val ctx = null.asInstanceOf[Scalan] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "minerPk", Array[Class[_]]()) { (obj, args) => @@ -416,7 +415,7 @@ object GraphIRReflection { } { val clazz = classOf[SigmaDsl#PreHeader] - val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + val ctx = null.asInstanceOf[Scalan] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "minerPk", Array[Class[_]]()) { (obj, _) => @@ -445,7 +444,7 @@ object GraphIRReflection { } { val clazz = classOf[SigmaDsl#SigmaDslBuilder] - val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + val ctx = null.asInstanceOf[Scalan] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "byteArrayToLong", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => @@ -512,7 +511,7 @@ object GraphIRReflection { ) } - { val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + { val ctx = null.asInstanceOf[Scalan] // ok! type level only val clazz = classOf[ctx.WOption.WOptionElem[_, _]] registerClassEntry(clazz, constructors = Array( @@ -525,7 +524,7 @@ object GraphIRReflection { } { val clazz = classOf[WRTypes#WRType[_]] - val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + val ctx = null.asInstanceOf[Scalan] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "name", Array[Class[_]]()) { (obj, _) => @@ -535,7 +534,7 @@ object GraphIRReflection { ) } - { val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + { val ctx = null.asInstanceOf[Scalan] // ok! type level only val clazz = classOf[ctx.WRType.WRTypeElem[_, _]] registerClassEntry(clazz, constructors = Array( @@ -547,7 +546,7 @@ object GraphIRReflection { ) } - { val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + { val ctx = null.asInstanceOf[Scalan] // ok! type level only val clazz = classOf[ctx.Coll.CollElem[_, _]] registerClassEntry(clazz, constructors = Array( @@ -560,7 +559,7 @@ object GraphIRReflection { } { val clazz = classOf[wrappers.special.WSpecialPredefs#WSpecialPredefCompanion] - val ctx = null.asInstanceOf[SigmaLibrary] // ok! type level only + val ctx = null.asInstanceOf[Scalan] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "some", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => diff --git a/sc/shared/src/main/scala/scalan/Scalan.scala b/sc/shared/src/main/scala/scalan/Scalan.scala index a466df29fa..b6e9ae2efd 100644 --- a/sc/shared/src/main/scala/scalan/Scalan.scala +++ b/sc/shared/src/main/scala/scalan/Scalan.scala @@ -2,7 +2,7 @@ package scalan import scalan.primitives._ import scalan.staged.Transforming -import sigma.CollsModule +import sigma.{CollsModule, SigmaDslModule} import sigma.data.{Nullable, RType} import sigma.util.MemoizedFunc import special.wrappers.WrappersModule @@ -20,7 +20,7 @@ import special.wrappers.WrappersModule * in classed derived from `Scalan`, this is significant benefit over * *everything is global* design. */ - trait Scalan +trait Scalan extends TypeDescs with MethodCalls with Tuples @@ -38,7 +38,9 @@ import special.wrappers.WrappersModule with Modules with DefRewriting with WrappersModule - with CollsModule { + with CollsModule + with sigma.wrappers.WrappersModule + with SigmaDslModule { import WOption._ import WRType._ @@ -72,6 +74,11 @@ import special.wrappers.WrappersModule def colBuilder: Ref[CollBuilder] + implicit lazy val wRTypeAnyElement: Elem[WRType[Any]] = wRTypeElement(AnyElement) + + /** During compilation represent a global value Global, see also SGlobal type. */ + def sigmaDslBuilder: Ref[SigmaDslBuilder] + object IsNumericToInt { def unapply(d: Def[_]): Nullable[Ref[A] forSome {type A}] = d match { case ApplyUnOp(_: NumericToInt[_], x) => Nullable(x.asInstanceOf[Ref[A] forSome {type A}]) @@ -147,6 +154,5 @@ import special.wrappers.WrappersModule super.invokeUnlifted(e, mc, dataEnv) } - } diff --git a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala index 4a126754a5..ebfd0c8e90 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala @@ -1,7 +1,7 @@ package sigmastate.eval import org.ergoplatform._ -import scalan.MutableLazy +import scalan.{MutableLazy, Scalan} import sigma.{SigmaException, ast} import sigma.ast.TypeCodes.LastConstantCode import sigma.ast.Value.Typed @@ -27,7 +27,7 @@ import scala.collection.mutable.ArrayBuffer * CSE however means the original structure of source code may not be preserved in the * resulting ErgoTree. * */ -trait GraphBuilding extends SigmaLibrary { IR: IRContext => +trait GraphBuilding extends Scalan { IR: IRContext => import AvlTree._ import BigInt._ import Box._ diff --git a/sc/shared/src/main/scala/sigmastate/eval/SigmaLibrary.scala b/sc/shared/src/main/scala/sigmastate/eval/SigmaLibrary.scala deleted file mode 100644 index ea0329e3db..0000000000 --- a/sc/shared/src/main/scala/sigmastate/eval/SigmaLibrary.scala +++ /dev/null @@ -1,17 +0,0 @@ -package sigmastate.eval - -import scalan.Scalan -import sigma.SigmaDslModule - -/** Main trait which represents sigma operations in graph IR cake. */ -trait SigmaLibrary extends Scalan - with sigma.wrappers.WrappersModule - with SigmaDslModule -{ - import WRType._ - - implicit lazy val wRTypeAnyElement: Elem[WRType[Any]] = wRTypeElement(AnyElement) - - /** During compilation represent a global value Global, see also SGlobal type. */ - def sigmaDslBuilder: Ref[SigmaDslBuilder] -} diff --git a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala index 11ae0b85f4..770e7a408f 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala @@ -3,6 +3,7 @@ package sigmastate.eval import sigma.ast._ import org.ergoplatform._ +import scalan.Scalan import sigma.ast.syntax.ValueOps import sigma.serialization.OpCodes._ import sigma.serialization.ConstantStore @@ -24,7 +25,7 @@ import sigma.serialization.ValueCodes.OpCode * * @see buildTree method * */ -trait TreeBuilding extends SigmaLibrary { IR: IRContext => +trait TreeBuilding extends Scalan { IR: IRContext => import Liftables._ import Context._ import SigmaProp._ diff --git a/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala b/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala index 48548226a5..91add24b4d 100644 --- a/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala +++ b/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala @@ -1,8 +1,7 @@ package sigma { import scalan._ - import sigmastate.eval.SigmaLibrary - trait SigmaDsl extends Base { self: SigmaLibrary => + trait SigmaDsl extends Base { self: Scalan => trait BigInt extends Def[BigInt] { def add(that: Ref[BigInt]): Ref[BigInt]; def subtract(that: Ref[BigInt]): Ref[BigInt]; diff --git a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala index 70fb35c329..a79b006515 100644 --- a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala +++ b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala @@ -2,18 +2,16 @@ package sigma import scala.language.{existentials, implicitConversions} import scalan._ -import sigmastate.eval.SigmaLibrary import scala.collection.compat.immutable.ArraySeq package impl { import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} - import sigmastate.eval.SigmaLibrary // Abs ----------------------------------- -trait SigmaDslDefs extends scalan.Scalan with SigmaDsl { - self: SigmaLibrary => +trait SigmaDslDefs extends Base with SigmaDsl { + self: Scalan => registerModule(SigmaDslModule) @@ -2326,4 +2324,4 @@ object SigmaDslModule extends scalan.ModuleInfo("sigma", "SigmaDsl") { } } -trait SigmaDslModule extends sigma.impl.SigmaDslDefs {self: SigmaLibrary =>} +trait SigmaDslModule extends sigma.impl.SigmaDslDefs {self: Scalan =>} diff --git a/sc/shared/src/test/scala/scalan/TestLibrary.scala b/sc/shared/src/test/scala/scalan/TestLibrary.scala index d78312317f..c3d8a5beb8 100644 --- a/sc/shared/src/test/scala/scalan/TestLibrary.scala +++ b/sc/shared/src/test/scala/scalan/TestLibrary.scala @@ -2,6 +2,8 @@ package scalan trait TestLibrary extends Scalan { import CollBuilder._ + import SigmaDslBuilder._ val reflection = (GraphIRReflection) lazy val colBuilder: Ref[CollBuilder] = variable[CollBuilder] + lazy val sigmaDslBuilder: Ref[SigmaDslBuilder] = variable[SigmaDslBuilder] } From 30d3bd9ef588b0e07f7258af71c5a0dab139822e Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Wed, 15 May 2024 20:34:54 +0100 Subject: [PATCH 48/65] refactor-ir-cake: Scalan moved to sigma.compiler package --- sc/js/src/test/scala/scalan/Platform.scala | 2 ++ sc/jvm/src/test/scala/scalan/Platform.scala | 1 + .../scalan/compilation/GraphVizExport.scala | 2 +- .../InterpreterReflectionGeneratorTests.scala | 4 +-- .../sigmastate/ReflectionGenerator.scala | 2 +- .../{scalan => sigma/compiler}/Base.scala | 27 ++++++++++--------- .../compiler}/DefRewriting.scala | 3 ++- .../{scalan => sigma/compiler}/Entities.scala | 2 +- .../compiler}/Exceptions.scala | 0 .../compiler}/GraphIRReflection.scala | 11 ++++---- .../compiler}/MethodCalls.scala | 12 ++++----- .../compiler}/ModuleInfo.scala | 2 +- .../{scalan => sigma/compiler}/Modules.scala | 2 +- .../compiler}/MutableLazy.scala | 0 .../{scalan => sigma/compiler}/Scalan.scala | 12 +++++---- .../compiler}/TypeDescs.scala | 16 +++++------ .../compiler}/core/Variance.scala | 0 .../compiler}/meta/SSymName.scala | 0 .../compiler}/primitives/Equal.scala | 4 +-- .../compiler}/primitives/Functions.scala | 15 +++++------ .../compiler}/primitives/IfThenElse.scala | 4 +-- .../compiler}/primitives/LogicalOps.scala | 4 +-- .../compiler}/primitives/NumericOps.scala | 4 +-- .../compiler}/primitives/OrderingOps.scala | 4 +-- .../compiler}/primitives/Thunks.scala | 9 +++---- .../compiler}/primitives/Tuples.scala | 7 ++--- .../compiler}/primitives/UnBinOps.scala | 4 +-- .../compiler}/primitives/UniversalOps.scala | 4 +-- .../compiler}/staged/AstGraphs.scala | 10 +++---- .../compiler}/staged/ProgramGraphs.scala | 10 +++---- .../compiler}/staged/Transforming.scala | 12 ++++----- .../scala/sigmastate/eval/GraphBuilding.scala | 3 ++- .../scala/sigmastate/eval/TreeBuilding.scala | 2 +- .../scala/sigmastate/lang/SigmaCompiler.scala | 2 +- .../scala/special/collection/CollsUnit.scala | 1 + .../special/collection/impl/CollsImpl.scala | 7 +++-- .../scala/special/sigma/SigmaDslUnit.scala | 1 + .../special/sigma/impl/SigmaDslImpl.scala | 4 ++- .../sigma/wrappers/WrappersModule.scala | 2 +- .../special/wrappers/WrappersModule.scala | 2 +- .../main/scala/wrappers/scala/WOptions.scala | 2 +- .../wrappers/scala/impl/WOptionsImpl.scala | 7 +++-- .../main/scala/wrappers/scalan/WRTypes.scala | 1 + .../wrappers/scalan/impl/WRTypesImpl.scala | 7 +++-- .../wrappers/special/WSpecialPredefs.scala | 1 + .../special/impl/WSpecialPredefsImpl.scala | 6 +++-- .../test/scala/scalan/BaseLiftableTests.scala | 2 ++ .../src/test/scala/scalan/LibraryTests.scala | 1 + .../src/test/scala/scalan/TestContexts.scala | 1 + .../src/test/scala/scalan/TestLibrary.scala | 2 ++ .../test/scala/sigma/CollsStagingTests.scala | 1 + 51 files changed, 135 insertions(+), 109 deletions(-) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/Base.scala (98%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/DefRewriting.scala (99%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/Entities.scala (99%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/Exceptions.scala (100%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/GraphIRReflection.scala (99%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/MethodCalls.scala (97%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/ModuleInfo.scala (95%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/Modules.scala (95%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/MutableLazy.scala (100%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/Scalan.scala (95%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/TypeDescs.scala (98%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/core/Variance.scala (100%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/meta/SSymName.scala (100%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/primitives/Equal.scala (93%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/primitives/Functions.scala (98%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/primitives/IfThenElse.scala (96%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/primitives/LogicalOps.scala (97%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/primitives/NumericOps.scala (98%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/primitives/OrderingOps.scala (97%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/primitives/Thunks.scala (99%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/primitives/Tuples.scala (96%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/primitives/UnBinOps.scala (97%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/primitives/UniversalOps.scala (98%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/staged/AstGraphs.scala (98%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/staged/ProgramGraphs.scala (96%) rename sc/shared/src/main/scala/{scalan => sigma/compiler}/staged/Transforming.scala (98%) diff --git a/sc/js/src/test/scala/scalan/Platform.scala b/sc/js/src/test/scala/scalan/Platform.scala index 5f938111d2..2349a1f444 100644 --- a/sc/js/src/test/scala/scalan/Platform.scala +++ b/sc/js/src/test/scala/scalan/Platform.scala @@ -1,5 +1,7 @@ package scalan +import sigma.compiler.Scalan + import scala.annotation.unused object Platform { diff --git a/sc/jvm/src/test/scala/scalan/Platform.scala b/sc/jvm/src/test/scala/scalan/Platform.scala index 43041a92c6..b9c65374c2 100644 --- a/sc/jvm/src/test/scala/scalan/Platform.scala +++ b/sc/jvm/src/test/scala/scalan/Platform.scala @@ -3,6 +3,7 @@ package scalan import scalan.compilation.GraphVizExport import sigma.util.FileUtil import org.scalatest.Assertions +import sigma.compiler.Scalan object Platform { /** Output graph given by symbols in `sfs` to files. diff --git a/sc/jvm/src/test/scala/scalan/compilation/GraphVizExport.scala b/sc/jvm/src/test/scala/scalan/compilation/GraphVizExport.scala index 8568e6c1db..c5b7f16cca 100644 --- a/sc/jvm/src/test/scala/scalan/compilation/GraphVizExport.scala +++ b/sc/jvm/src/test/scala/scalan/compilation/GraphVizExport.scala @@ -2,8 +2,8 @@ package scalan.compilation import java.awt.Desktop import java.io.{File, PrintWriter} -import scalan.Scalan import scalan.core.ScalaNameUtil +import sigma.compiler.Scalan import sigma.util.{FileUtil, ProcessUtil, StringUtil} import scala.annotation.unused diff --git a/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala b/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala index 5d81e0d19a..2a65dfedf5 100644 --- a/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala +++ b/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala @@ -2,7 +2,7 @@ package sigmastate import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec -import scalan.TypeDescs +import sigma.compiler.{Scalan, TypeDescs} import sigma.reflection.ReflectionData.registerClassEntry import sigma.reflection.SRConstructor @@ -37,7 +37,7 @@ class InterpreterReflectionGeneratorTests extends AnyPropSpec with Matchers { } property("inner class") { - val ctx = null.asInstanceOf[scalan.Scalan] // ok! type level only + val ctx = null.asInstanceOf[Scalan] // ok! type level only val clazz = classOf[ctx.Coll.CollElem[_, _]] registerClassEntry(clazz, constructors = Array( diff --git a/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala b/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala index 1375b48d99..735297d119 100644 --- a/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala +++ b/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala @@ -1,6 +1,6 @@ package sigmastate -import scalan.{Base, TypeDescs} +import sigma.compiler.{Base, TypeDescs} import sigma.reflection._ import scala.annotation.unused import scala.collection.mutable diff --git a/sc/shared/src/main/scala/scalan/Base.scala b/sc/shared/src/main/scala/sigma/compiler/Base.scala similarity index 98% rename from sc/shared/src/main/scala/scalan/Base.scala rename to sc/shared/src/main/scala/sigma/compiler/Base.scala index cc29af45b9..b6e81f2a6f 100644 --- a/sc/shared/src/main/scala/scalan/Base.scala +++ b/sc/shared/src/main/scala/sigma/compiler/Base.scala @@ -1,14 +1,15 @@ -package scalan +package sigma.compiler import debox.{cfor, Buffer => DBuffer} -import sigma.data.{AVHashMap, Nullable, RType} +import scalan.MutableLazy import sigma.data.OverloadHack.Overloaded1 -import sigma.util.StringUtil +import sigma.data.{AVHashMap, Nullable, RType} import sigma.reflection.RConstructor +import sigma.util.StringUtil import java.util.Arrays -import scala.annotation.{implicitNotFound, unused} import scala.annotation.unchecked.uncheckedVariance +import scala.annotation.{implicitNotFound, unused} import scala.collection.compat.immutable.ArraySeq import scala.collection.mutable import scala.language.implicitConversions @@ -51,7 +52,7 @@ abstract class Base { scalan: Scalan => /** Base class for all IR nodes/operations/definitions. */ abstract class Node extends Product { - private[scalan] var _nodeId: Int = freshId + private[compiler] var _nodeId: Int = freshId /** Unique id of the graph node assigned for each new instance using * `freshId` generator. @@ -365,8 +366,8 @@ abstract class Base { scalan: Scalan => /** Most of the references are initialized when created. * These methods are used in core to assign new value for the reference.*/ - private[scalan] def assignDef[B >: T](d: Def[B]): Unit - private[scalan] def assignDefFrom[B >: T](ref: Ref[B]): Unit + private[compiler] def assignDef[B >: T](d: Def[B]): Unit + private[compiler] def assignDefFrom[B >: T](ref: Ref[B]): Unit /** Whether the underlying node is Placeholder. */ @inline final def isPlaceholder: Boolean = node.isInstanceOf[Placeholder[_]] @@ -550,7 +551,7 @@ abstract class Base { scalan: Scalan => } /** Prepend owner parameter depending on its kind. */ - private[scalan] def addOwnerParameter(ownerType: OwnerKind, params: Seq[Any]): Seq[AnyRef] = { + private[compiler] def addOwnerParameter(ownerType: OwnerKind, params: Seq[Any]): Seq[AnyRef] = { val finalParams = (ownerType match { case EntityObjectOwner(obj) => obj +: params case ScalanOwner => scalan +: params @@ -601,7 +602,7 @@ abstract class Base { scalan: Scalan => override def elem: Elem[T @uncheckedVariance] = _node.resultType override def node: Def[T] = _node - private[scalan] def assignDefInternal[B >: T](d: Def[B]): Unit = { + private[compiler] def assignDefInternal[B >: T](d: Def[B]): Unit = { assert(_node.isInstanceOf[Placeholder[_]]) assert(_node.nodeId > 0) val tab = _symbolTable @@ -612,12 +613,12 @@ abstract class Base { scalan: Scalan => _node = d.asInstanceOf[Def[T]] } - private[scalan] def assignDef[B >: T](d: Def[B]): Unit = { + private[compiler] def assignDef[B >: T](d: Def[B]): Unit = { assignDefInternal(d) updateSymbolTable(this, d) } - private[scalan] def assignDefFrom[B >: T](sym: Ref[B]): Unit = { + private[compiler] def assignDefFrom[B >: T](sym: Ref[B]): Unit = { assignDefInternal(sym.node) } @@ -670,7 +671,7 @@ abstract class Base { scalan: Scalan => } /** Should be invoked to reset IR global node counter. */ - @inline final private[scalan] def resetIdCounter() = { currId = 0 } + @inline final private[compiler] def resetIdCounter() = { currId = 0 } /** Create or find symbol (node Ref) which refers to the given node in the table of all created symbols. * The d.nodeId is the index in the _symbolTable which is DBuffer (backed by Array) @@ -825,7 +826,7 @@ abstract class Base { scalan: Scalan => * @tparam T * @return The symbol of the graph which is semantically(up to rewrites) equivalent to d */ - protected[scalan] def toExp[T](d: Def[T], newSym: => Ref[T]): Ref[T] = { + protected[compiler] def toExp[T](d: Def[T], newSym: => Ref[T]): Ref[T] = { var res = findOrCreateDefinition(d, newSym) var currSym = res var currDef = d diff --git a/sc/shared/src/main/scala/scalan/DefRewriting.scala b/sc/shared/src/main/scala/sigma/compiler/DefRewriting.scala similarity index 99% rename from sc/shared/src/main/scala/scalan/DefRewriting.scala rename to sc/shared/src/main/scala/sigma/compiler/DefRewriting.scala index 114fb1b0e6..38930d0307 100644 --- a/sc/shared/src/main/scala/scalan/DefRewriting.scala +++ b/sc/shared/src/main/scala/sigma/compiler/DefRewriting.scala @@ -1,5 +1,6 @@ -package scalan +package sigma.compiler +import scalan.DelayInvokeException import sigma.data.ExactNumeric trait DefRewriting { scalan: Scalan => diff --git a/sc/shared/src/main/scala/scalan/Entities.scala b/sc/shared/src/main/scala/sigma/compiler/Entities.scala similarity index 99% rename from sc/shared/src/main/scala/scalan/Entities.scala rename to sc/shared/src/main/scala/sigma/compiler/Entities.scala index 8a32dcde10..2cce7fe7d7 100644 --- a/sc/shared/src/main/scala/scalan/Entities.scala +++ b/sc/shared/src/main/scala/sigma/compiler/Entities.scala @@ -1,4 +1,4 @@ -package scalan +package sigma.compiler /** A slice in the Scalan cake with base classes for various descriptors. */ trait Entities extends TypeDescs { self: Scalan => diff --git a/sc/shared/src/main/scala/scalan/Exceptions.scala b/sc/shared/src/main/scala/sigma/compiler/Exceptions.scala similarity index 100% rename from sc/shared/src/main/scala/scalan/Exceptions.scala rename to sc/shared/src/main/scala/sigma/compiler/Exceptions.scala diff --git a/sc/shared/src/main/scala/scalan/GraphIRReflection.scala b/sc/shared/src/main/scala/sigma/compiler/GraphIRReflection.scala similarity index 99% rename from sc/shared/src/main/scala/scalan/GraphIRReflection.scala rename to sc/shared/src/main/scala/sigma/compiler/GraphIRReflection.scala index 86244fb675..054cfed9b7 100644 --- a/sc/shared/src/main/scala/scalan/GraphIRReflection.scala +++ b/sc/shared/src/main/scala/sigma/compiler/GraphIRReflection.scala @@ -1,11 +1,10 @@ -package scalan +package sigma.compiler -import scalan.primitives.Thunks +import sigma.compiler.primitives.Thunks +import sigma.{Colls, SigmaDsl} +import sigma.data.RType import sigma.reflection.ReflectionData.registerClassEntry import sigma.reflection.{ReflectionData, mkConstructor, mkMethod} -import sigma.Colls -import sigma.SigmaDsl -import sigma.data.RType import special.wrappers.{OptionWrapSpec, RTypeWrapSpec} import wrappers.scalan.WRTypes @@ -23,7 +22,7 @@ object GraphIRReflection { val reflection = ReflectionData { val clazz = classOf[wrappers.scala.WOptions#WOption[_]] - val ctx = null.asInstanceOf[scalan.Scalan] // ok! type level only + val ctx = null.asInstanceOf[Scalan] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "filter", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => diff --git a/sc/shared/src/main/scala/scalan/MethodCalls.scala b/sc/shared/src/main/scala/sigma/compiler/MethodCalls.scala similarity index 97% rename from sc/shared/src/main/scala/scalan/MethodCalls.scala rename to sc/shared/src/main/scala/sigma/compiler/MethodCalls.scala index 14212df632..4a0a189edd 100644 --- a/sc/shared/src/main/scala/scalan/MethodCalls.scala +++ b/sc/shared/src/main/scala/sigma/compiler/MethodCalls.scala @@ -1,12 +1,12 @@ -package scalan +package sigma.compiler -import scala.annotation.{tailrec, unused} -import scala.reflect.ClassTag -import debox.{Buffer => DBuffer} -import debox.cfor +import debox.{cfor, Buffer => DBuffer} +import scalan.DelayInvokeException import sigma.reflection.RMethod import sigma.util.CollectionUtil.TraversableOps +import scala.annotation.{tailrec, unused} + trait MethodCalls extends Base { self: Scalan => def delayInvoke = throw new DelayInvokeException @@ -116,7 +116,7 @@ trait MethodCalls extends Base { self: Scalan => def rewriteNonInvokableMethodCall(@unused mc: MethodCall): Ref[_] = null /** Generic helper to call the given method on the given receiver node. */ - private[scalan] def invokeMethod[A](receiver: Sym, m: RMethod, args: Array[AnyRef], + private[compiler] def invokeMethod[A](receiver: Sym, m: RMethod, args: Array[AnyRef], onInvokeSuccess: Any => A, onInvokeException: Throwable => A, onInvokeImpossible: => A): A = { diff --git a/sc/shared/src/main/scala/scalan/ModuleInfo.scala b/sc/shared/src/main/scala/sigma/compiler/ModuleInfo.scala similarity index 95% rename from sc/shared/src/main/scala/scalan/ModuleInfo.scala rename to sc/shared/src/main/scala/sigma/compiler/ModuleInfo.scala index 86fce48ce6..8c2030b1c7 100644 --- a/sc/shared/src/main/scala/scalan/ModuleInfo.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ModuleInfo.scala @@ -1,4 +1,4 @@ -package scalan +package sigma.compiler import scalan.meta.SSymName diff --git a/sc/shared/src/main/scala/scalan/Modules.scala b/sc/shared/src/main/scala/sigma/compiler/Modules.scala similarity index 95% rename from sc/shared/src/main/scala/scalan/Modules.scala rename to sc/shared/src/main/scala/sigma/compiler/Modules.scala index 989f2c524c..94cbaf9816 100644 --- a/sc/shared/src/main/scala/scalan/Modules.scala +++ b/sc/shared/src/main/scala/sigma/compiler/Modules.scala @@ -1,4 +1,4 @@ -package scalan +package sigma.compiler trait Modules extends Base { self: Scalan => diff --git a/sc/shared/src/main/scala/scalan/MutableLazy.scala b/sc/shared/src/main/scala/sigma/compiler/MutableLazy.scala similarity index 100% rename from sc/shared/src/main/scala/scalan/MutableLazy.scala rename to sc/shared/src/main/scala/sigma/compiler/MutableLazy.scala diff --git a/sc/shared/src/main/scala/scalan/Scalan.scala b/sc/shared/src/main/scala/sigma/compiler/Scalan.scala similarity index 95% rename from sc/shared/src/main/scala/scalan/Scalan.scala rename to sc/shared/src/main/scala/sigma/compiler/Scalan.scala index b6e9ae2efd..76fee8c7f1 100644 --- a/sc/shared/src/main/scala/scalan/Scalan.scala +++ b/sc/shared/src/main/scala/sigma/compiler/Scalan.scala @@ -1,10 +1,11 @@ -package scalan +package sigma.compiler -import scalan.primitives._ -import scalan.staged.Transforming -import sigma.{CollsModule, SigmaDslModule} +import scalan._ +import sigma.compiler.primitives.{Equal, Functions, IfThenElse, LogicalOps, NumericOps, OrderingOps, Thunks, Tuples, UnBinOps, UniversalOps} +import sigma.compiler.staged.Transforming import sigma.data.{Nullable, RType} import sigma.util.MemoizedFunc +import sigma.{CollsModule, SigmaDslModule} import special.wrappers.WrappersModule /** Aggregate cake with all inter-dependent modules assembled together. @@ -42,9 +43,10 @@ trait Scalan with sigma.wrappers.WrappersModule with SigmaDslModule { + import Coll._ + import CollBuilder._ import WOption._ import WRType._ - import Coll._; import CollBuilder._; import WSpecialPredef._ type LazyRep[T] = MutableLazy[Ref[T]] diff --git a/sc/shared/src/main/scala/scalan/TypeDescs.scala b/sc/shared/src/main/scala/sigma/compiler/TypeDescs.scala similarity index 98% rename from sc/shared/src/main/scala/scalan/TypeDescs.scala rename to sc/shared/src/main/scala/sigma/compiler/TypeDescs.scala index fdef77a108..875c3f7b9a 100644 --- a/sc/shared/src/main/scala/scalan/TypeDescs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/TypeDescs.scala @@ -1,10 +1,5 @@ -package scalan +package sigma.compiler -import scala.language.implicitConversions -import scala.annotation.implicitNotFound -import scala.collection.immutable.ListMap - -import scala.collection.mutable import debox.cfor import scalan.core.{Contravariant, Covariant, Variance} import sigma.data.{AVHashMap, Lazy, Nullable, RType} @@ -12,6 +7,11 @@ import sigma.reflection.{RClass, RConstructor, RMethod} import sigma.util.CollectionUtil import special.wrappers.WrapSpec +import scala.annotation.implicitNotFound +import scala.collection.immutable.ListMap +import scala.collection.mutable +import scala.language.implicitConversions + abstract class TypeDescs extends Base { self: Scalan => /** Helper type case method. */ @@ -267,7 +267,7 @@ abstract class TypeDescs extends Base { self: Scalan => e.invokeUnlifted(mc, dataEnv) /** Get first (and the only) constructor of the `clazz`. */ - private[scalan] final def getConstructor(clazz: RClass[_]): RConstructor[_] = { + private[compiler] final def getConstructor(clazz: RClass[_]): RConstructor[_] = { val constructors = clazz.getConstructors() if (constructors.length != 1) !!!(s"Element class $clazz has ${constructors.length} constructors, 1 expected") @@ -297,7 +297,7 @@ abstract class TypeDescs extends Base { self: Scalan => protected val elemCache = AVHashMap[RClass[_], ElemCacheEntry](1000) - private[scalan] final def cachedElem0(clazz: RClass[_], optConstructor: Nullable[RConstructor[_]], args: Seq[AnyRef]): Elem[_] = { + private[compiler] final def cachedElem0(clazz: RClass[_], optConstructor: Nullable[RConstructor[_]], args: Seq[AnyRef]): Elem[_] = { val entry = elemCache.get(clazz) match { case Nullable(entry) => entry case _ => diff --git a/sc/shared/src/main/scala/scalan/core/Variance.scala b/sc/shared/src/main/scala/sigma/compiler/core/Variance.scala similarity index 100% rename from sc/shared/src/main/scala/scalan/core/Variance.scala rename to sc/shared/src/main/scala/sigma/compiler/core/Variance.scala diff --git a/sc/shared/src/main/scala/scalan/meta/SSymName.scala b/sc/shared/src/main/scala/sigma/compiler/meta/SSymName.scala similarity index 100% rename from sc/shared/src/main/scala/scalan/meta/SSymName.scala rename to sc/shared/src/main/scala/sigma/compiler/meta/SSymName.scala diff --git a/sc/shared/src/main/scala/scalan/primitives/Equal.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/Equal.scala similarity index 93% rename from sc/shared/src/main/scala/scalan/primitives/Equal.scala rename to sc/shared/src/main/scala/sigma/compiler/primitives/Equal.scala index 4d64e94383..f0aab234b2 100644 --- a/sc/shared/src/main/scala/scalan/primitives/Equal.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/Equal.scala @@ -1,6 +1,6 @@ -package scalan.primitives +package sigma.compiler.primitives -import scalan.{Base, Scalan} +import sigma.compiler.{Base, Scalan} import scala.annotation.unused diff --git a/sc/shared/src/main/scala/scalan/primitives/Functions.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala similarity index 98% rename from sc/shared/src/main/scala/scalan/primitives/Functions.scala rename to sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala index 9026461777..f572f2b126 100644 --- a/sc/shared/src/main/scala/scalan/primitives/Functions.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala @@ -1,15 +1,14 @@ -package scalan.primitives +package sigma.compiler.primitives -import java.util -import scalan.staged.ProgramGraphs -import scalan.{Base, Scalan} -import debox.{Buffer => DBuffer} - -import scala.language.implicitConversions -import debox.cfor +import debox.{cfor, Buffer => DBuffer} +import sigma.compiler.staged.ProgramGraphs +import sigma.compiler.{Base, Scalan} import sigma.data.{Lazy, Nullable, emptyDBufferOfInt} import sigma.util.GraphUtil +import java.util +import scala.language.implicitConversions + trait Functions extends Base with ProgramGraphs { self: Scalan => implicit class LambdaOps[A,B](f: Ref[A => B]) { diff --git a/sc/shared/src/main/scala/scalan/primitives/IfThenElse.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/IfThenElse.scala similarity index 96% rename from sc/shared/src/main/scala/scalan/primitives/IfThenElse.scala rename to sc/shared/src/main/scala/sigma/compiler/primitives/IfThenElse.scala index 22fd2095d7..57d742b194 100644 --- a/sc/shared/src/main/scala/scalan/primitives/IfThenElse.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/IfThenElse.scala @@ -1,6 +1,6 @@ -package scalan.primitives +package sigma.compiler.primitives -import scalan.{Base, Scalan} +import sigma.compiler.{Base, Scalan} trait IfThenElse extends Base { self: Scalan => diff --git a/sc/shared/src/main/scala/scalan/primitives/LogicalOps.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/LogicalOps.scala similarity index 97% rename from sc/shared/src/main/scala/scalan/primitives/LogicalOps.scala rename to sc/shared/src/main/scala/sigma/compiler/primitives/LogicalOps.scala index e81b546139..16510eb1fa 100644 --- a/sc/shared/src/main/scala/scalan/primitives/LogicalOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/LogicalOps.scala @@ -1,6 +1,6 @@ -package scalan.primitives +package sigma.compiler.primitives -import scalan.{Base, Scalan} +import sigma.compiler.{Base, Scalan} /** Slice in Scala cake with definitions of logical operations. */ trait LogicalOps extends Base { self: Scalan => diff --git a/sc/shared/src/main/scala/scalan/primitives/NumericOps.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/NumericOps.scala similarity index 98% rename from sc/shared/src/main/scala/scalan/primitives/NumericOps.scala rename to sc/shared/src/main/scala/sigma/compiler/primitives/NumericOps.scala index 3c3d80e94d..8783df2ce1 100644 --- a/sc/shared/src/main/scala/scalan/primitives/NumericOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/NumericOps.scala @@ -1,6 +1,6 @@ -package scalan.primitives +package sigma.compiler.primitives -import scalan.{Base, Scalan} +import sigma.compiler.{Base, Scalan} import sigma.data.{ExactIntegral, ExactNumeric} /** Slice in Scala cake with definitions of numeric operations. */ diff --git a/sc/shared/src/main/scala/scalan/primitives/OrderingOps.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/OrderingOps.scala similarity index 97% rename from sc/shared/src/main/scala/scalan/primitives/OrderingOps.scala rename to sc/shared/src/main/scala/sigma/compiler/primitives/OrderingOps.scala index 8e6f5e0134..d125787d07 100644 --- a/sc/shared/src/main/scala/scalan/primitives/OrderingOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/OrderingOps.scala @@ -1,6 +1,6 @@ -package scalan.primitives +package sigma.compiler.primitives -import scalan.{Base, Scalan} +import sigma.compiler.{Base, Scalan} import sigma.data.ExactOrdering import scala.language.implicitConversions diff --git a/sc/shared/src/main/scala/scalan/primitives/Thunks.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/Thunks.scala similarity index 99% rename from sc/shared/src/main/scala/scalan/primitives/Thunks.scala rename to sc/shared/src/main/scala/sigma/compiler/primitives/Thunks.scala index f9f843664d..24b9e97708 100644 --- a/sc/shared/src/main/scala/scalan/primitives/Thunks.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/Thunks.scala @@ -1,15 +1,14 @@ -package scalan.primitives +package sigma.compiler.primitives -import scala.language.{existentials, implicitConversions} -import scalan._ -import debox.{Buffer => DBuffer, Set => DSet} -import debox.cfor +import debox.{cfor, Buffer => DBuffer, Set => DSet} import scalan.core.Covariant +import sigma.compiler.Scalan import sigma.data.{AVHashMap, DFunc, Lazy, Nullable, RType} import sigma.reflection.RClass import sigma.util.GraphUtil import scala.collection.Seq +import scala.language.{existentials, implicitConversions} /** Slice in the [[Scalan]] cake with definitions of Thunk operations. * See https://en.wikipedia.org/wiki/Thunk. diff --git a/sc/shared/src/main/scala/scalan/primitives/Tuples.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/Tuples.scala similarity index 96% rename from sc/shared/src/main/scala/scalan/primitives/Tuples.scala rename to sc/shared/src/main/scala/sigma/compiler/primitives/Tuples.scala index fd201b9574..ae30569c29 100644 --- a/sc/shared/src/main/scala/scalan/primitives/Tuples.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/Tuples.scala @@ -2,11 +2,12 @@ * Author: Alexander Slesarenko * Date: 7/25/12 */ -package scalan.primitives +package sigma.compiler.primitives + +import sigma.compiler.{Base, Scalan} +import sigma.data.AVHashMap -import scalan.{Base, Scalan} import scala.language.implicitConversions -import sigma.data.{AVHashMap} trait Tuples extends Base { self: Scalan => object Pair { diff --git a/sc/shared/src/main/scala/scalan/primitives/UnBinOps.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/UnBinOps.scala similarity index 97% rename from sc/shared/src/main/scala/scalan/primitives/UnBinOps.scala rename to sc/shared/src/main/scala/sigma/compiler/primitives/UnBinOps.scala index 749556bf0e..701239488d 100644 --- a/sc/shared/src/main/scala/scalan/primitives/UnBinOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/UnBinOps.scala @@ -1,6 +1,6 @@ -package scalan.primitives +package sigma.compiler.primitives -import scalan.{Scalan, Base} +import sigma.compiler.{Base, Scalan} trait UnBinOps extends Base { self: Scalan => diff --git a/sc/shared/src/main/scala/scalan/primitives/UniversalOps.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/UniversalOps.scala similarity index 98% rename from sc/shared/src/main/scala/scalan/primitives/UniversalOps.scala rename to sc/shared/src/main/scala/sigma/compiler/primitives/UniversalOps.scala index eaca5821ce..c6dd96f03b 100644 --- a/sc/shared/src/main/scala/scalan/primitives/UniversalOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/UniversalOps.scala @@ -1,6 +1,6 @@ -package scalan.primitives +package sigma.compiler.primitives -import scalan.{Base, Scalan} +import sigma.compiler.{Base, Scalan} trait UniversalOps extends Base { scalan: Scalan => case class HashCode[A]() extends UnOp[A, Int]("hashCode") { diff --git a/sc/shared/src/main/scala/scalan/staged/AstGraphs.scala b/sc/shared/src/main/scala/sigma/compiler/staged/AstGraphs.scala similarity index 98% rename from sc/shared/src/main/scala/scalan/staged/AstGraphs.scala rename to sc/shared/src/main/scala/sigma/compiler/staged/AstGraphs.scala index 7ad5c24f17..09000db191 100644 --- a/sc/shared/src/main/scala/scalan/staged/AstGraphs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/staged/AstGraphs.scala @@ -1,11 +1,11 @@ -package scalan.staged +package sigma.compiler.staged -import scala.collection._ -import scalan.Scalan -import debox.cfor -import debox.{Buffer => DBuffer, Map => DMap, Set => DSet} +import debox.{cfor, Buffer => DBuffer, Map => DMap, Set => DSet} +import sigma.compiler.Scalan import sigma.data.emptyDBufferOfInt +import scala.collection._ + trait AstGraphs extends Transforming { self: Scalan => diff --git a/sc/shared/src/main/scala/scalan/staged/ProgramGraphs.scala b/sc/shared/src/main/scala/sigma/compiler/staged/ProgramGraphs.scala similarity index 96% rename from sc/shared/src/main/scala/scalan/staged/ProgramGraphs.scala rename to sc/shared/src/main/scala/sigma/compiler/staged/ProgramGraphs.scala index ccb351e7a2..1c8617bc74 100644 --- a/sc/shared/src/main/scala/scalan/staged/ProgramGraphs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/staged/ProgramGraphs.scala @@ -1,10 +1,10 @@ -package scalan.staged +package sigma.compiler.staged -import scalan.Scalan -import debox.{Buffer => DBuffer} -import sigma.util.GraphUtil -import debox.cfor +import debox.{cfor, Buffer => DBuffer} +import sigma.compiler.Scalan import sigma.data.{DFunc, Nullable} +import sigma.util.GraphUtil + import scala.collection.compat.immutable.ArraySeq trait ProgramGraphs extends AstGraphs { self: Scalan => diff --git a/sc/shared/src/main/scala/scalan/staged/Transforming.scala b/sc/shared/src/main/scala/sigma/compiler/staged/Transforming.scala similarity index 98% rename from sc/shared/src/main/scala/scalan/staged/Transforming.scala rename to sc/shared/src/main/scala/sigma/compiler/staged/Transforming.scala index a64b998ff6..90cc2dd350 100644 --- a/sc/shared/src/main/scala/scalan/staged/Transforming.scala +++ b/sc/shared/src/main/scala/sigma/compiler/staged/Transforming.scala @@ -1,13 +1,13 @@ -package scalan.staged +package sigma.compiler.staged -import java.util -import scala.language.existentials -import scalan.Scalan -import debox.{Buffer => DBuffer} -import debox.cfor +import debox.{cfor, Buffer => DBuffer} +import sigma.compiler.Scalan import sigma.data.{Lazy, Nullable} import sigma.reflection.RMethod +import java.util +import scala.language.existentials + trait Transforming { self: Scalan => /** Descriptor of a current compiler pass. diff --git a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala index ebfd0c8e90..445edd3594 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala @@ -1,7 +1,7 @@ package sigmastate.eval import org.ergoplatform._ -import scalan.{MutableLazy, Scalan} +import scalan.MutableLazy import sigma.{SigmaException, ast} import sigma.ast.TypeCodes.LastConstantCode import sigma.ast.Value.Typed @@ -14,6 +14,7 @@ import sigma.data.{CSigmaDslBuilder, ExactIntegral, ExactNumeric, ExactOrdering, import sigma.util.Extensions.ByteOps import sigmastate.interpreter.Interpreter.ScriptEnv import sigma.ast.{Ident, Select, Val} +import sigma.compiler.Scalan import sigma.exceptions.GraphBuildingException import sigma.serialization.OpCodes diff --git a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala b/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala index 770e7a408f..4a6bca7d2e 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala +++ b/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala @@ -3,11 +3,11 @@ package sigmastate.eval import sigma.ast._ import org.ergoplatform._ -import scalan.Scalan import sigma.ast.syntax.ValueOps import sigma.serialization.OpCodes._ import sigma.serialization.ConstantStore import sigma.ast.syntax._ +import sigma.compiler.Scalan import sigma.data.{ProveDHTuple, ProveDlog} import scala.collection.mutable.ArrayBuffer diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala index 3e83aa866c..20e1e28471 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala @@ -4,7 +4,6 @@ import fastparse.Parsed import fastparse.Parsed.Success import sigma.kiama.rewriting.Rewriter.{everywherebu, rewrite, rule} import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix -import scalan.GraphIRReflection import sigma.ast.{Exponentiate, MultiplyGroup, SCollectionMethods, SGlobalMethods, SGroupElementMethods, Value, Xor} import sigmastate.eval.IRContext import sigmastate.interpreter.Interpreter.ScriptEnv @@ -14,6 +13,7 @@ import sigmastate.lang.parsers.ParserException import sigma.ast._ import sigma.ast.syntax.SValue import SCollectionMethods.{ExistsMethod, ForallMethod, MapMethod} +import sigma.compiler.GraphIRReflection import sigmastate.InterpreterReflection /** diff --git a/sc/shared/src/main/scala/special/collection/CollsUnit.scala b/sc/shared/src/main/scala/special/collection/CollsUnit.scala index db9922b82f..a057f40f7a 100644 --- a/sc/shared/src/main/scala/special/collection/CollsUnit.scala +++ b/sc/shared/src/main/scala/special/collection/CollsUnit.scala @@ -1,5 +1,6 @@ package sigma { import scalan._ + import sigma.compiler.{Base, Scalan} /** Staged version of collection interfaces which is used in graph-based IR to represent * methods of Coll and CollBuilder. diff --git a/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala b/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala index 382f5fe763..c85621bbbe 100644 --- a/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala +++ b/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala @@ -1,10 +1,13 @@ package sigma -import scala.language.{existentials,implicitConversions} +import scala.language.{existentials, implicitConversions} import scalan._ +import sigma.compiler.Scalan + import scala.collection.compat.immutable.ArraySeq package impl { + import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, Scalan} import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} @@ -634,7 +637,7 @@ object CollBuilder extends EntityObject("CollBuilder") { } -object CollsModule extends scalan.ModuleInfo("sigma", "Colls") { +object CollsModule extends ModuleInfo("sigma", "Colls") { val reflection = GraphIRReflection } } diff --git a/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala b/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala index 91add24b4d..6cc97daba6 100644 --- a/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala +++ b/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala @@ -1,5 +1,6 @@ package sigma { import scalan._ + import sigma.compiler.{Base, Scalan} trait SigmaDsl extends Base { self: Scalan => trait BigInt extends Def[BigInt] { diff --git a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala index a79b006515..760f5094ca 100644 --- a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala +++ b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala @@ -2,10 +2,12 @@ package sigma import scala.language.{existentials, implicitConversions} import scalan._ +import sigma.compiler.Scalan import scala.collection.compat.immutable.ArraySeq package impl { + import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, Scalan} import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} @@ -2319,7 +2321,7 @@ object SigmaDslBuilder extends EntityObject("SigmaDslBuilder") { registerEntityObject("SigmaDslBuilder", SigmaDslBuilder) } -object SigmaDslModule extends scalan.ModuleInfo("sigma", "SigmaDsl") { +object SigmaDslModule extends ModuleInfo("sigma", "SigmaDsl") { val reflection = GraphIRReflection } } diff --git a/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala b/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala index 50869cc4e1..1250487071 100644 --- a/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala +++ b/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala @@ -1,6 +1,6 @@ package sigma.wrappers -import scalan.Scalan +import sigma.compiler.Scalan trait WrappersModule extends special.wrappers.WrappersModule { self: Scalan => } diff --git a/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala b/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala index 745413569a..1a25f6a9d4 100644 --- a/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala +++ b/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala @@ -1,6 +1,6 @@ package special.wrappers -import scalan.Scalan +import sigma.compiler.Scalan import wrappers.scala.WOptionsModule import wrappers.scalan.WRTypesModule import wrappers.special.WSpecialPredefsModule diff --git a/sc/shared/src/main/scala/wrappers/scala/WOptions.scala b/sc/shared/src/main/scala/wrappers/scala/WOptions.scala index 445da52006..830d05233f 100644 --- a/sc/shared/src/main/scala/wrappers/scala/WOptions.scala +++ b/sc/shared/src/main/scala/wrappers/scala/WOptions.scala @@ -1,6 +1,6 @@ package wrappers.scala { import scalan._ - + import sigma.compiler.{Base, Scalan} import special.wrappers.WrappersModule trait WOptions extends Base { self: Scalan => diff --git a/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala b/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala index 62a0e0c10f..b1006c4e9f 100644 --- a/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala +++ b/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala @@ -1,12 +1,15 @@ package wrappers.scala -import scala.language.{existentials,implicitConversions} +import scala.language.{existentials, implicitConversions} import scalan._ +import sigma.compiler.Scalan import special.wrappers.WrappersModule import special.wrappers.OptionWrapSpec + import scala.collection.compat.immutable.ArraySeq package impl { + import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, Scalan} import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} @@ -235,7 +238,7 @@ class WOptionCls extends EntityObject("WOption") { registerEntityObject("WOption", WOption) } -object WOptionsModule extends scalan.ModuleInfo("wrappers.scala", "WOptions") { +object WOptionsModule extends ModuleInfo("wrappers.scala", "WOptions") { val reflection = GraphIRReflection } } diff --git a/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala b/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala index bc71b8ad26..204fa40957 100644 --- a/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala +++ b/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala @@ -1,5 +1,6 @@ package wrappers.scalan { import scalan._ + import sigma.compiler.{Base, Scalan} trait WRTypes extends Base { self: Scalan => diff --git a/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala b/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala index c78a2268bf..7868546bb9 100644 --- a/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala +++ b/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala @@ -1,7 +1,6 @@ package wrappers.scalan -import scalan.Scalan - +import sigma.compiler.Scalan import scala.language.{existentials, implicitConversions} import sigma.data.RType import special.wrappers.RTypeWrapSpec @@ -9,7 +8,7 @@ import special.wrappers.RTypeWrapSpec import scala.collection.compat.immutable.ArraySeq package impl { - import scalan.{Base, GraphIRReflection, Scalan} + import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, Scalan} import sigma.reflection.{RClass, RMethod} // Abs ----------------------------------- @@ -113,7 +112,7 @@ registerEntityObject("WRType", WRType) } -object WRTypesModule extends scalan.ModuleInfo("wrappers.scalan", "WRTypes") { +object WRTypesModule extends ModuleInfo("wrappers.scalan", "WRTypes") { val reflection = GraphIRReflection } } diff --git a/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala b/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala index d1c1260391..3c71796c47 100644 --- a/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala +++ b/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala @@ -1,5 +1,6 @@ package wrappers.special { import scalan._ + import sigma.compiler.{Base, Scalan} trait WSpecialPredefs extends Base { self: Scalan => trait WSpecialPredef extends Def[WSpecialPredef]; diff --git a/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala b/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala index 697de01802..4bb7a13128 100644 --- a/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala +++ b/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala @@ -1,10 +1,12 @@ package wrappers.special -import scala.language.{existentials,implicitConversions} +import scala.language.{existentials, implicitConversions} import scalan._ +import sigma.compiler.Scalan import special.wrappers.WrappersModule package impl { + import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, Scalan} import sigma.data.Nullable import sigma.reflection.RClass @@ -61,7 +63,7 @@ object WSpecialPredef extends EntityObject("WSpecialPredef") { } -object WSpecialPredefsModule extends scalan.ModuleInfo("wrappers.special", "WSpecialPredefs") { +object WSpecialPredefsModule extends ModuleInfo("wrappers.special", "WSpecialPredefs") { val reflection = GraphIRReflection } } diff --git a/sc/shared/src/test/scala/scalan/BaseLiftableTests.scala b/sc/shared/src/test/scala/scalan/BaseLiftableTests.scala index 3d437a2f1d..120c15dfe6 100644 --- a/sc/shared/src/test/scala/scalan/BaseLiftableTests.scala +++ b/sc/shared/src/test/scala/scalan/BaseLiftableTests.scala @@ -1,5 +1,7 @@ package scalan +import sigma.compiler.Scalan + trait BaseLiftableTests { self: BaseCtxTests => trait LiftableTestKit { scalan: Scalan => diff --git a/sc/shared/src/test/scala/scalan/LibraryTests.scala b/sc/shared/src/test/scala/scalan/LibraryTests.scala index d095a2f20a..a6844070eb 100644 --- a/sc/shared/src/test/scala/scalan/LibraryTests.scala +++ b/sc/shared/src/test/scala/scalan/LibraryTests.scala @@ -1,5 +1,6 @@ package scalan +import sigma.compiler.Scalan import sigma.util.BenchmarkUtil.{measure, measureTime} class Benchmark[T <: Scalan](createContext: => T) { diff --git a/sc/shared/src/test/scala/scalan/TestContexts.scala b/sc/shared/src/test/scala/scalan/TestContexts.scala index a86bf42276..39649b541a 100644 --- a/sc/shared/src/test/scala/scalan/TestContexts.scala +++ b/sc/shared/src/test/scala/scalan/TestContexts.scala @@ -1,5 +1,6 @@ package scalan +import sigma.compiler.{GraphIRReflection, Scalan} import sigma.reflection.RMethod import sigma.{BaseNestedTests, BaseShouldTests, BaseTests, TestUtils} diff --git a/sc/shared/src/test/scala/scalan/TestLibrary.scala b/sc/shared/src/test/scala/scalan/TestLibrary.scala index c3d8a5beb8..f54d2d9073 100644 --- a/sc/shared/src/test/scala/scalan/TestLibrary.scala +++ b/sc/shared/src/test/scala/scalan/TestLibrary.scala @@ -1,5 +1,7 @@ package scalan +import sigma.compiler.{GraphIRReflection, Scalan} + trait TestLibrary extends Scalan { import CollBuilder._ import SigmaDslBuilder._ diff --git a/sc/shared/src/test/scala/sigma/CollsStagingTests.scala b/sc/shared/src/test/scala/sigma/CollsStagingTests.scala index 332c5e300c..f0d74f40e9 100644 --- a/sc/shared/src/test/scala/sigma/CollsStagingTests.scala +++ b/sc/shared/src/test/scala/sigma/CollsStagingTests.scala @@ -3,6 +3,7 @@ package sigma import scala.language.reflectiveCalls import special.wrappers.WrappersTests import scalan._ +import sigma.compiler.Scalan import sigma.data.CollOverArrayBuilder class CollsStagingTests extends WrappersTests { From bd0feb0be824fe408674d32bc63747315f423782 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Wed, 15 May 2024 21:05:36 +0100 Subject: [PATCH 49/65] refactor-ir-cake: IRContext moved to sigma.compiler --- .../compiler}/GraphBuilding.scala | 17 ++++++----- .../eval => sigma/compiler}/IRContext.scala | 2 +- .../compiler}/TreeBuilding.scala | 28 +++++++++---------- 3 files changed, 22 insertions(+), 25 deletions(-) rename sc/shared/src/main/scala/{sigmastate/eval => sigma/compiler}/GraphBuilding.scala (99%) rename sc/shared/src/main/scala/{sigmastate/eval => sigma/compiler}/IRContext.scala (94%) rename sc/shared/src/main/scala/{sigmastate/eval => sigma/compiler}/TreeBuilding.scala (99%) diff --git a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala b/sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala similarity index 99% rename from sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala rename to sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala index 445edd3594..d800ff03bd 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/GraphBuilding.scala +++ b/sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala @@ -1,22 +1,21 @@ -package sigmastate.eval +package sigma.compiler import org.ergoplatform._ import scalan.MutableLazy -import sigma.{SigmaException, ast} import sigma.ast.TypeCodes.LastConstantCode import sigma.ast.Value.Typed -import sigma.ast._ import sigma.ast.syntax.{SValue, ValueOps} +import sigma.ast._ import sigma.crypto.EcPointType import sigma.data.ExactIntegral.{ByteIsExactIntegral, IntIsExactIntegral, LongIsExactIntegral, ShortIsExactIntegral} import sigma.data.ExactOrdering.{ByteIsExactOrdering, IntIsExactOrdering, LongIsExactOrdering, ShortIsExactOrdering} import sigma.data.{CSigmaDslBuilder, ExactIntegral, ExactNumeric, ExactOrdering, Lazy, Nullable} -import sigma.util.Extensions.ByteOps -import sigmastate.interpreter.Interpreter.ScriptEnv -import sigma.ast.{Ident, Select, Val} -import sigma.compiler.Scalan import sigma.exceptions.GraphBuildingException import sigma.serialization.OpCodes +import sigma.util.Extensions.ByteOps +import sigma.{SigmaException, ast} +import sigmastate.eval.IRContext +import sigmastate.interpreter.Interpreter.ScriptEnv import scala.collection.mutable.ArrayBuffer @@ -43,8 +42,8 @@ trait GraphBuilding extends Scalan { IR: IRContext => import SigmaProp._ import WOption._ - /** Should be specified in the final cake */ - val builder: SigmaBuilder + /** Builder used to create ErgoTree nodes. */ + val builder = TransformingSigmaBuilder import builder._ val okMeasureOperationTime: Boolean = false diff --git a/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala b/sc/shared/src/main/scala/sigma/compiler/IRContext.scala similarity index 94% rename from sc/shared/src/main/scala/sigmastate/eval/IRContext.scala rename to sc/shared/src/main/scala/sigma/compiler/IRContext.scala index 597711d458..5365c75e5e 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/IRContext.scala +++ b/sc/shared/src/main/scala/sigma/compiler/IRContext.scala @@ -1,6 +1,7 @@ package sigmastate.eval import sigma.ast.TransformingSigmaBuilder +import sigma.compiler.{GraphBuilding, TreeBuilding} /** Main interface of graph IR context which contain both GraphBuilding and TreeBuilding * methods. @@ -11,7 +12,6 @@ import sigma.ast.TransformingSigmaBuilder * @see CompiletimeIRContext */ trait IRContext extends TreeBuilding with GraphBuilding { - override val builder = TransformingSigmaBuilder /** Pass configuration which is used to turn-off constant propagation. * USED IN TESTS ONLY. diff --git a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala b/sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala similarity index 99% rename from sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala rename to sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala index 4a6bca7d2e..b5c7be20ff 100644 --- a/sc/shared/src/main/scala/sigmastate/eval/TreeBuilding.scala +++ b/sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala @@ -1,17 +1,15 @@ -package sigmastate.eval +package sigma.compiler - -import sigma.ast._ import org.ergoplatform._ -import sigma.ast.syntax.ValueOps -import sigma.serialization.OpCodes._ -import sigma.serialization.ConstantStore -import sigma.ast.syntax._ -import sigma.compiler.Scalan +import sigma.ast._ +import sigma.ast.syntax.{ValueOps, _} import sigma.data.{ProveDHTuple, ProveDlog} +import sigma.serialization.ConstantStore +import sigma.serialization.OpCodes._ +import sigma.serialization.ValueCodes.OpCode +import sigmastate.eval.IRContext import scala.collection.mutable.ArrayBuffer -import sigma.serialization.ValueCodes.OpCode /** Implementation of IR-graph to ErgoTree expression translation. * This, in a sense, is inverse to [[GraphBuilding]], however roundtrip identity is not @@ -26,16 +24,16 @@ import sigma.serialization.ValueCodes.OpCode * @see buildTree method * */ trait TreeBuilding extends Scalan { IR: IRContext => - import Liftables._ - import Context._ - import SigmaProp._ - import Coll._ + import BigInt._ import Box._ + import Coll._ import CollBuilder._ + import Context._ + import GroupElement._ + import Liftables._ import SigmaDslBuilder._ - import BigInt._ + import SigmaProp._ import WOption._ - import GroupElement._ /** Convenience synonyms for easier pattern matching. */ private val ContextM = ContextMethods From f4bd542714f1443422f77077ccefd582456d2c37 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Wed, 15 May 2024 21:39:46 +0100 Subject: [PATCH 50/65] refactor-ir-cake: everything is assembled in Scalan cake --- .../sigmastate/lang/js/SigmaCompiler.scala | 2 +- .../org/ergoplatform/ErgoScriptPredef.scala | 6 ++--- .../org/ergoplatform/dsl/ContractSpec.scala | 4 +-- .../ergoplatform/dsl/ErgoContractSpec.scala | 4 +-- .../scala/sigma/compiler/GraphBuilding.scala | 5 ++-- .../main/scala/sigma/compiler/IRContext.scala | 25 +++---------------- .../main/scala/sigma/compiler/Scalan.scala | 16 +++++++++++- .../scala/sigma/compiler/TreeBuilding.scala | 3 +-- .../scala/sigmastate/lang/SigmaCompiler.scala | 11 ++++---- .../lang/SigmaTemplateCompiler.scala | 2 +- .../ergoplatform/dsl/TestContractSpec.scala | 5 ++-- .../src/test/scala/scalan/TestLibrary.scala | 2 -- .../scala/sigma/SigmaDslStaginTests.scala | 3 ++- .../test/scala/sigma/SigmaDslTesting.scala | 19 +++++++------- .../scala/sigmastate/CompilerTestsBase.scala | 8 +++--- .../ScriptVersionSwitchSpecification.scala | 5 ++-- .../sigmastate/eval/ErgoScriptTestkit.scala | 5 ++-- .../eval/ErgoTreeBuildingTest.scala | 3 ++- .../helpers/CompilerTestingCommons.scala | 11 ++++---- .../ErgoTreeSerializerSpecification.scala | 4 +-- .../utxo/AVLTreeScriptsSpecification.scala | 4 +-- .../UsingContextPropertiesSpecification.scala | 4 +-- .../BlockchainSimulationTestingCommons.scala | 5 ++-- .../sigmastate/utxo/examples/IcoExample.scala | 3 ++- .../utxo/examples/LetsSpecification.scala | 4 +-- 25 files changed, 81 insertions(+), 82 deletions(-) diff --git a/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala b/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala index 8fe26a30b0..3dfd285e93 100644 --- a/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala +++ b/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala @@ -9,7 +9,7 @@ import scala.scalajs.js import scala.scalajs.js.annotation.JSExportTopLevel import sigma.js.Value import sigma.ast.ErgoTree.HeaderType -import sigmastate.eval.CompiletimeIRContext +import sigma.compiler.CompiletimeIRContext import sigma.ast.syntax.ValueOps diff --git a/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala b/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala index faded6e28c..a2bc3362d7 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala @@ -1,18 +1,18 @@ package org.ergoplatform import sigmastate.lang.SigmaCompiler -import sigmastate.eval.IRContext import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix import sigma.ast.SType import sigma.ast.syntax.SigmaPropValue import sigma.ast.Value import sigma.ast.syntax.ValueOps +import sigma.compiler.Scalan object ErgoScriptPredef { import sigmastate.interpreter.Interpreter._ /** Compiles the given ErgoScript `code` into ErgoTree expression. */ - def compileWithCosting(env: ScriptEnv, code: String, networkPrefix: NetworkPrefix)(implicit IR: IRContext): Value[SType] = { + def compileWithCosting(env: ScriptEnv, code: String, networkPrefix: NetworkPrefix)(implicit IR: Scalan): Value[SType] = { val compiler = SigmaCompiler(networkPrefix) val res = compiler.compile(env, code) res.buildTree @@ -30,7 +30,7 @@ object ErgoScriptPredef { tokenId: Array[Byte], thresholdAmount: Long, networkPrefix: NetworkPrefix) - (implicit IR: IRContext): SigmaPropValue = { + (implicit IR: Scalan): SigmaPropValue = { val env = emptyEnv + ("tokenId" -> tokenId, "thresholdAmount" -> thresholdAmount) val res = compileWithCosting(env, diff --git a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala index 484b9e2728..539da9d79b 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala @@ -5,11 +5,11 @@ import sigma.interpreter.{CostedProverResult, ProverResult} import sigma.data.{CSigmaDslBuilder, RType} import org.ergoplatform.{ErgoBox, ErgoLikeContext} import sigma.{Coll, SigmaDslBuilder, SigmaProp} -import sigmastate.eval.IRContext import scala.util.Try import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition, Token} import sigma.ast.{ErgoTree, EvaluatedValue, SType} +import sigma.compiler.Scalan import scala.language.implicitConversions @@ -19,7 +19,7 @@ trait ContractSpec { implicit def Coll[T](items: Array[T])(implicit cT: RType[T]): Coll[T] = Colls.fromArray(items) - val IR: IRContext + val IR: Scalan trait PropositionSpec { def name: String diff --git a/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala b/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala index 2c31304b70..6a91c6f60a 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala @@ -1,12 +1,12 @@ package org.ergoplatform.dsl import sigma.Coll -import sigmastate.eval.IRContext import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition, Token} import org.ergoplatform.ErgoBox.{BoxId, NonMandatoryRegisterId, TokenId} +import sigma.compiler.Scalan import sigma.interpreter.CostedProverResult -class ErgoContractSpec(implicit val IR: IRContext) extends ContractSpec { +class ErgoContractSpec(implicit val IR: Scalan) extends ContractSpec { case class ErgoOutBox(tx: TransactionCandidate, boxIndex: Int, value: Long, propSpec: PropositionSpec) extends OutBox { diff --git a/sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala b/sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala index d800ff03bd..784ee0e836 100644 --- a/sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala +++ b/sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala @@ -14,7 +14,6 @@ import sigma.exceptions.GraphBuildingException import sigma.serialization.OpCodes import sigma.util.Extensions.ByteOps import sigma.{SigmaException, ast} -import sigmastate.eval.IRContext import sigmastate.interpreter.Interpreter.ScriptEnv import scala.collection.mutable.ArrayBuffer @@ -27,7 +26,7 @@ import scala.collection.mutable.ArrayBuffer * CSE however means the original structure of source code may not be preserved in the * resulting ErgoTree. * */ -trait GraphBuilding extends Scalan { IR: IRContext => +trait GraphBuilding extends Base with DefRewriting { IR: Scalan => import AvlTree._ import BigInt._ import Box._ @@ -59,7 +58,7 @@ trait GraphBuilding extends Scalan { IR: IRContext => * In v5.x this code is taken from CheckTupleType validation rule which is no longer * part of consensus. */ - def checkTupleType[Ctx <: IRContext, T](ctx: Ctx)(e: ctx.Elem[_]): Unit = { + def checkTupleType[Ctx <: Scalan, T](ctx: Ctx)(e: ctx.Elem[_]): Unit = { val condition = e match { case _: ctx.PairElem[_, _] => true case _ => false diff --git a/sc/shared/src/main/scala/sigma/compiler/IRContext.scala b/sc/shared/src/main/scala/sigma/compiler/IRContext.scala index 5365c75e5e..0b958b9ab9 100644 --- a/sc/shared/src/main/scala/sigma/compiler/IRContext.scala +++ b/sc/shared/src/main/scala/sigma/compiler/IRContext.scala @@ -1,25 +1,6 @@ -package sigmastate.eval +package sigma.compiler -import sigma.ast.TransformingSigmaBuilder -import sigma.compiler.{GraphBuilding, TreeBuilding} - -/** Main interface of graph IR context which contain both GraphBuilding and TreeBuilding - * methods. - * It is not used in v5.0 interpreter and thus not part of consensus. - * - * Used in ErgoScript compiler only. - * - * @see CompiletimeIRContext - */ -trait IRContext extends TreeBuilding with GraphBuilding { - - /** Pass configuration which is used to turn-off constant propagation. - * USED IN TESTS ONLY. - * @see `beginPass(noCostPropagationPass)` */ - lazy val noConstPropagationPass = new DefaultPass( - "noCostPropagationPass", - Pass.defaultPassConfig.copy(constantPropagation = false)) -} +trait IRContext extends Scalan /** IR context to be used by script development tools to compile ErgoScript into ErgoTree bytecode. */ -class CompiletimeIRContext extends IRContext +class CompiletimeIRContext extends Scalan diff --git a/sc/shared/src/main/scala/sigma/compiler/Scalan.scala b/sc/shared/src/main/scala/sigma/compiler/Scalan.scala index 76fee8c7f1..8009cd5e36 100644 --- a/sc/shared/src/main/scala/sigma/compiler/Scalan.scala +++ b/sc/shared/src/main/scala/sigma/compiler/Scalan.scala @@ -20,6 +20,11 @@ import special.wrappers.WrappersModule * At the same time cake design pattern allow to `override` many methods and values * in classed derived from `Scalan`, this is significant benefit over * *everything is global* design. + * + * It is not used in v5.0 interpreter and thus not part of consensus. + * Used in ErgoScript compiler only. + * + * @see CompiletimeIRContext */ trait Scalan extends TypeDescs @@ -41,7 +46,9 @@ trait Scalan with WrappersModule with CollsModule with sigma.wrappers.WrappersModule - with SigmaDslModule { + with SigmaDslModule + with TreeBuilding + with GraphBuilding { import Coll._ import CollBuilder._ @@ -49,6 +56,13 @@ trait Scalan import WRType._ import WSpecialPredef._ + /** Pass configuration which is used to turn-off constant propagation. + * USED IN TESTS ONLY. + * @see `beginPass(noCostPropagationPass)` */ + lazy val noConstPropagationPass = new DefaultPass( + "noCostPropagationPass", + Pass.defaultPassConfig.copy(constantPropagation = false)) + type LazyRep[T] = MutableLazy[Ref[T]] private val _liftElemMemo = new MemoizedFunc({ diff --git a/sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala b/sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala index b5c7be20ff..f781215901 100644 --- a/sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala +++ b/sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala @@ -7,7 +7,6 @@ import sigma.data.{ProveDHTuple, ProveDlog} import sigma.serialization.ConstantStore import sigma.serialization.OpCodes._ import sigma.serialization.ValueCodes.OpCode -import sigmastate.eval.IRContext import scala.collection.mutable.ArrayBuffer @@ -23,7 +22,7 @@ import scala.collection.mutable.ArrayBuffer * * @see buildTree method * */ -trait TreeBuilding extends Scalan { IR: IRContext => +trait TreeBuilding extends Base { IR: Scalan => import BigInt._ import Box._ import Coll._ diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala index 20e1e28471..4392e97216 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala @@ -5,7 +5,6 @@ import fastparse.Parsed.Success import sigma.kiama.rewriting.Rewriter.{everywherebu, rewrite, rule} import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix import sigma.ast.{Exponentiate, MultiplyGroup, SCollectionMethods, SGlobalMethods, SGroupElementMethods, Value, Xor} -import sigmastate.eval.IRContext import sigmastate.interpreter.Interpreter.ScriptEnv import sigma.ast.SigmaPredef.PredefinedFuncRegistry import sigma.ast.MethodCall @@ -13,7 +12,7 @@ import sigmastate.lang.parsers.ParserException import sigma.ast._ import sigma.ast.syntax.SValue import SCollectionMethods.{ExistsMethod, ForallMethod, MapMethod} -import sigma.compiler.GraphIRReflection +import sigma.compiler.{GraphIRReflection, Scalan} import sigmastate.InterpreterReflection /** @@ -38,7 +37,7 @@ case class CompilerSettings( * @param compiledGraph graph obtained by using new [[GraphBuilding]] * @param buildTree ErgoTree expression obtained from graph created by [[GraphBuilding]] */ -case class CompilerResult[Ctx <: IRContext]( +case class CompilerResult[Ctx <: Scalan]( env: ScriptEnv, code: String, compiledGraph: Ctx#Ref[Ctx#Context => Any], @@ -84,14 +83,14 @@ class SigmaCompiler private(settings: CompilerSettings) { } /** Compiles the given ErgoScript source code. */ - def compile(env: ScriptEnv, code: String)(implicit IR: IRContext): CompilerResult[IR.type] = { + def compile(env: ScriptEnv, code: String)(implicit IR: Scalan): CompilerResult[IR.type] = { val typed = typecheck(env, code) val res = compileTyped(env, typed).copy(code = code) res } /** Compiles the given typed expression. */ - def compileTyped(env: ScriptEnv, typedExpr: SValue)(implicit IR: IRContext): CompilerResult[IR.type] = { + def compileTyped(env: ScriptEnv, typedExpr: SValue)(implicit IR: Scalan): CompilerResult[IR.type] = { val placeholdersEnv = env .collect { case (name, t: SType) => name -> t } .zipWithIndex @@ -103,7 +102,7 @@ class SigmaCompiler private(settings: CompilerSettings) { } /** Compiles the given parsed contract source. */ - def compileParsed(env: ScriptEnv, parsedExpr: SValue)(implicit IR: IRContext): CompilerResult[IR.type] = { + def compileParsed(env: ScriptEnv, parsedExpr: SValue)(implicit IR: Scalan): CompilerResult[IR.type] = { val typed = typecheck(env, parsedExpr) compileTyped(env, typed) } diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala index f77735118c..8c8a84d29e 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala @@ -4,7 +4,7 @@ import fastparse.Parsed import org.ergoplatform.sdk.{ContractTemplate, Parameter} import sigma.ast.SourceContext import sigma.ast.syntax.SValue -import sigmastate.eval.CompiletimeIRContext +import sigma.compiler.CompiletimeIRContext import sigmastate.lang.parsers.ParserException /** Compiler which compiles Ergo contract templates into a [[ContractTemplate]]. */ diff --git a/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala b/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala index 26e8b08b14..0c8bb83e56 100644 --- a/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala +++ b/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala @@ -4,6 +4,7 @@ import sigmastate.interpreter.Interpreter.ScriptNameProp import scala.collection.mutable import sigma.interpreter.{CostedProverResult, ProverResult} + import scala.collection.mutable.ArrayBuffer import org.ergoplatform.ErgoBox.{NonMandatoryRegisterId, TokenId} import sigma.data.{AvlTreeData, CAnyValue, CSigmaProp, Nullable} @@ -14,14 +15,14 @@ import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition, Token} import sigma.ast.{ErgoTree, SType} import sigma.ast.EvaluatedValue import sigma.interpreter.ContextExtension -import sigmastate.eval.IRContext import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} import sigmastate.helpers.TestingHelpers._ import sigma.ast.syntax.ValueOps import sigma.{AnyValue, Evaluation, SigmaProp} import ErgoTree.ZeroHeader +import sigma.compiler.Scalan -case class TestContractSpec(testSuite: CompilerTestingCommons)(implicit val IR: IRContext) extends ContractSpec { +case class TestContractSpec(testSuite: CompilerTestingCommons)(implicit val IR: Scalan) extends ContractSpec { case class TestPropositionSpec(name: String, dslSpec: Proposition, scriptSpec: ErgoScript) extends PropositionSpec { lazy val ergoTree: ErgoTree = { diff --git a/sc/shared/src/test/scala/scalan/TestLibrary.scala b/sc/shared/src/test/scala/scalan/TestLibrary.scala index f54d2d9073..2c4c355cb8 100644 --- a/sc/shared/src/test/scala/scalan/TestLibrary.scala +++ b/sc/shared/src/test/scala/scalan/TestLibrary.scala @@ -6,6 +6,4 @@ trait TestLibrary extends Scalan { import CollBuilder._ import SigmaDslBuilder._ val reflection = (GraphIRReflection) - lazy val colBuilder: Ref[CollBuilder] = variable[CollBuilder] - lazy val sigmaDslBuilder: Ref[SigmaDslBuilder] = variable[SigmaDslBuilder] } diff --git a/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala b/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala index 91178b2b67..90eefab5e0 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala @@ -2,6 +2,7 @@ package sigma import org.scalatest.BeforeAndAfterAll import scalan.{BaseCtxTests, BaseLiftableTests} +import sigma.compiler.Scalan import sigma.data.TrivialProp import sigma.eval.Extensions.toAnyValue import sigmastate.eval._ @@ -9,7 +10,7 @@ import sigmastate.eval._ import scala.language.reflectiveCalls class SigmaDslStaginTests extends BaseCtxTests with ErgoScriptTestkit with BaseLiftableTests with BeforeAndAfterAll { - class Ctx extends TestContext with IRContext with LiftableTestKit { + class Ctx extends TestContext with Scalan with LiftableTestKit { } test("invokeUnlifted") { diff --git a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala index 46222d9fb1..4acb6e0f75 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala @@ -25,12 +25,13 @@ import sigma.ast._ import sigma.eval.{CostDetails, EvalSettings, SigmaDsl} import sigmastate.crypto.DLogProtocol.DLogProverInput import sigmastate.crypto.SigmaProtocolPrivateInput -import sigmastate.eval.{CContext, CompiletimeIRContext, IRContext} +import sigmastate.eval.CContext import sigmastate.helpers.TestingHelpers._ import sigmastate.helpers.{CompilerTestingCommons, ErgoLikeContextTesting, ErgoLikeTestInterpreter, SigmaPPrint} import sigmastate.interpreter.Interpreter.{ScriptEnv, VerificationResult} import sigmastate.interpreter._ import sigma.ast.Apply +import sigma.compiler.{CompiletimeIRContext, Scalan} import sigma.eval.Extensions.SigmaBooleanOps import sigma.interpreter.{ContextExtension, ProverResult} import sigma.serialization.ValueSerializer @@ -54,7 +55,7 @@ class SigmaDslTesting extends AnyPropSpec override def contractEnv: ScriptEnv = Map() - def createIR(): IRContext = new TestingIRContext { + def createIR(): Scalan = new TestingIRContext { override val okMeasureOperationTime: Boolean = true } @@ -495,7 +496,7 @@ class SigmaDslTesting extends AnyPropSpec expectedExpr: Option[SValue], printExpectedExpr: Boolean = true, logScript: Boolean = LogScriptDefault - )(implicit IR: IRContext, val tA: RType[A], val tB: RType[B], + )(implicit IR: Scalan, val tA: RType[A], val tB: RType[B], override val evalSettings: EvalSettings) extends Feature[A, B] { implicit val cs = compilerSettingsInTests @@ -665,7 +666,7 @@ class SigmaDslTesting extends AnyPropSpec logScript: Boolean = LogScriptDefault, allowNewToSucceed: Boolean = false, override val allowDifferentErrors: Boolean = false - )(implicit IR: IRContext, override val evalSettings: EvalSettings, val tA: RType[A], val tB: RType[B]) + )(implicit IR: Scalan, override val evalSettings: EvalSettings, val tA: RType[A], val tB: RType[B]) extends Feature[A, B] { feature => implicit val cs = compilerSettingsInTests @@ -839,7 +840,7 @@ class SigmaDslTesting extends AnyPropSpec expectedExpr: Option[SValue], printExpectedExpr: Boolean = true, logScript: Boolean = LogScriptDefault - )(implicit IR: IRContext, override val evalSettings: EvalSettings, val tA: RType[A], val tB: RType[B]) + )(implicit IR: Scalan, override val evalSettings: EvalSettings, val tA: RType[A], val tB: RType[B]) extends Feature[A, B] { override def scalaFunc: A => B = { x => sys.error(s"Semantic Scala function is not defined for old implementation: $this") @@ -1012,7 +1013,7 @@ class SigmaDslTesting extends AnyPropSpec def existingFeature[A: RType, B: RType] (scalaFunc: A => B, script: String, expectedExpr: SValue = null) - (implicit IR: IRContext, evalSettings: EvalSettings): Feature[A, B] = { + (implicit IR: Scalan, evalSettings: EvalSettings): Feature[A, B] = { ExistingFeature( script, scalaFunc, Option(expectedExpr)) } @@ -1035,7 +1036,7 @@ class SigmaDslTesting extends AnyPropSpec expectedExpr: SValue = null, allowNewToSucceed: Boolean = false, allowDifferentErrors: Boolean = false) - (implicit IR: IRContext, evalSettings: EvalSettings): Feature[A, B] = { + (implicit IR: Scalan, evalSettings: EvalSettings): Feature[A, B] = { ChangedFeature(script, scalaFunc, scalaFuncNew, Option(expectedExpr), allowNewToSucceed = allowNewToSucceed, allowDifferentErrors = allowDifferentErrors) @@ -1052,7 +1053,7 @@ class SigmaDslTesting extends AnyPropSpec */ def newFeature[A: RType, B: RType] (scalaFunc: A => B, script: String, expectedExpr: SValue = null) - (implicit IR: IRContext, es: EvalSettings): Feature[A, B] = { + (implicit IR: Scalan, es: EvalSettings): Feature[A, B] = { NewFeature(script, scalaFunc, Option(expectedExpr)) } @@ -1150,7 +1151,7 @@ class SigmaDslTesting extends AnyPropSpec def benchmarkCases[A: Ordering : Arbitrary : ClassTag, B] (cases: Seq[A], f: Feature[A, B], nIters: Int, formatter: MeasureFormatter[A]) - (implicit IR: IRContext, evalSettings: EvalSettings): Seq[Long] = { + (implicit IR: Scalan, evalSettings: EvalSettings): Seq[Long] = { val fNew = f.newF implicit val tA = fNew.tA implicit val tB = fNew.tB diff --git a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala index 0b2951b92f..0d00fef070 100644 --- a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala +++ b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala @@ -7,7 +7,7 @@ import sigma.ast.{ErgoTree, SType, TransformingSigmaBuilder, Value} import org.ergoplatform.ErgoAddressEncoder.TestnetNetworkPrefix import sigma.ast.syntax.{SValue, SigmaPropValue} import sigma.serialization.ValueSerializer -import sigmastate.eval.IRContext +import sigma.compiler.Scalan import sigma.ast.syntax.ValueOps import sigmastate.helpers.{NegativeTesting, SigmaPPrint} @@ -44,21 +44,21 @@ trait CompilerTestsBase extends TestsBase with NegativeTesting { } /** Compile the given code to ErgoTree expression. */ - def compile(env: ScriptEnv, code: String)(implicit IR: IRContext): Value[SType] = { + def compile(env: ScriptEnv, code: String)(implicit IR: Scalan): Value[SType] = { val res = compiler.compile(env, code) checkCompilerResult(res) res.buildTree } /** Check the given [[CompilerResult]] meets equality and sanity requirements. */ - def checkCompilerResult[Ctx <: IRContext](res: CompilerResult[Ctx]): Unit = { + def checkCompilerResult[Ctx <: Scalan](res: CompilerResult[Ctx]): Unit = { checkSerializationRoundTrip(res.buildTree) } /** Compiles the given code and checks the resulting `prop` against `expected`. */ def compileAndCheck(env: ScriptEnv, code: String, expected: SValue) - (implicit IR: IRContext): (ErgoTree, SigmaPropValue) = { + (implicit IR: Scalan): (ErgoTree, SigmaPropValue) = { val prop = compile(env, code).asSigmaProp prop shouldBe expected val tree = mkTestErgoTree(prop) diff --git a/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala b/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala index b0206fa464..767c1dbd7b 100644 --- a/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala @@ -14,6 +14,7 @@ import sigmastate.interpreter.CErgoTreeEvaluator.DefaultEvalSettings import sigma.eval.EvalSettings.EvaluationMode import sigmastate.interpreter._ import sigma.ast.syntax.ValueOps +import sigma.compiler.Scalan import sigma.data.CBox import sigma.eval.EvalSettings import sigma.exceptions.InterpreterException @@ -32,7 +33,7 @@ class ScriptVersionSwitchSpecification extends SigmaDslTesting { costTracingEnabled = true // should always be enabled in tests (and false by default) ) - implicit def IR: IRContext = createIR() + implicit def IR: Scalan = createIR() lazy val b1 = CBox( new ErgoBox( @@ -51,7 +52,7 @@ class ScriptVersionSwitchSpecification extends SigmaDslTesting { ) /** Creates ErgoTree with segregated constants and also the given header flags. */ - def createErgoTree(header: HeaderType)(implicit IR: IRContext): ErgoTree = { + def createErgoTree(header: HeaderType)(implicit IR: Scalan): ErgoTree = { val code = s"""{ | val func = { (x: Coll[Box]) => x.filter({(b: Box) => b.value > 1 }) } diff --git a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala index a10a717d2f..dc9cccae9c 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala @@ -14,6 +14,7 @@ import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeConte import sigmastate.interpreter.Interpreter.ScriptEnv import sigmastate.interpreter.CErgoTreeEvaluator import sigma.ast.syntax.ValueOps +import sigma.compiler.Scalan import sigma.interpreter.ContextExtension import sigmastate.lang.{CompilerResult, CompilerSettings, LangTests, SigmaCompiler} import sigma.serialization.ErgoTreeSerializer.DefaultSerializer @@ -26,8 +27,8 @@ import scala.util.{Success, Try} trait ErgoScriptTestkit extends ContractsTestkit with LangTests with ValidationSpecification with CompilerTestsBase { self: BaseCtxTests => - implicit lazy val IR: TestContext with IRContext = - new TestContext with IRContext + implicit lazy val IR: TestContext with Scalan = + new TestContext with Scalan import IR._ import BigInt._ diff --git a/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala b/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala index 526012f212..deb2110443 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala @@ -8,11 +8,12 @@ import scalan.BaseCtxTests import sigma.ast.syntax.ValueOps import sigmastate.lang.LangTests import sigma.ast.Apply +import sigma.compiler.Scalan class ErgoTreeBuildingTest extends BaseCtxTests with LangTests with ExampleContracts with ErgoScriptTestkit { - implicit override lazy val IR: TestContext with IRContext = new TestContext with IRContext { + implicit override lazy val IR: TestContext with Scalan = new TestContext with Scalan { beginPass(noConstPropagationPass) } diff --git a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala index 6c3708b782..b7bdf58452 100644 --- a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala +++ b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala @@ -12,6 +12,7 @@ import sigma.data.{RType, SigmaBoolean} import sigma.validation.ValidationException import sigma.validation.ValidationRules.CheckSerializableTypeCode import sigma.ast.syntax.{SValue, SigmaPropValue} +import sigma.compiler.Scalan import sigma.eval.{CostDetails, EvalSettings, Extensions, GivenCost, TracedCost} import sigmastate.helpers.TestingHelpers._ import sigma.interpreter.ContextExtension.VarBinding @@ -21,7 +22,7 @@ import sigmastate.interpreter._ import sigmastate.lang.{CompilerSettings, SigmaCompiler} import sigma.serialization.SigmaSerializer import sigmastate.CompilerTestsBase -import sigmastate.eval.{CContext, IRContext} +import sigmastate.eval.CContext import scala.util.DynamicVariable @@ -29,7 +30,7 @@ trait CompilerTestingCommons extends TestingCommons with TestUtils with TestContexts with ValidationSpecification with CompilerTestsBase { - class TestingIRContext extends TestContext with IRContext + class TestingIRContext extends TestContext with Scalan case class CompiledFunc[A,B] (script: String, bindings: Seq[VarBinding], expr: SValue, compiledTree: SValue, func: A => (B, CostDetails)) @@ -90,7 +91,7 @@ trait CompilerTestingCommons extends TestingCommons def compileTestScript[A] (env: ScriptEnv, funcScript: String) (implicit tA: RType[A], - IR: IRContext, + IR: Scalan, compilerSettings: CompilerSettings): SValue = { val code = s"""{ @@ -128,7 +129,7 @@ trait CompilerTestingCommons extends TestingCommons def funcJitFromExpr[A: RType, B: RType] (funcScript: String, expr: SValue, bindings: VarBinding*) - (implicit IR: IRContext, + (implicit IR: Scalan, evalSettings: EvalSettings, compilerSettings: CompilerSettings): CompiledFunc[A, B] = { val f = (in: A) => { @@ -166,7 +167,7 @@ trait CompilerTestingCommons extends TestingCommons def funcJit[A: RType, B: RType] (funcScript: String, bindings: VarBinding*) - (implicit IR: IRContext, + (implicit IR: Scalan, evalSettings: EvalSettings, compilerSettings: CompilerSettings): CompiledFunc[A, B] = { val compiledTree = compileTestScript[A](Interpreter.emptyEnv, funcScript) diff --git a/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala b/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala index e20d8a6d1e..ae517a2ee6 100644 --- a/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala @@ -10,9 +10,9 @@ import sigma.util.Extensions.SigmaPropOps import sigma.validation.ValidationException import ErgoTree.EmptyConstants import ErgoTree.HeaderType +import sigma.compiler.Scalan import sigma.eval.Extensions.SigmaBooleanOps import sigmastate._ -import sigmastate.eval.IRContext import sigmastate.helpers.CompilerTestingCommons import sigma.serialization.ErgoTreeSerializer.DefaultSerializer @@ -25,7 +25,7 @@ class ErgoTreeSerializerSpecification extends SerializationSpecification beginPass(noConstPropagationPass) } - private def extractConstants(prop: SigmaPropValue)(implicit IR: IRContext): Seq[ErgoTree] = { + private def extractConstants(prop: SigmaPropValue)(implicit IR: Scalan): Seq[ErgoTree] = { import ErgoTree._ val env = Map[String, Any]() val res = compiler.compileTyped(env, prop) diff --git a/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala index 566bf5bd58..7e1b9a5491 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala @@ -9,7 +9,6 @@ import scorex.crypto.hash.{Blake2b256, Digest32} import sigma.ast.SCollection.SByteArray import sigma.ast._ import sigmastate._ -import sigmastate.eval.IRContext import sigmastate.eval._ import sigma.Extensions.ArrayOps import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestInterpreter} @@ -19,6 +18,7 @@ import sigma.ast.syntax._ import sigma.Coll import sigma.ast.SAvlTree import sigma.ast.syntax.{GetVarByteArray, OptionValueOps} +import sigma.compiler.Scalan import sigma.data.{AvlTreeData, AvlTreeFlags, CSigmaProp, TrivialProp} import sigma.eval.SigmaDsl import sigma.interpreter.ProverResult @@ -31,7 +31,7 @@ class AVLTreeScriptsSpecification extends CompilerTestingCommons import org.ergoplatform.dsl.AvlTreeHelpers._ lazy val spec = TestContractSpec(suite)(new TestingIRContext) lazy val prover = spec.ProvingParty("Alice") - private implicit lazy val IR: IRContext = spec.IR + private implicit lazy val IR: Scalan = spec.IR private val reg1 = ErgoBox.nonMandatoryRegisters(0) private val reg2 = ErgoBox.nonMandatoryRegisters(1) diff --git a/sc/shared/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala index e3d43ab868..9c29c0301d 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala @@ -1,20 +1,20 @@ package sigmastate.utxo import sigmastate.CompilerCrossVersionProps -import sigmastate.eval.IRContext import sigma.Extensions.ArrayOps import sigma.Context import sigmastate.helpers.CompilerTestingCommons import org.ergoplatform.dsl.{ContractSpec, SigmaContractSyntax, TestContractSpec} import org.ergoplatform.ErgoBox import scorex.crypto.hash.Blake2b256 +import sigma.compiler.Scalan import sigma.data.{CSigmaProp, TrivialProp} class UsingContextPropertiesSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { suite => lazy val spec = TestContractSpec(suite)(new TestingIRContext) lazy val prover = spec.ProvingParty("Alice") - private implicit lazy val IR: IRContext = spec.IR + private implicit lazy val IR: Scalan = spec.IR private val reg1 = ErgoBox.nonMandatoryRegisters(0) diff --git a/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala b/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala index 0dca8a4471..4cf39a8cb6 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala @@ -17,6 +17,7 @@ import scorex.util._ import sigma.Colls import sigma.data.{AvlTreeData, AvlTreeFlags} import ErgoTree.ZeroHeader +import sigma.compiler.Scalan import sigma.eval.Extensions.SigmaBooleanOps import sigma.interpreter.ContextExtension import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} @@ -125,7 +126,7 @@ object BlockchainSimulationTestingCommons extends CompilerTestingCommons { } - case class ValidationState(state: BlockchainState, boxesReader: InMemoryErgoBoxReader, activatedVersion: Byte)(implicit IR: IRContext) { + case class ValidationState(state: BlockchainState, boxesReader: InMemoryErgoBoxReader, activatedVersion: Byte)(implicit IR: Scalan) { val validator = new ErgoTransactionValidator(activatedVersion) def applyBlock(block: FullBlock, maxCost: Int = MaxBlockCost): Try[ValidationState] = Try { @@ -165,7 +166,7 @@ object BlockchainSimulationTestingCommons extends CompilerTestingCommons { ErgoLikeContextTesting.dummyPubkey ) - def initialState(activatedVersion: Byte, block: FullBlock)(implicit IR: IRContext): ValidationState = { + def initialState(activatedVersion: Byte, block: FullBlock)(implicit IR: Scalan): ValidationState = { val keySize = 32 val prover = new BatchProver(keySize, None) diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala index c930135bc2..6a55338fbe 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala @@ -22,6 +22,7 @@ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingIn import sigmastate.interpreter.Interpreter.ScriptNameProp import sigmastate.interpreter.Interpreter import sigma.ast.syntax._ +import sigma.compiler.Scalan import sigma.eval.SigmaDsl import sigma.serialization.ErgoTreeSerializer import sigma.serialization.ErgoTreeSerializer.DefaultSerializer @@ -241,7 +242,7 @@ class IcoExample extends CompilerTestingCommons with CompilerCrossVersionProps with BeforeAndAfterAll { suite => // Not mixed with TestContext since it is not possible to call commpiler.compile outside tests if mixed - implicit lazy val IR: IRContext = new IRContext {} + implicit lazy val IR: Scalan = new Scalan {} lazy val spec = TestContractSpec(suite) lazy val project = new ErgoLikeTestProvingInterpreter() diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala index ce4ed2114e..5b40d111f3 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala @@ -10,12 +10,12 @@ import sigma.data.{AvlTreeData, AvlTreeFlags, Digest32Coll, TrivialProp} import sigmastate.CompilerCrossVersionProps import sigma.ast.{AvlTreeConstant, ByteArrayConstant, LongConstant, SigmaPropConstant} import sigma.Extensions.ArrayOps -import sigmastate.eval.IRContext import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingInterpreter, ErgoLikeContextTesting, ErgoLikeTestProvingInterpreter} import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter.ScriptNameProp import sigma.serialization.ErgoTreeSerializer import sigma.ast.syntax._ +import sigma.compiler.Scalan import sigma.eval.SigmaDsl import scala.util.Random @@ -172,7 +172,7 @@ import scala.util.Random class LetsSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { suite => // Not mixed with TestContext since it is not possible to call compiler.compile outside tests if mixed - implicit lazy val IR: IRContext = new TestingIRContext + implicit lazy val IR: Scalan = new TestingIRContext lazy val project = new ErgoLikeTestProvingInterpreter() From 26da1fad2565eb2842871f323ce0eec0c09648b1 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Wed, 15 May 2024 22:11:03 +0100 Subject: [PATCH 51/65] refactor-ir-cake: Scalan renamed to IRContext --- sc/js/src/test/scala/scalan/Platform.scala | 6 +- sc/jvm/src/test/scala/scalan/Platform.scala | 12 +- .../scalan/compilation/GraphVizExport.scala | 6 +- .../InterpreterReflectionGeneratorTests.scala | 4 +- .../sigmastate/ReflectionGenerator.scala | 4 +- .../org/ergoplatform/ErgoScriptPredef.scala | 6 +- .../org/ergoplatform/dsl/ContractSpec.scala | 4 +- .../ergoplatform/dsl/ErgoContractSpec.scala | 4 +- .../src/main/scala/sigma/compiler/Base.scala | 4 +- .../scala/sigma/compiler/DefRewriting.scala | 2 +- .../main/scala/sigma/compiler/Entities.scala | 2 +- .../scala/sigma/compiler/GraphBuilding.scala | 4 +- .../sigma/compiler/GraphIRReflection.scala | 42 ++--- .../main/scala/sigma/compiler/IRContext.scala | 174 +++++++++++++++++- .../scala/sigma/compiler/MethodCalls.scala | 2 +- .../main/scala/sigma/compiler/Modules.scala | 2 +- .../main/scala/sigma/compiler/Scalan.scala | 174 ------------------ .../scala/sigma/compiler/TreeBuilding.scala | 2 +- .../main/scala/sigma/compiler/TypeDescs.scala | 2 +- .../sigma/compiler/primitives/Equal.scala | 4 +- .../sigma/compiler/primitives/Functions.scala | 4 +- .../compiler/primitives/IfThenElse.scala | 4 +- .../compiler/primitives/LogicalOps.scala | 4 +- .../compiler/primitives/NumericOps.scala | 4 +- .../compiler/primitives/OrderingOps.scala | 4 +- .../sigma/compiler/primitives/Thunks.scala | 7 +- .../sigma/compiler/primitives/Tuples.scala | 4 +- .../sigma/compiler/primitives/UnBinOps.scala | 4 +- .../compiler/primitives/UniversalOps.scala | 4 +- .../sigma/compiler/staged/AstGraphs.scala | 4 +- .../sigma/compiler/staged/ProgramGraphs.scala | 4 +- .../sigma/compiler/staged/Transforming.scala | 4 +- .../scala/sigmastate/lang/SigmaCompiler.scala | 10 +- .../scala/special/collection/CollsUnit.scala | 5 +- .../special/collection/impl/CollsImpl.scala | 8 +- .../scala/special/sigma/SigmaDslUnit.scala | 4 +- .../special/sigma/impl/SigmaDslImpl.scala | 8 +- .../sigma/wrappers/WrappersModule.scala | 4 +- .../special/wrappers/WrappersModule.scala | 4 +- .../main/scala/wrappers/scala/WOptions.scala | 4 +- .../wrappers/scala/impl/WOptionsImpl.scala | 8 +- .../main/scala/wrappers/scalan/WRTypes.scala | 4 +- .../wrappers/scalan/impl/WRTypesImpl.scala | 8 +- .../wrappers/special/WSpecialPredefs.scala | 4 +- .../special/impl/WSpecialPredefsImpl.scala | 9 +- .../ergoplatform/dsl/TestContractSpec.scala | 4 +- .../test/scala/scalan/BaseLiftableTests.scala | 4 +- .../src/test/scala/scalan/LibraryTests.scala | 4 +- .../src/test/scala/scalan/TestContexts.scala | 6 +- .../src/test/scala/scalan/TestLibrary.scala | 4 +- .../test/scala/sigma/CollsStagingTests.scala | 6 +- .../scala/sigma/SigmaDslStaginTests.scala | 4 +- .../test/scala/sigma/SigmaDslTesting.scala | 18 +- .../scala/sigmastate/CompilerTestsBase.scala | 8 +- .../ScriptVersionSwitchSpecification.scala | 6 +- .../sigmastate/eval/ErgoScriptTestkit.scala | 6 +- .../eval/ErgoTreeBuildingTest.scala | 4 +- .../helpers/CompilerTestingCommons.scala | 10 +- .../ErgoTreeSerializerSpecification.scala | 4 +- .../utxo/AVLTreeScriptsSpecification.scala | 6 +- .../UsingContextPropertiesSpecification.scala | 6 +- .../BlockchainSimulationTestingCommons.scala | 6 +- .../sigmastate/utxo/examples/IcoExample.scala | 4 +- .../utxo/examples/LetsSpecification.scala | 4 +- 64 files changed, 350 insertions(+), 355 deletions(-) delete mode 100644 sc/shared/src/main/scala/sigma/compiler/Scalan.scala diff --git a/sc/js/src/test/scala/scalan/Platform.scala b/sc/js/src/test/scala/scalan/Platform.scala index 2349a1f444..afb5ff72c1 100644 --- a/sc/js/src/test/scala/scalan/Platform.scala +++ b/sc/js/src/test/scala/scalan/Platform.scala @@ -1,16 +1,16 @@ package scalan -import sigma.compiler.Scalan +import sigma.compiler.IRContext import scala.annotation.unused object Platform { /** In JS tests do nothing. The corresponding JVM method outputs graphs into files. */ - def stage[Ctx <: Scalan](scalan: Ctx)( + def stage[Ctx <: IRContext](ctx: Ctx)( @unused prefix: String, @unused testName: String, @unused name: String, - @unused sfs: Seq[() => scalan.Sym]): Unit = { + @unused sfs: Seq[() => ctx.Sym]): Unit = { } /** On JS it is no-operation. */ diff --git a/sc/jvm/src/test/scala/scalan/Platform.scala b/sc/jvm/src/test/scala/scalan/Platform.scala index b9c65374c2..3a194a7d50 100644 --- a/sc/jvm/src/test/scala/scalan/Platform.scala +++ b/sc/jvm/src/test/scala/scalan/Platform.scala @@ -3,23 +3,23 @@ package scalan import scalan.compilation.GraphVizExport import sigma.util.FileUtil import org.scalatest.Assertions -import sigma.compiler.Scalan +import sigma.compiler.IRContext object Platform { /** Output graph given by symbols in `sfs` to files. - * @param scalan The Scalan context + * @param ctx The Scalan context * @param prefix The prefix of the directory where the graphs will be stored. * @param testName The name of the test. * @param name The name of the graph. * @param sfs A sequence of functions that return symbols of the graph roots. */ - def stage[Ctx <: Scalan](scalan: Ctx) - (prefix: String, testName: String, name: String, sfs: Seq[() => scalan.Sym]): Unit = { + def stage[Ctx <: IRContext](ctx: Ctx) + (prefix: String, testName: String, name: String, sfs: Seq[() => ctx.Sym]): Unit = { val directory = FileUtil.file(prefix, testName) - val gv = new GraphVizExport(scalan) + val gv = new GraphVizExport(ctx) implicit val graphVizConfig = gv.defaultGraphVizConfig try { - val ss = sfs.map(_.apply()).asInstanceOf[Seq[gv.scalan.Sym]] + val ss = sfs.map(_.apply()).asInstanceOf[Seq[gv.ctx.Sym]] gv.emitDepGraph(ss, directory, name)(graphVizConfig) } catch { case e: Exception => diff --git a/sc/jvm/src/test/scala/scalan/compilation/GraphVizExport.scala b/sc/jvm/src/test/scala/scalan/compilation/GraphVizExport.scala index c5b7f16cca..1072de00e2 100644 --- a/sc/jvm/src/test/scala/scalan/compilation/GraphVizExport.scala +++ b/sc/jvm/src/test/scala/scalan/compilation/GraphVizExport.scala @@ -3,7 +3,7 @@ package scalan.compilation import java.awt.Desktop import java.io.{File, PrintWriter} import scalan.core.ScalaNameUtil -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.util.{FileUtil, ProcessUtil, StringUtil} import scala.annotation.unused @@ -12,8 +12,8 @@ import scala.collection.immutable.StringOps // TODO implement this outside of the cake /** Implementation of Graphviz's dot file generator. */ -class GraphVizExport[Ctx <: Scalan](val scalan: Ctx) { - import scalan._ +class GraphVizExport[Ctx <: IRContext](val ctx: Ctx) { + import ctx._ case class GraphFile(file: File, fileType: String) { def open() = { Desktop.getDesktop.open(file) diff --git a/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala b/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala index 2a65dfedf5..7fc0e454ed 100644 --- a/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala +++ b/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala @@ -2,7 +2,7 @@ package sigmastate import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec -import sigma.compiler.{Scalan, TypeDescs} +import sigma.compiler.{IRContext, TypeDescs} import sigma.reflection.ReflectionData.registerClassEntry import sigma.reflection.SRConstructor @@ -37,7 +37,7 @@ class InterpreterReflectionGeneratorTests extends AnyPropSpec with Matchers { } property("inner class") { - val ctx = null.asInstanceOf[Scalan] // ok! type level only + val ctx = null.asInstanceOf[IRContext] // ok! type level only val clazz = classOf[ctx.Coll.CollElem[_, _]] registerClassEntry(clazz, constructors = Array( diff --git a/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala b/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala index 735297d119..963e1c56d1 100644 --- a/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala +++ b/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala @@ -30,7 +30,7 @@ object ReflectionGenerator { } val knownPackages = Array( - "scalan.primitives.", + "sigma.compiler.primitives.", "sigma.", "sigma.", "special.wrappers.", @@ -40,7 +40,7 @@ object ReflectionGenerator { "sigmastate.utxo.", "sigmastate.", "wrappers.scala.", - "scalan.", + "sigma.compiler.", "scala.collection.", "scala." ) diff --git a/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala b/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala index a2bc3362d7..1b84e7f0d6 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala @@ -6,13 +6,13 @@ import sigma.ast.SType import sigma.ast.syntax.SigmaPropValue import sigma.ast.Value import sigma.ast.syntax.ValueOps -import sigma.compiler.Scalan +import sigma.compiler.IRContext object ErgoScriptPredef { import sigmastate.interpreter.Interpreter._ /** Compiles the given ErgoScript `code` into ErgoTree expression. */ - def compileWithCosting(env: ScriptEnv, code: String, networkPrefix: NetworkPrefix)(implicit IR: Scalan): Value[SType] = { + def compileWithCosting(env: ScriptEnv, code: String, networkPrefix: NetworkPrefix)(implicit IR: IRContext): Value[SType] = { val compiler = SigmaCompiler(networkPrefix) val res = compiler.compile(env, code) res.buildTree @@ -30,7 +30,7 @@ object ErgoScriptPredef { tokenId: Array[Byte], thresholdAmount: Long, networkPrefix: NetworkPrefix) - (implicit IR: Scalan): SigmaPropValue = { + (implicit IR: IRContext): SigmaPropValue = { val env = emptyEnv + ("tokenId" -> tokenId, "thresholdAmount" -> thresholdAmount) val res = compileWithCosting(env, diff --git a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala index 539da9d79b..128351efea 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala @@ -9,7 +9,7 @@ import sigma.{Coll, SigmaDslBuilder, SigmaProp} import scala.util.Try import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition, Token} import sigma.ast.{ErgoTree, EvaluatedValue, SType} -import sigma.compiler.Scalan +import sigma.compiler.IRContext import scala.language.implicitConversions @@ -19,7 +19,7 @@ trait ContractSpec { implicit def Coll[T](items: Array[T])(implicit cT: RType[T]): Coll[T] = Colls.fromArray(items) - val IR: Scalan + val IR: IRContext trait PropositionSpec { def name: String diff --git a/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala b/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala index 6a91c6f60a..5929299a3b 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala @@ -3,10 +3,10 @@ package org.ergoplatform.dsl import sigma.Coll import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition, Token} import org.ergoplatform.ErgoBox.{BoxId, NonMandatoryRegisterId, TokenId} -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.interpreter.CostedProverResult -class ErgoContractSpec(implicit val IR: Scalan) extends ContractSpec { +class ErgoContractSpec(implicit val IR: IRContext) extends ContractSpec { case class ErgoOutBox(tx: TransactionCandidate, boxIndex: Int, value: Long, propSpec: PropositionSpec) extends OutBox { diff --git a/sc/shared/src/main/scala/sigma/compiler/Base.scala b/sc/shared/src/main/scala/sigma/compiler/Base.scala index b6e81f2a6f..3d6b763c5a 100644 --- a/sc/shared/src/main/scala/sigma/compiler/Base.scala +++ b/sc/shared/src/main/scala/sigma/compiler/Base.scala @@ -18,7 +18,7 @@ import scala.language.implicitConversions * The Base trait houses common AST nodes. It also manages a list of encountered definitions which * allows for common sub-expression elimination (CSE). */ -abstract class Base { scalan: Scalan => +abstract class Base { thisIR: IRContext => type |[+A, +B] = Either[A, B] type RFunc[-A,+B] = Ref[Function1[A,B]] type RPair[+A, +B] = Ref[(A,B)] @@ -554,7 +554,7 @@ abstract class Base { scalan: Scalan => private[compiler] def addOwnerParameter(ownerType: OwnerKind, params: Seq[Any]): Seq[AnyRef] = { val finalParams = (ownerType match { case EntityObjectOwner(obj) => obj +: params - case ScalanOwner => scalan +: params + case ScalanOwner => thisIR +: params case NoOwner => params }) finalParams.asInstanceOf[Seq[AnyRef]] diff --git a/sc/shared/src/main/scala/sigma/compiler/DefRewriting.scala b/sc/shared/src/main/scala/sigma/compiler/DefRewriting.scala index 38930d0307..0cc86c0644 100644 --- a/sc/shared/src/main/scala/sigma/compiler/DefRewriting.scala +++ b/sc/shared/src/main/scala/sigma/compiler/DefRewriting.scala @@ -3,7 +3,7 @@ package sigma.compiler import scalan.DelayInvokeException import sigma.data.ExactNumeric -trait DefRewriting { scalan: Scalan => +trait DefRewriting { scalan: IRContext => /** Rewrites given node to another equivalent node and returns its reference. * @param d node to be matched against rewrite patterns diff --git a/sc/shared/src/main/scala/sigma/compiler/Entities.scala b/sc/shared/src/main/scala/sigma/compiler/Entities.scala index 2cce7fe7d7..bfda787fc3 100644 --- a/sc/shared/src/main/scala/sigma/compiler/Entities.scala +++ b/sc/shared/src/main/scala/sigma/compiler/Entities.scala @@ -1,7 +1,7 @@ package sigma.compiler /** A slice in the Scalan cake with base classes for various descriptors. */ -trait Entities extends TypeDescs { self: Scalan => +trait Entities extends TypeDescs { self: IRContext => /** Base class for all descriptors of staged traits. * See derived classes in `impl` packages. diff --git a/sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala b/sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala index 784ee0e836..bbc1361dfe 100644 --- a/sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala +++ b/sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala @@ -26,7 +26,7 @@ import scala.collection.mutable.ArrayBuffer * CSE however means the original structure of source code may not be preserved in the * resulting ErgoTree. * */ -trait GraphBuilding extends Base with DefRewriting { IR: Scalan => +trait GraphBuilding extends Base with DefRewriting { IR: IRContext => import AvlTree._ import BigInt._ import Box._ @@ -58,7 +58,7 @@ trait GraphBuilding extends Base with DefRewriting { IR: Scalan => * In v5.x this code is taken from CheckTupleType validation rule which is no longer * part of consensus. */ - def checkTupleType[Ctx <: Scalan, T](ctx: Ctx)(e: ctx.Elem[_]): Unit = { + def checkTupleType[Ctx <: IRContext, T](ctx: Ctx)(e: ctx.Elem[_]): Unit = { val condition = e match { case _: ctx.PairElem[_, _] => true case _ => false diff --git a/sc/shared/src/main/scala/sigma/compiler/GraphIRReflection.scala b/sc/shared/src/main/scala/sigma/compiler/GraphIRReflection.scala index 054cfed9b7..59f1116569 100644 --- a/sc/shared/src/main/scala/sigma/compiler/GraphIRReflection.scala +++ b/sc/shared/src/main/scala/sigma/compiler/GraphIRReflection.scala @@ -22,7 +22,7 @@ object GraphIRReflection { val reflection = ReflectionData { val clazz = classOf[wrappers.scala.WOptions#WOption[_]] - val ctx = null.asInstanceOf[Scalan] // ok! type level only + val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "filter", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => @@ -46,8 +46,8 @@ object GraphIRReflection { registerClassEntry(classOf[TypeDescs#FuncElem[_,_]], constructors = Array( - mkConstructor(Array(classOf[Scalan], classOf[TypeDescs#Elem[_]], classOf[TypeDescs#Elem[_]])) { args => - val ctx = args(0).asInstanceOf[Scalan] + mkConstructor(Array(classOf[IRContext], classOf[TypeDescs#Elem[_]], classOf[TypeDescs#Elem[_]])) { args => + val ctx = args(0).asInstanceOf[IRContext] new ctx.FuncElem(args(1).asInstanceOf[ctx.Elem[_]], args(2).asInstanceOf[ctx.Elem[_]]) } ) @@ -55,8 +55,8 @@ object GraphIRReflection { registerClassEntry(classOf[TypeDescs#PairElem[_,_]], constructors = Array( - mkConstructor(Array(classOf[Scalan], classOf[TypeDescs#Elem[_]], classOf[TypeDescs#Elem[_]])) { args => - val ctx = args(0).asInstanceOf[Scalan] + mkConstructor(Array(classOf[IRContext], classOf[TypeDescs#Elem[_]], classOf[TypeDescs#Elem[_]])) { args => + val ctx = args(0).asInstanceOf[IRContext] new ctx.PairElem(args(1).asInstanceOf[ctx.Elem[_]], args(2).asInstanceOf[ctx.Elem[_]]) } ) @@ -64,8 +64,8 @@ object GraphIRReflection { registerClassEntry(classOf[Thunks#ThunkElem[_]], constructors = Array( - mkConstructor(Array(classOf[Scalan], classOf[TypeDescs#Elem[_]])) { args => - val ctx = args(0).asInstanceOf[Scalan] + mkConstructor(Array(classOf[IRContext], classOf[TypeDescs#Elem[_]])) { args => + val ctx = args(0).asInstanceOf[IRContext] new ctx.ThunkElem(args(1).asInstanceOf[ctx.Elem[_]]) } ) @@ -121,7 +121,7 @@ object GraphIRReflection { } { val clazz = classOf[Colls#CollBuilder] - val ctx = null.asInstanceOf[Scalan] // ok! type level only + val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "xor", Array[Class[_]](classOf[Base#Ref[_]], classOf[Base#Ref[_]])) { (obj, args) => @@ -143,7 +143,7 @@ object GraphIRReflection { { val clazz = classOf[Colls#Coll[_]] - val ctx = null.asInstanceOf[Scalan] // ok! type level only + val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "append", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => @@ -209,7 +209,7 @@ object GraphIRReflection { } { val clazz = classOf[SigmaDsl#AvlTree] - val ctx = null.asInstanceOf[Scalan] // ok! type level only + val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "updateOperations", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => @@ -267,7 +267,7 @@ object GraphIRReflection { } { val clazz = classOf[SigmaDsl#Box] - val ctx = null.asInstanceOf[Scalan] // ok! type level only + val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "value", Array[Class[_]]()) { (obj, _) => @@ -300,7 +300,7 @@ object GraphIRReflection { { val clazz = classOf[SigmaDsl#Context] - val ctx = null.asInstanceOf[Scalan] // ok! type level only + val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "LastBlockUtxoRootHash", Array[Class[_]]()) { (obj, args) => @@ -341,7 +341,7 @@ object GraphIRReflection { } { val clazz = classOf[SigmaDsl#GroupElement] - val ctx = null.asInstanceOf[Scalan] // ok! type level only + val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "exp", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => @@ -361,7 +361,7 @@ object GraphIRReflection { } { val clazz = classOf[SigmaDsl#Header] - val ctx = null.asInstanceOf[Scalan] // ok! type level only + val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "minerPk", Array[Class[_]]()) { (obj, args) => @@ -414,7 +414,7 @@ object GraphIRReflection { } { val clazz = classOf[SigmaDsl#PreHeader] - val ctx = null.asInstanceOf[Scalan] // ok! type level only + val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "minerPk", Array[Class[_]]()) { (obj, _) => @@ -443,7 +443,7 @@ object GraphIRReflection { } { val clazz = classOf[SigmaDsl#SigmaDslBuilder] - val ctx = null.asInstanceOf[Scalan] // ok! type level only + val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "byteArrayToLong", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => @@ -510,7 +510,7 @@ object GraphIRReflection { ) } - { val ctx = null.asInstanceOf[Scalan] // ok! type level only + { val ctx = null.asInstanceOf[IRContext] // ok! type level only val clazz = classOf[ctx.WOption.WOptionElem[_, _]] registerClassEntry(clazz, constructors = Array( @@ -523,7 +523,7 @@ object GraphIRReflection { } { val clazz = classOf[WRTypes#WRType[_]] - val ctx = null.asInstanceOf[Scalan] // ok! type level only + val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "name", Array[Class[_]]()) { (obj, _) => @@ -533,7 +533,7 @@ object GraphIRReflection { ) } - { val ctx = null.asInstanceOf[Scalan] // ok! type level only + { val ctx = null.asInstanceOf[IRContext] // ok! type level only val clazz = classOf[ctx.WRType.WRTypeElem[_, _]] registerClassEntry(clazz, constructors = Array( @@ -545,7 +545,7 @@ object GraphIRReflection { ) } - { val ctx = null.asInstanceOf[Scalan] // ok! type level only + { val ctx = null.asInstanceOf[IRContext] // ok! type level only val clazz = classOf[ctx.Coll.CollElem[_, _]] registerClassEntry(clazz, constructors = Array( @@ -558,7 +558,7 @@ object GraphIRReflection { } { val clazz = classOf[wrappers.special.WSpecialPredefs#WSpecialPredefCompanion] - val ctx = null.asInstanceOf[Scalan] // ok! type level only + val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( mkMethod(clazz, "some", Array[Class[_]](classOf[Base#Ref[_]])) { (obj, args) => diff --git a/sc/shared/src/main/scala/sigma/compiler/IRContext.scala b/sc/shared/src/main/scala/sigma/compiler/IRContext.scala index 0b958b9ab9..2f31d71589 100644 --- a/sc/shared/src/main/scala/sigma/compiler/IRContext.scala +++ b/sc/shared/src/main/scala/sigma/compiler/IRContext.scala @@ -1,6 +1,176 @@ package sigma.compiler -trait IRContext extends Scalan +import scalan._ +import sigma.compiler.primitives._ +import sigma.compiler.staged.Transforming +import sigma.data.{Nullable, RType} +import sigma.util.MemoizedFunc +import sigma.{CollsModule, SigmaDslModule} +import special.wrappers.WrappersModule + +/** Aggregate cake with all inter-dependent modules assembled together. + * Each instance of this class contains independent IR context, thus many + * instances can be created simultaneously. + * However, the inner types declared in the traits are path-dependant. + * This in particular means that ctx1.Ref[_] and ctx2.Ref[_] are different types. + * The typical usage is to create `val ctx = new Scalan` and then import inner + * declarations using `import ctx._`. + * This way the declaration will be directly available as if they were global + * declarations. + * At the same time cake design pattern allow to `override` many methods and values + * in classed derived from `Scalan`, this is significant benefit over + * *everything is global* design. + * + * It is not used in v5.0 interpreter and thus not part of consensus. + * Used in ErgoScript compiler only. + * + * @see CompiletimeIRContext + */ +trait IRContext + extends TypeDescs + with MethodCalls + with Tuples + with NumericOps + with UnBinOps + with LogicalOps + with OrderingOps + with Equal + with UniversalOps + with Functions + with IfThenElse + with Transforming + with Thunks + with Entities + with Modules + with DefRewriting + with WrappersModule + with CollsModule + with sigma.wrappers.WrappersModule + with SigmaDslModule + with TreeBuilding + with GraphBuilding { + + import Coll._ + import CollBuilder._ + import WOption._ + import WRType._ + import WSpecialPredef._ + + /** Pass configuration which is used to turn-off constant propagation. + * USED IN TESTS ONLY. + * @see `beginPass(noCostPropagationPass)` */ + lazy val noConstPropagationPass = new DefaultPass( + "noCostPropagationPass", + Pass.defaultPassConfig.copy(constantPropagation = false)) + + type LazyRep[T] = MutableLazy[Ref[T]] + + private val _liftElemMemo = new MemoizedFunc({ + case eT: Elem[t] => + val lT = Liftables.asLiftable[Any, t](eT.liftable) + liftableRType(lT).lift(eT.sourceType.asInstanceOf[RType[Any]]) + }) + implicit def liftElem[T](eT: Elem[T]): Ref[WRType[T]] = { + _liftElemMemo(eT).asInstanceOf[Ref[WRType[T]]] // asRep cannot be used for AnyRef + } + + private val _specialPredef: LazyRep[WSpecialPredefCompanionCtor] = MutableLazy(RWSpecialPredef.value) + def specialPredef: Ref[WSpecialPredefCompanionCtor] = _specialPredef.value + + override protected def onReset(): Unit = { + _specialPredef.reset() + _liftElemMemo.reset() + super.onReset() + } + + val CM = CollMethods + private val CBM = CollBuilderMethods + private val WOptionM = WOptionMethods + private val SPCM = WSpecialPredefCompanionMethods + + def colBuilder: Ref[CollBuilder] + + implicit lazy val wRTypeAnyElement: Elem[WRType[Any]] = wRTypeElement(AnyElement) + + /** During compilation represent a global value Global, see also SGlobal type. */ + def sigmaDslBuilder: Ref[SigmaDslBuilder] + + object IsNumericToInt { + def unapply(d: Def[_]): Nullable[Ref[A] forSome {type A}] = d match { + case ApplyUnOp(_: NumericToInt[_], x) => Nullable(x.asInstanceOf[Ref[A] forSome {type A}]) + case _ => Nullable.None + } + } + object IsNumericToLong { + def unapply(d: Def[_]): Nullable[Ref[A] forSome {type A}] = d match { + case ApplyUnOp(_: NumericToLong[_], x) => Nullable(x.asInstanceOf[Ref[A] forSome {type A}]) + case _ => Nullable.None + } + } + + override def rewriteDef[T](d: Def[T]) = d match { + case CM.length(ys) => ys.node match { + // Rule: xs.map(f).length ==> xs.length + case CM.map(xs, _) => + xs.length + // Rule: replicate(len, v).length => len + case CBM.replicate(_, len, _) => + len + // Rule: Const[Coll[T]](coll).length => + case CollConst(coll, _) => + coll.length + // Rule: Coll(items @ Seq(x1, x2, x3)).length => items.length + case CBM.fromItems(_, items, _) => + items.length + case _ => super.rewriteDef(d) + } + + // Rule: replicate(l, x).zip(replicate(l, y)) ==> replicate(l, (x,y)) + case CM.zip(CBM.replicate(b1, l1, v1), CBM.replicate(b2, l2, v2)) if b1 == b2 && l1 == l2 => + b1.replicate(l1, Pair(v1, v2)) + + case CM.map(xs, _f) => _f.node match { + case IdentityLambda() => xs + case _ => xs.node match { + // Rule: replicate(l, v).map(f) ==> replicate(l, f(v)) + case CBM.replicate(b, l, v: Ref[a]) => + val f = asRep[a => Any](_f) + b.replicate(l, Apply(f, v, false)) + + // Rule: xs.map(f).map(g) ==> xs.map(x => g(f(x))) + case CM.map(_xs, f: RFunc[a, b]) => + implicit val ea = f.elem.eDom + val xs = asRep[Coll[a]](_xs) + val g = asRep[b => Any](_f) + xs.map[Any](fun { x: Ref[a] => g(f(x)) }) + + case _ => super.rewriteDef(d) + } + } + + case WOptionM.getOrElse(opt, _) => opt.node match { + // Rule: Some(x).getOrElse(_) ==> x + case SPCM.some(x) => x + case WOptionConst(Some(x), lA) => lA.lift(x) + case _ => super.rewriteDef(d) + } + + case _ => super.rewriteDef(d) + } + + override def invokeUnlifted(e: Elem[_], mc: MethodCall, dataEnv: DataEnv): Any = e match { + case _: CollElem[_,_] => mc match { + case CollMethods.map(_, f) => + val newMC = mc.copy(args = mc.args :+ f.elem.eRange)(mc.resultType, mc.isAdapterCall) + super.invokeUnlifted(e, newMC, dataEnv) + case _ => + super.invokeUnlifted(e, mc, dataEnv) + } + case _ => + super.invokeUnlifted(e, mc, dataEnv) + } + +} /** IR context to be used by script development tools to compile ErgoScript into ErgoTree bytecode. */ -class CompiletimeIRContext extends Scalan +class CompiletimeIRContext extends IRContext diff --git a/sc/shared/src/main/scala/sigma/compiler/MethodCalls.scala b/sc/shared/src/main/scala/sigma/compiler/MethodCalls.scala index 4a0a189edd..4b534930d8 100644 --- a/sc/shared/src/main/scala/sigma/compiler/MethodCalls.scala +++ b/sc/shared/src/main/scala/sigma/compiler/MethodCalls.scala @@ -7,7 +7,7 @@ import sigma.util.CollectionUtil.TraversableOps import scala.annotation.{tailrec, unused} -trait MethodCalls extends Base { self: Scalan => +trait MethodCalls extends Base { self: IRContext => def delayInvoke = throw new DelayInvokeException diff --git a/sc/shared/src/main/scala/sigma/compiler/Modules.scala b/sc/shared/src/main/scala/sigma/compiler/Modules.scala index 94cbaf9816..527dcd6eb8 100644 --- a/sc/shared/src/main/scala/sigma/compiler/Modules.scala +++ b/sc/shared/src/main/scala/sigma/compiler/Modules.scala @@ -1,6 +1,6 @@ package sigma.compiler -trait Modules extends Base { self: Scalan => +trait Modules extends Base { self: IRContext => /** Whether staged modules should be registered when cake is constructed and initialized. */ def okRegisterModules: Boolean = false diff --git a/sc/shared/src/main/scala/sigma/compiler/Scalan.scala b/sc/shared/src/main/scala/sigma/compiler/Scalan.scala deleted file mode 100644 index 8009cd5e36..0000000000 --- a/sc/shared/src/main/scala/sigma/compiler/Scalan.scala +++ /dev/null @@ -1,174 +0,0 @@ -package sigma.compiler - -import scalan._ -import sigma.compiler.primitives.{Equal, Functions, IfThenElse, LogicalOps, NumericOps, OrderingOps, Thunks, Tuples, UnBinOps, UniversalOps} -import sigma.compiler.staged.Transforming -import sigma.data.{Nullable, RType} -import sigma.util.MemoizedFunc -import sigma.{CollsModule, SigmaDslModule} -import special.wrappers.WrappersModule - -/** Aggregate cake with all inter-dependent modules assembled together. - * Each instance of this class contains independent IR context, thus many - * instances can be created simultaneously. - * However, the inner types declared in the traits are path-dependant. - * This in particular means that ctx1.Ref[_] and ctx2.Ref[_] are different types. - * The typical usage is to create `val ctx = new Scalan` and then import inner - * declarations using `import ctx._`. - * This way the declaration will be directly available as if they were global - * declarations. - * At the same time cake design pattern allow to `override` many methods and values - * in classed derived from `Scalan`, this is significant benefit over - * *everything is global* design. - * - * It is not used in v5.0 interpreter and thus not part of consensus. - * Used in ErgoScript compiler only. - * - * @see CompiletimeIRContext - */ -trait Scalan - extends TypeDescs - with MethodCalls - with Tuples - with NumericOps - with UnBinOps - with LogicalOps - with OrderingOps - with Equal - with UniversalOps - with Functions - with IfThenElse - with Transforming - with Thunks - with Entities - with Modules - with DefRewriting - with WrappersModule - with CollsModule - with sigma.wrappers.WrappersModule - with SigmaDslModule - with TreeBuilding - with GraphBuilding { - - import Coll._ - import CollBuilder._ - import WOption._ - import WRType._ - import WSpecialPredef._ - - /** Pass configuration which is used to turn-off constant propagation. - * USED IN TESTS ONLY. - * @see `beginPass(noCostPropagationPass)` */ - lazy val noConstPropagationPass = new DefaultPass( - "noCostPropagationPass", - Pass.defaultPassConfig.copy(constantPropagation = false)) - - type LazyRep[T] = MutableLazy[Ref[T]] - - private val _liftElemMemo = new MemoizedFunc({ - case eT: Elem[t] => - val lT = Liftables.asLiftable[Any, t](eT.liftable) - liftableRType(lT).lift(eT.sourceType.asInstanceOf[RType[Any]]) - }) - implicit def liftElem[T](eT: Elem[T]): Ref[WRType[T]] = { - _liftElemMemo(eT).asInstanceOf[Ref[WRType[T]]] // asRep cannot be used for AnyRef - } - - private val _specialPredef: LazyRep[WSpecialPredefCompanionCtor] = MutableLazy(RWSpecialPredef.value) - def specialPredef: Ref[WSpecialPredefCompanionCtor] = _specialPredef.value - - override protected def onReset(): Unit = { - _specialPredef.reset() - _liftElemMemo.reset() - super.onReset() - } - - val CM = CollMethods - private val CBM = CollBuilderMethods - private val WOptionM = WOptionMethods - private val SPCM = WSpecialPredefCompanionMethods - - def colBuilder: Ref[CollBuilder] - - implicit lazy val wRTypeAnyElement: Elem[WRType[Any]] = wRTypeElement(AnyElement) - - /** During compilation represent a global value Global, see also SGlobal type. */ - def sigmaDslBuilder: Ref[SigmaDslBuilder] - - object IsNumericToInt { - def unapply(d: Def[_]): Nullable[Ref[A] forSome {type A}] = d match { - case ApplyUnOp(_: NumericToInt[_], x) => Nullable(x.asInstanceOf[Ref[A] forSome {type A}]) - case _ => Nullable.None - } - } - object IsNumericToLong { - def unapply(d: Def[_]): Nullable[Ref[A] forSome {type A}] = d match { - case ApplyUnOp(_: NumericToLong[_], x) => Nullable(x.asInstanceOf[Ref[A] forSome {type A}]) - case _ => Nullable.None - } - } - - override def rewriteDef[T](d: Def[T]) = d match { - case CM.length(ys) => ys.node match { - // Rule: xs.map(f).length ==> xs.length - case CM.map(xs, _) => - xs.length - // Rule: replicate(len, v).length => len - case CBM.replicate(_, len, _) => - len - // Rule: Const[Coll[T]](coll).length => - case CollConst(coll, _) => - coll.length - // Rule: Coll(items @ Seq(x1, x2, x3)).length => items.length - case CBM.fromItems(_, items, _) => - items.length - case _ => super.rewriteDef(d) - } - - // Rule: replicate(l, x).zip(replicate(l, y)) ==> replicate(l, (x,y)) - case CM.zip(CBM.replicate(b1, l1, v1), CBM.replicate(b2, l2, v2)) if b1 == b2 && l1 == l2 => - b1.replicate(l1, Pair(v1, v2)) - - case CM.map(xs, _f) => _f.node match { - case IdentityLambda() => xs - case _ => xs.node match { - // Rule: replicate(l, v).map(f) ==> replicate(l, f(v)) - case CBM.replicate(b, l, v: Ref[a]) => - val f = asRep[a => Any](_f) - b.replicate(l, Apply(f, v, false)) - - // Rule: xs.map(f).map(g) ==> xs.map(x => g(f(x))) - case CM.map(_xs, f: RFunc[a, b]) => - implicit val ea = f.elem.eDom - val xs = asRep[Coll[a]](_xs) - val g = asRep[b => Any](_f) - xs.map[Any](fun { x: Ref[a] => g(f(x)) }) - - case _ => super.rewriteDef(d) - } - } - - case WOptionM.getOrElse(opt, _) => opt.node match { - // Rule: Some(x).getOrElse(_) ==> x - case SPCM.some(x) => x - case WOptionConst(Some(x), lA) => lA.lift(x) - case _ => super.rewriteDef(d) - } - - case _ => super.rewriteDef(d) - } - - override def invokeUnlifted(e: Elem[_], mc: MethodCall, dataEnv: DataEnv): Any = e match { - case _: CollElem[_,_] => mc match { - case CollMethods.map(_, f) => - val newMC = mc.copy(args = mc.args :+ f.elem.eRange)(mc.resultType, mc.isAdapterCall) - super.invokeUnlifted(e, newMC, dataEnv) - case _ => - super.invokeUnlifted(e, mc, dataEnv) - } - case _ => - super.invokeUnlifted(e, mc, dataEnv) - } - -} - diff --git a/sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala b/sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala index f781215901..de6437645f 100644 --- a/sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala +++ b/sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala @@ -22,7 +22,7 @@ import scala.collection.mutable.ArrayBuffer * * @see buildTree method * */ -trait TreeBuilding extends Base { IR: Scalan => +trait TreeBuilding extends Base { IR: IRContext => import BigInt._ import Box._ import Coll._ diff --git a/sc/shared/src/main/scala/sigma/compiler/TypeDescs.scala b/sc/shared/src/main/scala/sigma/compiler/TypeDescs.scala index 875c3f7b9a..6e2de8d952 100644 --- a/sc/shared/src/main/scala/sigma/compiler/TypeDescs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/TypeDescs.scala @@ -12,7 +12,7 @@ import scala.collection.immutable.ListMap import scala.collection.mutable import scala.language.implicitConversions -abstract class TypeDescs extends Base { self: Scalan => +abstract class TypeDescs extends Base { self: IRContext => /** Helper type case method. */ @inline final def asElem[T](d: TypeDesc): Elem[T] = d.asInstanceOf[Elem[T]] diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/Equal.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/Equal.scala index f0aab234b2..fc6e67fbfd 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/Equal.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/Equal.scala @@ -1,10 +1,10 @@ package sigma.compiler.primitives -import sigma.compiler.{Base, Scalan} +import sigma.compiler.{Base, IRContext} import scala.annotation.unused -trait Equal extends Base { self: Scalan => +trait Equal extends Base { self: IRContext => /** Binary operation representing structural equality between arguments. */ case class Equals[A: Elem]() extends BinOp[A, Boolean]("==") { override def applySeq(x: A, y: A): Boolean = equalValues[A](x, y) diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala index f572f2b126..dce2578d4f 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala @@ -2,14 +2,14 @@ package sigma.compiler.primitives import debox.{cfor, Buffer => DBuffer} import sigma.compiler.staged.ProgramGraphs -import sigma.compiler.{Base, Scalan} +import sigma.compiler.{Base, IRContext} import sigma.data.{Lazy, Nullable, emptyDBufferOfInt} import sigma.util.GraphUtil import java.util import scala.language.implicitConversions -trait Functions extends Base with ProgramGraphs { self: Scalan => +trait Functions extends Base with ProgramGraphs { self: IRContext => implicit class LambdaOps[A,B](f: Ref[A => B]) { /** Apply given function symbol to the given argument symbol. diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/IfThenElse.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/IfThenElse.scala index 57d742b194..e09036fcaf 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/IfThenElse.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/IfThenElse.scala @@ -1,8 +1,8 @@ package sigma.compiler.primitives -import sigma.compiler.{Base, Scalan} +import sigma.compiler.{Base, IRContext} -trait IfThenElse extends Base { self: Scalan => +trait IfThenElse extends Base { self: IRContext => /** If c then t else e construction with standard lazy evaluation of branches. * The representation uses Thunk for each branch */ diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/LogicalOps.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/LogicalOps.scala index 16510eb1fa..faf186bf04 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/LogicalOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/LogicalOps.scala @@ -1,9 +1,9 @@ package sigma.compiler.primitives -import sigma.compiler.{Base, Scalan} +import sigma.compiler.{Base, IRContext} /** Slice in Scala cake with definitions of logical operations. */ -trait LogicalOps extends Base { self: Scalan => +trait LogicalOps extends Base { self: IRContext => /** Logical AND binary operation. */ val And = new EndoBinOp[Boolean]("&&") { override def applySeq(x: Boolean, y: Boolean): Boolean = x && y diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/NumericOps.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/NumericOps.scala index 8783df2ce1..de3f2e6fed 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/NumericOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/NumericOps.scala @@ -1,10 +1,10 @@ package sigma.compiler.primitives -import sigma.compiler.{Base, Scalan} +import sigma.compiler.{Base, IRContext} import sigma.data.{ExactIntegral, ExactNumeric} /** Slice in Scala cake with definitions of numeric operations. */ -trait NumericOps extends Base { self: Scalan => +trait NumericOps extends Base { self: IRContext => /** Extension methods over `Ref[T]` where T is instance of ExactNumeric type-class. */ implicit class NumericOpsCls[T](x: Ref[T])(implicit val n: ExactNumeric[T]) { diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/OrderingOps.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/OrderingOps.scala index d125787d07..31d4c88365 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/OrderingOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/OrderingOps.scala @@ -1,12 +1,12 @@ package sigma.compiler.primitives -import sigma.compiler.{Base, Scalan} +import sigma.compiler.{Base, IRContext} import sigma.data.ExactOrdering import scala.language.implicitConversions /** Slice in Scala cake with definitions of comparison operations. */ -trait OrderingOps extends Base { self: Scalan => +trait OrderingOps extends Base { self: IRContext => implicit def repOrderingToOrderingOps[T](x: Ref[T])(implicit n: ExactOrdering[T]) = new OrderingOpsCls(x) implicit def OrderingToOrderingOps[T](x: T)(implicit n: ExactOrdering[T], et: Elem[T]) = new OrderingOpsCls(toRep(x)) diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/Thunks.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/Thunks.scala index 24b9e97708..2b5c97fcba 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/Thunks.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/Thunks.scala @@ -2,7 +2,7 @@ package sigma.compiler.primitives import debox.{cfor, Buffer => DBuffer, Set => DSet} import scalan.core.Covariant -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.data.{AVHashMap, DFunc, Lazy, Nullable, RType} import sigma.reflection.RClass import sigma.util.GraphUtil @@ -10,12 +10,13 @@ import sigma.util.GraphUtil import scala.collection.Seq import scala.language.{existentials, implicitConversions} -/** Slice in the [[Scalan]] cake with definitions of Thunk operations. +/** Slice in the [[IRContext]] cake with definitions of Thunk operations. * See https://en.wikipedia.org/wiki/Thunk. * Thunks are used to represent lazy operations in the graph IR. + * * @see ApplyBinOpLazy, IfThenElseLazy */ -trait Thunks extends Functions { self: Scalan => +trait Thunks extends Functions { self: IRContext => type Th[+T] = Ref[Thunk[T]] diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/Tuples.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/Tuples.scala index ae30569c29..d0455d0106 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/Tuples.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/Tuples.scala @@ -4,12 +4,12 @@ */ package sigma.compiler.primitives -import sigma.compiler.{Base, Scalan} +import sigma.compiler.{Base, IRContext} import sigma.data.AVHashMap import scala.language.implicitConversions -trait Tuples extends Base { self: Scalan => +trait Tuples extends Base { self: IRContext => object Pair { def apply[A, B](a: Ref[A], b: Ref[B]) = zipPair[A, B]((a, b)) def unapply[A, B](p: Ref[(A, B)]) = Some(unzipPair[A, B](p)) diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/UnBinOps.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/UnBinOps.scala index 701239488d..4bb9b6b9ab 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/UnBinOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/UnBinOps.scala @@ -1,8 +1,8 @@ package sigma.compiler.primitives -import sigma.compiler.{Base, Scalan} +import sigma.compiler.{Base, IRContext} -trait UnBinOps extends Base { self: Scalan => +trait UnBinOps extends Base { self: IRContext => /** Base class for descriptors of unary operations. */ abstract class UnOp[A, R](val opName: String)(implicit val eResult: Elem[R]) { diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/UniversalOps.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/UniversalOps.scala index c6dd96f03b..b83e152b4f 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/UniversalOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/UniversalOps.scala @@ -1,8 +1,8 @@ package sigma.compiler.primitives -import sigma.compiler.{Base, Scalan} +import sigma.compiler.{Base, IRContext} -trait UniversalOps extends Base { scalan: Scalan => +trait UniversalOps extends Base { self: IRContext => case class HashCode[A]() extends UnOp[A, Int]("hashCode") { override def applySeq(x: A): Int = x.hashCode } diff --git a/sc/shared/src/main/scala/sigma/compiler/staged/AstGraphs.scala b/sc/shared/src/main/scala/sigma/compiler/staged/AstGraphs.scala index 09000db191..5ee20810fa 100644 --- a/sc/shared/src/main/scala/sigma/compiler/staged/AstGraphs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/staged/AstGraphs.scala @@ -1,13 +1,13 @@ package sigma.compiler.staged import debox.{cfor, Buffer => DBuffer, Map => DMap, Set => DSet} -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.data.emptyDBufferOfInt import scala.collection._ -trait AstGraphs extends Transforming { self: Scalan => +trait AstGraphs extends Transforming { self: IRContext => /** GraphNode is created for each symbol of the AstGraph and represents graph linking structure */ case class GraphNode( diff --git a/sc/shared/src/main/scala/sigma/compiler/staged/ProgramGraphs.scala b/sc/shared/src/main/scala/sigma/compiler/staged/ProgramGraphs.scala index 1c8617bc74..67220d1002 100644 --- a/sc/shared/src/main/scala/sigma/compiler/staged/ProgramGraphs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/staged/ProgramGraphs.scala @@ -1,13 +1,13 @@ package sigma.compiler.staged import debox.{cfor, Buffer => DBuffer} -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.data.{DFunc, Nullable} import sigma.util.GraphUtil import scala.collection.compat.immutable.ArraySeq -trait ProgramGraphs extends AstGraphs { self: Scalan => +trait ProgramGraphs extends AstGraphs { self: IRContext => type PGraph = ProgramGraph diff --git a/sc/shared/src/main/scala/sigma/compiler/staged/Transforming.scala b/sc/shared/src/main/scala/sigma/compiler/staged/Transforming.scala index 90cc2dd350..6d729d35d0 100644 --- a/sc/shared/src/main/scala/sigma/compiler/staged/Transforming.scala +++ b/sc/shared/src/main/scala/sigma/compiler/staged/Transforming.scala @@ -1,14 +1,14 @@ package sigma.compiler.staged import debox.{cfor, Buffer => DBuffer} -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.data.{Lazy, Nullable} import sigma.reflection.RMethod import java.util import scala.language.existentials -trait Transforming { self: Scalan => +trait Transforming { self: IRContext => /** Descriptor of a current compiler pass. * Compiler can be configured to perform one pass after another. diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala index 4392e97216..f12a385973 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala @@ -12,7 +12,7 @@ import sigmastate.lang.parsers.ParserException import sigma.ast._ import sigma.ast.syntax.SValue import SCollectionMethods.{ExistsMethod, ForallMethod, MapMethod} -import sigma.compiler.{GraphIRReflection, Scalan} +import sigma.compiler.{GraphIRReflection, IRContext} import sigmastate.InterpreterReflection /** @@ -37,7 +37,7 @@ case class CompilerSettings( * @param compiledGraph graph obtained by using new [[GraphBuilding]] * @param buildTree ErgoTree expression obtained from graph created by [[GraphBuilding]] */ -case class CompilerResult[Ctx <: Scalan]( +case class CompilerResult[Ctx <: IRContext]( env: ScriptEnv, code: String, compiledGraph: Ctx#Ref[Ctx#Context => Any], @@ -83,14 +83,14 @@ class SigmaCompiler private(settings: CompilerSettings) { } /** Compiles the given ErgoScript source code. */ - def compile(env: ScriptEnv, code: String)(implicit IR: Scalan): CompilerResult[IR.type] = { + def compile(env: ScriptEnv, code: String)(implicit IR: IRContext): CompilerResult[IR.type] = { val typed = typecheck(env, code) val res = compileTyped(env, typed).copy(code = code) res } /** Compiles the given typed expression. */ - def compileTyped(env: ScriptEnv, typedExpr: SValue)(implicit IR: Scalan): CompilerResult[IR.type] = { + def compileTyped(env: ScriptEnv, typedExpr: SValue)(implicit IR: IRContext): CompilerResult[IR.type] = { val placeholdersEnv = env .collect { case (name, t: SType) => name -> t } .zipWithIndex @@ -102,7 +102,7 @@ class SigmaCompiler private(settings: CompilerSettings) { } /** Compiles the given parsed contract source. */ - def compileParsed(env: ScriptEnv, parsedExpr: SValue)(implicit IR: Scalan): CompilerResult[IR.type] = { + def compileParsed(env: ScriptEnv, parsedExpr: SValue)(implicit IR: IRContext): CompilerResult[IR.type] = { val typed = typecheck(env, parsedExpr) compileTyped(env, typed) } diff --git a/sc/shared/src/main/scala/special/collection/CollsUnit.scala b/sc/shared/src/main/scala/special/collection/CollsUnit.scala index a057f40f7a..53bf6f0530 100644 --- a/sc/shared/src/main/scala/special/collection/CollsUnit.scala +++ b/sc/shared/src/main/scala/special/collection/CollsUnit.scala @@ -1,6 +1,5 @@ package sigma { - import scalan._ - import sigma.compiler.{Base, Scalan} + import sigma.compiler.{Base, IRContext} /** Staged version of collection interfaces which is used in graph-based IR to represent * methods of Coll and CollBuilder. @@ -9,7 +8,7 @@ package sigma { * The semantics of each method is the same as in the original class, please look there * for details. */ - trait Colls extends Base { self: Scalan => + trait Colls extends Base { self: IRContext => trait Coll[A] extends Def[Coll[A]] { implicit def eA: Elem[A]; def length: Ref[Int]; diff --git a/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala b/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala index c85621bbbe..a14b2eb3b4 100644 --- a/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala +++ b/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala @@ -2,18 +2,18 @@ package sigma import scala.language.{existentials, implicitConversions} import scalan._ -import sigma.compiler.Scalan +import sigma.compiler.IRContext import scala.collection.compat.immutable.ArraySeq package impl { - import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, Scalan} + import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, IRContext} import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} // Abs ----------------------------------- trait CollsDefs extends Base with Colls { - self: Scalan => + self: IRContext => registerModule(CollsModule) @@ -642,4 +642,4 @@ object CollsModule extends ModuleInfo("sigma", "Colls") { } } -trait CollsModule extends sigma.impl.CollsDefs {self: Scalan =>} +trait CollsModule extends sigma.impl.CollsDefs {self: IRContext =>} diff --git a/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala b/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala index 6cc97daba6..a6fb60870c 100644 --- a/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala +++ b/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala @@ -1,8 +1,8 @@ package sigma { import scalan._ - import sigma.compiler.{Base, Scalan} + import sigma.compiler.{Base, IRContext} - trait SigmaDsl extends Base { self: Scalan => + trait SigmaDsl extends Base { self: IRContext => trait BigInt extends Def[BigInt] { def add(that: Ref[BigInt]): Ref[BigInt]; def subtract(that: Ref[BigInt]): Ref[BigInt]; diff --git a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala index 760f5094ca..a76ddb47d4 100644 --- a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala +++ b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala @@ -2,18 +2,18 @@ package sigma import scala.language.{existentials, implicitConversions} import scalan._ -import sigma.compiler.Scalan +import sigma.compiler.IRContext import scala.collection.compat.immutable.ArraySeq package impl { - import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, Scalan} + import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, IRContext} import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} // Abs ----------------------------------- trait SigmaDslDefs extends Base with SigmaDsl { - self: Scalan => + self: IRContext => registerModule(SigmaDslModule) @@ -2326,4 +2326,4 @@ object SigmaDslModule extends ModuleInfo("sigma", "SigmaDsl") { } } -trait SigmaDslModule extends sigma.impl.SigmaDslDefs {self: Scalan =>} +trait SigmaDslModule extends sigma.impl.SigmaDslDefs {self: IRContext =>} diff --git a/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala b/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala index 1250487071..6620d9db8f 100644 --- a/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala +++ b/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala @@ -1,6 +1,6 @@ package sigma.wrappers -import sigma.compiler.Scalan +import sigma.compiler.IRContext trait WrappersModule - extends special.wrappers.WrappersModule { self: Scalan => } + extends special.wrappers.WrappersModule { self: IRContext => } diff --git a/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala b/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala index 1a25f6a9d4..0d67f6147a 100644 --- a/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala +++ b/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala @@ -1,6 +1,6 @@ package special.wrappers -import sigma.compiler.Scalan +import sigma.compiler.IRContext import wrappers.scala.WOptionsModule import wrappers.scalan.WRTypesModule import wrappers.special.WSpecialPredefsModule @@ -8,4 +8,4 @@ import wrappers.special.WSpecialPredefsModule trait WrappersModule extends WSpecialPredefsModule with WOptionsModule - with WRTypesModule { self: Scalan => } \ No newline at end of file + with WRTypesModule { self: IRContext => } \ No newline at end of file diff --git a/sc/shared/src/main/scala/wrappers/scala/WOptions.scala b/sc/shared/src/main/scala/wrappers/scala/WOptions.scala index 830d05233f..4f41d0d025 100644 --- a/sc/shared/src/main/scala/wrappers/scala/WOptions.scala +++ b/sc/shared/src/main/scala/wrappers/scala/WOptions.scala @@ -1,9 +1,9 @@ package wrappers.scala { import scalan._ - import sigma.compiler.{Base, Scalan} + import sigma.compiler.{Base, IRContext} import special.wrappers.WrappersModule - trait WOptions extends Base { self: Scalan => + trait WOptions extends Base { self: IRContext => trait WOption[A] extends Def[WOption[A]] { implicit def eA: Elem[A]; def isDefined: Ref[Boolean]; diff --git a/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala b/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala index b1006c4e9f..915a271de9 100644 --- a/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala +++ b/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala @@ -2,20 +2,20 @@ package wrappers.scala import scala.language.{existentials, implicitConversions} import scalan._ -import sigma.compiler.Scalan +import sigma.compiler.IRContext import special.wrappers.WrappersModule import special.wrappers.OptionWrapSpec import scala.collection.compat.immutable.ArraySeq package impl { - import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, Scalan} + import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, IRContext} import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} // Abs ----------------------------------- trait WOptionsDefs extends Base with WOptions { - self: Scalan => + self: IRContext => class WOptionCls extends EntityObject("WOption") { // entityConst: single const for each entity @@ -243,4 +243,4 @@ object WOptionsModule extends ModuleInfo("wrappers.scala", "WOptions") { } } -trait WOptionsModule extends wrappers.scala.impl.WOptionsDefs {self: Scalan =>} +trait WOptionsModule extends wrappers.scala.impl.WOptionsDefs {self: IRContext =>} diff --git a/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala b/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala index 204fa40957..99f87242df 100644 --- a/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala +++ b/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala @@ -1,9 +1,9 @@ package wrappers.scalan { import scalan._ - import sigma.compiler.{Base, Scalan} + import sigma.compiler.{Base, IRContext} - trait WRTypes extends Base { self: Scalan => + trait WRTypes extends Base { self: IRContext => trait WRType[A] extends Def[WRType[A]] { implicit def eA: Elem[A]; def name: Ref[String] diff --git a/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala b/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala index 7868546bb9..55923c757b 100644 --- a/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala +++ b/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala @@ -1,6 +1,6 @@ package wrappers.scalan -import sigma.compiler.Scalan +import sigma.compiler.IRContext import scala.language.{existentials, implicitConversions} import sigma.data.RType import special.wrappers.RTypeWrapSpec @@ -8,12 +8,12 @@ import special.wrappers.RTypeWrapSpec import scala.collection.compat.immutable.ArraySeq package impl { - import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, Scalan} + import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, IRContext} import sigma.reflection.{RClass, RMethod} // Abs ----------------------------------- trait WRTypesDefs extends Base with WRTypes { - self: Scalan => + self: IRContext => registerModule(WRTypesModule) @@ -117,4 +117,4 @@ object WRTypesModule extends ModuleInfo("wrappers.scalan", "WRTypes") { } } -trait WRTypesModule extends wrappers.scalan.impl.WRTypesDefs {self: Scalan =>} +trait WRTypesModule extends wrappers.scalan.impl.WRTypesDefs {self: IRContext =>} diff --git a/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala b/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala index 3c71796c47..33f39f2458 100644 --- a/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala +++ b/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala @@ -1,8 +1,8 @@ package wrappers.special { import scalan._ - import sigma.compiler.{Base, Scalan} + import sigma.compiler.{Base, IRContext} - trait WSpecialPredefs extends Base { self: Scalan => + trait WSpecialPredefs extends Base { self: IRContext => trait WSpecialPredef extends Def[WSpecialPredef]; trait WSpecialPredefCompanion { def some[A](x: Ref[A]): Ref[WOption[A]]; diff --git a/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala b/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala index 4bb7a13128..7ec5d9bb53 100644 --- a/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala +++ b/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala @@ -2,17 +2,16 @@ package wrappers.special import scala.language.{existentials, implicitConversions} import scalan._ -import sigma.compiler.Scalan -import special.wrappers.WrappersModule +import sigma.compiler.IRContext package impl { - import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, Scalan} + import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, IRContext} import sigma.data.Nullable import sigma.reflection.RClass // Abs ----------------------------------- trait WSpecialPredefsDefs extends Base with WSpecialPredefs { - self: Scalan => + self: IRContext => registerModule(WSpecialPredefsModule) @@ -68,4 +67,4 @@ object WSpecialPredefsModule extends ModuleInfo("wrappers.special", "WSpecialPre } } -trait WSpecialPredefsModule extends wrappers.special.impl.WSpecialPredefsDefs {self: Scalan =>} +trait WSpecialPredefsModule extends wrappers.special.impl.WSpecialPredefsDefs {self: IRContext =>} diff --git a/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala b/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala index 0c8bb83e56..b6abfc1391 100644 --- a/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala +++ b/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala @@ -20,9 +20,9 @@ import sigmastate.helpers.TestingHelpers._ import sigma.ast.syntax.ValueOps import sigma.{AnyValue, Evaluation, SigmaProp} import ErgoTree.ZeroHeader -import sigma.compiler.Scalan +import sigma.compiler.IRContext -case class TestContractSpec(testSuite: CompilerTestingCommons)(implicit val IR: Scalan) extends ContractSpec { +case class TestContractSpec(testSuite: CompilerTestingCommons)(implicit val IR: IRContext) extends ContractSpec { case class TestPropositionSpec(name: String, dslSpec: Proposition, scriptSpec: ErgoScript) extends PropositionSpec { lazy val ergoTree: ErgoTree = { diff --git a/sc/shared/src/test/scala/scalan/BaseLiftableTests.scala b/sc/shared/src/test/scala/scalan/BaseLiftableTests.scala index 120c15dfe6..ae1cc75e73 100644 --- a/sc/shared/src/test/scala/scalan/BaseLiftableTests.scala +++ b/sc/shared/src/test/scala/scalan/BaseLiftableTests.scala @@ -1,10 +1,10 @@ package scalan -import sigma.compiler.Scalan +import sigma.compiler.IRContext trait BaseLiftableTests { self: BaseCtxTests => - trait LiftableTestKit { scalan: Scalan => + trait LiftableTestKit { scalan: IRContext => import Liftables._ /** Check the MethodCall reified in f can be mapped to unlifted method which can be invoked.*/ diff --git a/sc/shared/src/test/scala/scalan/LibraryTests.scala b/sc/shared/src/test/scala/scalan/LibraryTests.scala index a6844070eb..ef7c9f8b07 100644 --- a/sc/shared/src/test/scala/scalan/LibraryTests.scala +++ b/sc/shared/src/test/scala/scalan/LibraryTests.scala @@ -1,9 +1,9 @@ package scalan -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.util.BenchmarkUtil.{measure, measureTime} -class Benchmark[T <: Scalan](createContext: => T) { +class Benchmark[T <: IRContext](createContext: => T) { val printDebugInfo: Boolean = false def run() = { diff --git a/sc/shared/src/test/scala/scalan/TestContexts.scala b/sc/shared/src/test/scala/scalan/TestContexts.scala index 39649b541a..8a0caae69f 100644 --- a/sc/shared/src/test/scala/scalan/TestContexts.scala +++ b/sc/shared/src/test/scala/scalan/TestContexts.scala @@ -1,12 +1,12 @@ package scalan -import sigma.compiler.{GraphIRReflection, Scalan} +import sigma.compiler.{GraphIRReflection, IRContext} import sigma.reflection.RMethod import sigma.{BaseNestedTests, BaseShouldTests, BaseTests, TestUtils} trait TestContexts extends TestUtils { - trait TestContextApi { scalan: Scalan => + trait TestContextApi { ctx: IRContext => def invokeAll: Boolean def isInvokeEnabled(d: Def[_], m: RMethod): Boolean def shouldUnpack(e: Elem[_]): Boolean @@ -20,7 +20,7 @@ trait TestContexts extends TestUtils { emitF(testName, Seq(() => s1) ++ s2.map((s: Ref[_]) => () => s): _*) } } - abstract class TestContext(val testName: String) extends Scalan with TestContextApi { + abstract class TestContext(val testName: String) extends IRContext with TestContextApi { def this() = this(currentTestNameAsFileName) override val invokeAll = true diff --git a/sc/shared/src/test/scala/scalan/TestLibrary.scala b/sc/shared/src/test/scala/scalan/TestLibrary.scala index 2c4c355cb8..91eb2d2e0b 100644 --- a/sc/shared/src/test/scala/scalan/TestLibrary.scala +++ b/sc/shared/src/test/scala/scalan/TestLibrary.scala @@ -1,8 +1,8 @@ package scalan -import sigma.compiler.{GraphIRReflection, Scalan} +import sigma.compiler.{GraphIRReflection, IRContext} -trait TestLibrary extends Scalan { +trait TestLibrary extends IRContext { import CollBuilder._ import SigmaDslBuilder._ val reflection = (GraphIRReflection) diff --git a/sc/shared/src/test/scala/sigma/CollsStagingTests.scala b/sc/shared/src/test/scala/sigma/CollsStagingTests.scala index f0d74f40e9..82e77937fe 100644 --- a/sc/shared/src/test/scala/sigma/CollsStagingTests.scala +++ b/sc/shared/src/test/scala/sigma/CollsStagingTests.scala @@ -3,7 +3,7 @@ package sigma import scala.language.reflectiveCalls import special.wrappers.WrappersTests import scalan._ -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.data.CollOverArrayBuilder class CollsStagingTests extends WrappersTests { @@ -42,7 +42,7 @@ class CollsStagingTests extends WrappersTests { } test("invokeUnlifted for Col") { - val ctx = new WrappersCtx with Scalan + val ctx = new WrappersCtx with IRContext import ctx._ import Coll._ import CollBuilder._ @@ -60,7 +60,7 @@ class CollsStagingTests extends WrappersTests { } test("invokeUnlifted for method of Ctor") { - val ctx = new WrappersCtx with Scalan + val ctx = new WrappersCtx with IRContext import ctx._ import Coll._ import CollBuilder._ diff --git a/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala b/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala index 90eefab5e0..5b951bec38 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala @@ -2,7 +2,7 @@ package sigma import org.scalatest.BeforeAndAfterAll import scalan.{BaseCtxTests, BaseLiftableTests} -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.data.TrivialProp import sigma.eval.Extensions.toAnyValue import sigmastate.eval._ @@ -10,7 +10,7 @@ import sigmastate.eval._ import scala.language.reflectiveCalls class SigmaDslStaginTests extends BaseCtxTests with ErgoScriptTestkit with BaseLiftableTests with BeforeAndAfterAll { - class Ctx extends TestContext with Scalan with LiftableTestKit { + class Ctx extends TestContext with IRContext with LiftableTestKit { } test("invokeUnlifted") { diff --git a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala index 4acb6e0f75..11dd9b7e68 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala @@ -31,7 +31,7 @@ import sigmastate.helpers.{CompilerTestingCommons, ErgoLikeContextTesting, ErgoL import sigmastate.interpreter.Interpreter.{ScriptEnv, VerificationResult} import sigmastate.interpreter._ import sigma.ast.Apply -import sigma.compiler.{CompiletimeIRContext, Scalan} +import sigma.compiler.{CompiletimeIRContext, IRContext} import sigma.eval.Extensions.SigmaBooleanOps import sigma.interpreter.{ContextExtension, ProverResult} import sigma.serialization.ValueSerializer @@ -55,7 +55,7 @@ class SigmaDslTesting extends AnyPropSpec override def contractEnv: ScriptEnv = Map() - def createIR(): Scalan = new TestingIRContext { + def createIR(): IRContext = new TestingIRContext { override val okMeasureOperationTime: Boolean = true } @@ -496,7 +496,7 @@ class SigmaDslTesting extends AnyPropSpec expectedExpr: Option[SValue], printExpectedExpr: Boolean = true, logScript: Boolean = LogScriptDefault - )(implicit IR: Scalan, val tA: RType[A], val tB: RType[B], + )(implicit IR: IRContext, val tA: RType[A], val tB: RType[B], override val evalSettings: EvalSettings) extends Feature[A, B] { implicit val cs = compilerSettingsInTests @@ -666,7 +666,7 @@ class SigmaDslTesting extends AnyPropSpec logScript: Boolean = LogScriptDefault, allowNewToSucceed: Boolean = false, override val allowDifferentErrors: Boolean = false - )(implicit IR: Scalan, override val evalSettings: EvalSettings, val tA: RType[A], val tB: RType[B]) + )(implicit IR: IRContext, override val evalSettings: EvalSettings, val tA: RType[A], val tB: RType[B]) extends Feature[A, B] { feature => implicit val cs = compilerSettingsInTests @@ -840,7 +840,7 @@ class SigmaDslTesting extends AnyPropSpec expectedExpr: Option[SValue], printExpectedExpr: Boolean = true, logScript: Boolean = LogScriptDefault - )(implicit IR: Scalan, override val evalSettings: EvalSettings, val tA: RType[A], val tB: RType[B]) + )(implicit IR: IRContext, override val evalSettings: EvalSettings, val tA: RType[A], val tB: RType[B]) extends Feature[A, B] { override def scalaFunc: A => B = { x => sys.error(s"Semantic Scala function is not defined for old implementation: $this") @@ -1013,7 +1013,7 @@ class SigmaDslTesting extends AnyPropSpec def existingFeature[A: RType, B: RType] (scalaFunc: A => B, script: String, expectedExpr: SValue = null) - (implicit IR: Scalan, evalSettings: EvalSettings): Feature[A, B] = { + (implicit IR: IRContext, evalSettings: EvalSettings): Feature[A, B] = { ExistingFeature( script, scalaFunc, Option(expectedExpr)) } @@ -1036,7 +1036,7 @@ class SigmaDslTesting extends AnyPropSpec expectedExpr: SValue = null, allowNewToSucceed: Boolean = false, allowDifferentErrors: Boolean = false) - (implicit IR: Scalan, evalSettings: EvalSettings): Feature[A, B] = { + (implicit IR: IRContext, evalSettings: EvalSettings): Feature[A, B] = { ChangedFeature(script, scalaFunc, scalaFuncNew, Option(expectedExpr), allowNewToSucceed = allowNewToSucceed, allowDifferentErrors = allowDifferentErrors) @@ -1053,7 +1053,7 @@ class SigmaDslTesting extends AnyPropSpec */ def newFeature[A: RType, B: RType] (scalaFunc: A => B, script: String, expectedExpr: SValue = null) - (implicit IR: Scalan, es: EvalSettings): Feature[A, B] = { + (implicit IR: IRContext, es: EvalSettings): Feature[A, B] = { NewFeature(script, scalaFunc, Option(expectedExpr)) } @@ -1151,7 +1151,7 @@ class SigmaDslTesting extends AnyPropSpec def benchmarkCases[A: Ordering : Arbitrary : ClassTag, B] (cases: Seq[A], f: Feature[A, B], nIters: Int, formatter: MeasureFormatter[A]) - (implicit IR: Scalan, evalSettings: EvalSettings): Seq[Long] = { + (implicit IR: IRContext, evalSettings: EvalSettings): Seq[Long] = { val fNew = f.newF implicit val tA = fNew.tA implicit val tB = fNew.tB diff --git a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala index 0d00fef070..0a94ca85bd 100644 --- a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala +++ b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala @@ -7,7 +7,7 @@ import sigma.ast.{ErgoTree, SType, TransformingSigmaBuilder, Value} import org.ergoplatform.ErgoAddressEncoder.TestnetNetworkPrefix import sigma.ast.syntax.{SValue, SigmaPropValue} import sigma.serialization.ValueSerializer -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.ast.syntax.ValueOps import sigmastate.helpers.{NegativeTesting, SigmaPPrint} @@ -44,21 +44,21 @@ trait CompilerTestsBase extends TestsBase with NegativeTesting { } /** Compile the given code to ErgoTree expression. */ - def compile(env: ScriptEnv, code: String)(implicit IR: Scalan): Value[SType] = { + def compile(env: ScriptEnv, code: String)(implicit IR: IRContext): Value[SType] = { val res = compiler.compile(env, code) checkCompilerResult(res) res.buildTree } /** Check the given [[CompilerResult]] meets equality and sanity requirements. */ - def checkCompilerResult[Ctx <: Scalan](res: CompilerResult[Ctx]): Unit = { + def checkCompilerResult[Ctx <: IRContext](res: CompilerResult[Ctx]): Unit = { checkSerializationRoundTrip(res.buildTree) } /** Compiles the given code and checks the resulting `prop` against `expected`. */ def compileAndCheck(env: ScriptEnv, code: String, expected: SValue) - (implicit IR: Scalan): (ErgoTree, SigmaPropValue) = { + (implicit IR: IRContext): (ErgoTree, SigmaPropValue) = { val prop = compile(env, code).asSigmaProp prop shouldBe expected val tree = mkTestErgoTree(prop) diff --git a/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala b/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala index 767c1dbd7b..42c2b8706b 100644 --- a/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala @@ -14,7 +14,7 @@ import sigmastate.interpreter.CErgoTreeEvaluator.DefaultEvalSettings import sigma.eval.EvalSettings.EvaluationMode import sigmastate.interpreter._ import sigma.ast.syntax.ValueOps -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.data.CBox import sigma.eval.EvalSettings import sigma.exceptions.InterpreterException @@ -33,7 +33,7 @@ class ScriptVersionSwitchSpecification extends SigmaDslTesting { costTracingEnabled = true // should always be enabled in tests (and false by default) ) - implicit def IR: Scalan = createIR() + implicit def IR: IRContext = createIR() lazy val b1 = CBox( new ErgoBox( @@ -52,7 +52,7 @@ class ScriptVersionSwitchSpecification extends SigmaDslTesting { ) /** Creates ErgoTree with segregated constants and also the given header flags. */ - def createErgoTree(header: HeaderType)(implicit IR: Scalan): ErgoTree = { + def createErgoTree(header: HeaderType)(implicit IR: IRContext): ErgoTree = { val code = s"""{ | val func = { (x: Coll[Box]) => x.filter({(b: Box) => b.value > 1 }) } diff --git a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala index dc9cccae9c..2d8b613fa3 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala @@ -14,7 +14,7 @@ import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeConte import sigmastate.interpreter.Interpreter.ScriptEnv import sigmastate.interpreter.CErgoTreeEvaluator import sigma.ast.syntax.ValueOps -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.interpreter.ContextExtension import sigmastate.lang.{CompilerResult, CompilerSettings, LangTests, SigmaCompiler} import sigma.serialization.ErgoTreeSerializer.DefaultSerializer @@ -27,8 +27,8 @@ import scala.util.{Success, Try} trait ErgoScriptTestkit extends ContractsTestkit with LangTests with ValidationSpecification with CompilerTestsBase { self: BaseCtxTests => - implicit lazy val IR: TestContext with Scalan = - new TestContext with Scalan + implicit lazy val IR: TestContext with IRContext = + new TestContext with IRContext import IR._ import BigInt._ diff --git a/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala b/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala index deb2110443..e8fc16e953 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala @@ -8,12 +8,12 @@ import scalan.BaseCtxTests import sigma.ast.syntax.ValueOps import sigmastate.lang.LangTests import sigma.ast.Apply -import sigma.compiler.Scalan +import sigma.compiler.IRContext class ErgoTreeBuildingTest extends BaseCtxTests with LangTests with ExampleContracts with ErgoScriptTestkit { - implicit override lazy val IR: TestContext with Scalan = new TestContext with Scalan { + implicit override lazy val IR: TestContext with IRContext = new TestContext with IRContext { beginPass(noConstPropagationPass) } diff --git a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala index b7bdf58452..9539bfb135 100644 --- a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala +++ b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala @@ -12,7 +12,7 @@ import sigma.data.{RType, SigmaBoolean} import sigma.validation.ValidationException import sigma.validation.ValidationRules.CheckSerializableTypeCode import sigma.ast.syntax.{SValue, SigmaPropValue} -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.eval.{CostDetails, EvalSettings, Extensions, GivenCost, TracedCost} import sigmastate.helpers.TestingHelpers._ import sigma.interpreter.ContextExtension.VarBinding @@ -30,7 +30,7 @@ trait CompilerTestingCommons extends TestingCommons with TestUtils with TestContexts with ValidationSpecification with CompilerTestsBase { - class TestingIRContext extends TestContext with Scalan + class TestingIRContext extends TestContext with IRContext case class CompiledFunc[A,B] (script: String, bindings: Seq[VarBinding], expr: SValue, compiledTree: SValue, func: A => (B, CostDetails)) @@ -91,7 +91,7 @@ trait CompilerTestingCommons extends TestingCommons def compileTestScript[A] (env: ScriptEnv, funcScript: String) (implicit tA: RType[A], - IR: Scalan, + IR: IRContext, compilerSettings: CompilerSettings): SValue = { val code = s"""{ @@ -129,7 +129,7 @@ trait CompilerTestingCommons extends TestingCommons def funcJitFromExpr[A: RType, B: RType] (funcScript: String, expr: SValue, bindings: VarBinding*) - (implicit IR: Scalan, + (implicit IR: IRContext, evalSettings: EvalSettings, compilerSettings: CompilerSettings): CompiledFunc[A, B] = { val f = (in: A) => { @@ -167,7 +167,7 @@ trait CompilerTestingCommons extends TestingCommons def funcJit[A: RType, B: RType] (funcScript: String, bindings: VarBinding*) - (implicit IR: Scalan, + (implicit IR: IRContext, evalSettings: EvalSettings, compilerSettings: CompilerSettings): CompiledFunc[A, B] = { val compiledTree = compileTestScript[A](Interpreter.emptyEnv, funcScript) diff --git a/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala b/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala index ae517a2ee6..bbdc4cbdce 100644 --- a/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala @@ -10,7 +10,7 @@ import sigma.util.Extensions.SigmaPropOps import sigma.validation.ValidationException import ErgoTree.EmptyConstants import ErgoTree.HeaderType -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.eval.Extensions.SigmaBooleanOps import sigmastate._ import sigmastate.helpers.CompilerTestingCommons @@ -25,7 +25,7 @@ class ErgoTreeSerializerSpecification extends SerializationSpecification beginPass(noConstPropagationPass) } - private def extractConstants(prop: SigmaPropValue)(implicit IR: Scalan): Seq[ErgoTree] = { + private def extractConstants(prop: SigmaPropValue)(implicit IR: IRContext): Seq[ErgoTree] = { import ErgoTree._ val env = Map[String, Any]() val res = compiler.compileTyped(env, prop) diff --git a/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala index 7e1b9a5491..7cc36f798d 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala @@ -18,7 +18,7 @@ import sigma.ast.syntax._ import sigma.Coll import sigma.ast.SAvlTree import sigma.ast.syntax.{GetVarByteArray, OptionValueOps} -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.data.{AvlTreeData, AvlTreeFlags, CSigmaProp, TrivialProp} import sigma.eval.SigmaDsl import sigma.interpreter.ProverResult @@ -30,8 +30,8 @@ class AVLTreeScriptsSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { suite => import org.ergoplatform.dsl.AvlTreeHelpers._ lazy val spec = TestContractSpec(suite)(new TestingIRContext) - lazy val prover = spec.ProvingParty("Alice") - private implicit lazy val IR: Scalan = spec.IR + lazy val prover = spec.ProvingParty("Alice") + private implicit lazy val IR: IRContext = spec.IR private val reg1 = ErgoBox.nonMandatoryRegisters(0) private val reg2 = ErgoBox.nonMandatoryRegisters(1) diff --git a/sc/shared/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala index 9c29c0301d..5405c32b58 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala @@ -7,14 +7,14 @@ import sigmastate.helpers.CompilerTestingCommons import org.ergoplatform.dsl.{ContractSpec, SigmaContractSyntax, TestContractSpec} import org.ergoplatform.ErgoBox import scorex.crypto.hash.Blake2b256 -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.data.{CSigmaProp, TrivialProp} class UsingContextPropertiesSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { suite => lazy val spec = TestContractSpec(suite)(new TestingIRContext) - lazy val prover = spec.ProvingParty("Alice") - private implicit lazy val IR: Scalan = spec.IR + lazy val prover = spec.ProvingParty("Alice") + private implicit lazy val IR: IRContext = spec.IR private val reg1 = ErgoBox.nonMandatoryRegisters(0) diff --git a/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala b/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala index 4cf39a8cb6..4fe0ecc136 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala @@ -17,7 +17,7 @@ import scorex.util._ import sigma.Colls import sigma.data.{AvlTreeData, AvlTreeFlags} import ErgoTree.ZeroHeader -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.eval.Extensions.SigmaBooleanOps import sigma.interpreter.ContextExtension import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} @@ -126,7 +126,7 @@ object BlockchainSimulationTestingCommons extends CompilerTestingCommons { } - case class ValidationState(state: BlockchainState, boxesReader: InMemoryErgoBoxReader, activatedVersion: Byte)(implicit IR: Scalan) { + case class ValidationState(state: BlockchainState, boxesReader: InMemoryErgoBoxReader, activatedVersion: Byte)(implicit IR: IRContext) { val validator = new ErgoTransactionValidator(activatedVersion) def applyBlock(block: FullBlock, maxCost: Int = MaxBlockCost): Try[ValidationState] = Try { @@ -166,7 +166,7 @@ object BlockchainSimulationTestingCommons extends CompilerTestingCommons { ErgoLikeContextTesting.dummyPubkey ) - def initialState(activatedVersion: Byte, block: FullBlock)(implicit IR: Scalan): ValidationState = { + def initialState(activatedVersion: Byte, block: FullBlock)(implicit IR: IRContext): ValidationState = { val keySize = 32 val prover = new BatchProver(keySize, None) diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala index 6a55338fbe..9b5c796af8 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala @@ -22,7 +22,7 @@ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingIn import sigmastate.interpreter.Interpreter.ScriptNameProp import sigmastate.interpreter.Interpreter import sigma.ast.syntax._ -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.eval.SigmaDsl import sigma.serialization.ErgoTreeSerializer import sigma.serialization.ErgoTreeSerializer.DefaultSerializer @@ -242,7 +242,7 @@ class IcoExample extends CompilerTestingCommons with CompilerCrossVersionProps with BeforeAndAfterAll { suite => // Not mixed with TestContext since it is not possible to call commpiler.compile outside tests if mixed - implicit lazy val IR: Scalan = new Scalan {} + implicit lazy val IR: IRContext = new IRContext {} lazy val spec = TestContractSpec(suite) lazy val project = new ErgoLikeTestProvingInterpreter() diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala index 5b40d111f3..db3f3bc46b 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala @@ -15,7 +15,7 @@ import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter.ScriptNameProp import sigma.serialization.ErgoTreeSerializer import sigma.ast.syntax._ -import sigma.compiler.Scalan +import sigma.compiler.IRContext import sigma.eval.SigmaDsl import scala.util.Random @@ -172,7 +172,7 @@ import scala.util.Random class LetsSpecification extends CompilerTestingCommons with CompilerCrossVersionProps { suite => // Not mixed with TestContext since it is not possible to call compiler.compile outside tests if mixed - implicit lazy val IR: Scalan = new TestingIRContext + implicit lazy val IR: IRContext = new TestingIRContext lazy val project = new ErgoLikeTestProvingInterpreter() From 9c9ddc521e3090cbdeefca62434ac29c84ade044 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 16 May 2024 10:56:11 +0100 Subject: [PATCH 52/65] refactor-ir-cake: `staged` package removed --- .../src/main/scala/sigma/compiler/{staged => }/AstGraphs.scala | 3 +-- sc/shared/src/main/scala/sigma/compiler/IRContext.scala | 1 - .../main/scala/sigma/compiler/{staged => }/ProgramGraphs.scala | 3 +-- .../main/scala/sigma/compiler/{staged => }/Transforming.scala | 3 +-- .../src/main/scala/sigma/compiler/primitives/Functions.scala | 3 +-- 5 files changed, 4 insertions(+), 9 deletions(-) rename sc/shared/src/main/scala/sigma/compiler/{staged => }/AstGraphs.scala (99%) rename sc/shared/src/main/scala/sigma/compiler/{staged => }/ProgramGraphs.scala (97%) rename sc/shared/src/main/scala/sigma/compiler/{staged => }/Transforming.scala (99%) diff --git a/sc/shared/src/main/scala/sigma/compiler/staged/AstGraphs.scala b/sc/shared/src/main/scala/sigma/compiler/AstGraphs.scala similarity index 99% rename from sc/shared/src/main/scala/sigma/compiler/staged/AstGraphs.scala rename to sc/shared/src/main/scala/sigma/compiler/AstGraphs.scala index 5ee20810fa..3d6acb40ff 100644 --- a/sc/shared/src/main/scala/sigma/compiler/staged/AstGraphs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/AstGraphs.scala @@ -1,7 +1,6 @@ -package sigma.compiler.staged +package sigma.compiler import debox.{cfor, Buffer => DBuffer, Map => DMap, Set => DSet} -import sigma.compiler.IRContext import sigma.data.emptyDBufferOfInt import scala.collection._ diff --git a/sc/shared/src/main/scala/sigma/compiler/IRContext.scala b/sc/shared/src/main/scala/sigma/compiler/IRContext.scala index 2f31d71589..3c204c440e 100644 --- a/sc/shared/src/main/scala/sigma/compiler/IRContext.scala +++ b/sc/shared/src/main/scala/sigma/compiler/IRContext.scala @@ -2,7 +2,6 @@ package sigma.compiler import scalan._ import sigma.compiler.primitives._ -import sigma.compiler.staged.Transforming import sigma.data.{Nullable, RType} import sigma.util.MemoizedFunc import sigma.{CollsModule, SigmaDslModule} diff --git a/sc/shared/src/main/scala/sigma/compiler/staged/ProgramGraphs.scala b/sc/shared/src/main/scala/sigma/compiler/ProgramGraphs.scala similarity index 97% rename from sc/shared/src/main/scala/sigma/compiler/staged/ProgramGraphs.scala rename to sc/shared/src/main/scala/sigma/compiler/ProgramGraphs.scala index 67220d1002..4ed6cab9b9 100644 --- a/sc/shared/src/main/scala/sigma/compiler/staged/ProgramGraphs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ProgramGraphs.scala @@ -1,7 +1,6 @@ -package sigma.compiler.staged +package sigma.compiler import debox.{cfor, Buffer => DBuffer} -import sigma.compiler.IRContext import sigma.data.{DFunc, Nullable} import sigma.util.GraphUtil diff --git a/sc/shared/src/main/scala/sigma/compiler/staged/Transforming.scala b/sc/shared/src/main/scala/sigma/compiler/Transforming.scala similarity index 99% rename from sc/shared/src/main/scala/sigma/compiler/staged/Transforming.scala rename to sc/shared/src/main/scala/sigma/compiler/Transforming.scala index 6d729d35d0..33504ee961 100644 --- a/sc/shared/src/main/scala/sigma/compiler/staged/Transforming.scala +++ b/sc/shared/src/main/scala/sigma/compiler/Transforming.scala @@ -1,7 +1,6 @@ -package sigma.compiler.staged +package sigma.compiler import debox.{cfor, Buffer => DBuffer} -import sigma.compiler.IRContext import sigma.data.{Lazy, Nullable} import sigma.reflection.RMethod diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala b/sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala index dce2578d4f..3498c4ae0c 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala +++ b/sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala @@ -1,8 +1,7 @@ package sigma.compiler.primitives import debox.{cfor, Buffer => DBuffer} -import sigma.compiler.staged.ProgramGraphs -import sigma.compiler.{Base, IRContext} +import sigma.compiler.{Base, IRContext, ProgramGraphs} import sigma.data.{Lazy, Nullable, emptyDBufferOfInt} import sigma.util.GraphUtil From 291f255c87f9d07ec036d2acd6c2ebcaf9eccc5a Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 16 May 2024 11:11:07 +0100 Subject: [PATCH 53/65] refactor-ir-cake: IR classes moved to sigma.compiler.ir package --- sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala | 2 +- sc/js/src/test/scala/scalan/Platform.scala | 2 +- sc/jvm/src/test/scala/scalan/Platform.scala | 2 +- .../src/test/scala/scalan/compilation/GraphVizExport.scala | 2 +- .../sigmastate/InterpreterReflectionGeneratorTests.scala | 2 +- sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala | 6 +++--- .../src/main/scala/org/ergoplatform/ErgoScriptPredef.scala | 2 +- .../src/main/scala/org/ergoplatform/dsl/ContractSpec.scala | 2 +- .../main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala | 2 +- .../src/main/scala/sigma/compiler/{ => ir}/AstGraphs.scala | 2 +- sc/shared/src/main/scala/sigma/compiler/{ => ir}/Base.scala | 2 +- .../main/scala/sigma/compiler/{ => ir}/DefRewriting.scala | 2 +- .../src/main/scala/sigma/compiler/{ => ir}/Entities.scala | 2 +- .../src/main/scala/sigma/compiler/{ => ir}/Exceptions.scala | 0 .../main/scala/sigma/compiler/{ => ir}/GraphBuilding.scala | 2 +- .../scala/sigma/compiler/{ => ir}/GraphIRReflection.scala | 4 ++-- .../src/main/scala/sigma/compiler/{ => ir}/IRContext.scala | 4 ++-- .../main/scala/sigma/compiler/{ => ir}/MethodCalls.scala | 2 +- .../src/main/scala/sigma/compiler/{ => ir}/ModuleInfo.scala | 2 +- .../src/main/scala/sigma/compiler/{ => ir}/Modules.scala | 2 +- .../main/scala/sigma/compiler/{ => ir}/MutableLazy.scala | 0 .../main/scala/sigma/compiler/{ => ir}/ProgramGraphs.scala | 2 +- .../main/scala/sigma/compiler/{ => ir}/Transforming.scala | 2 +- .../main/scala/sigma/compiler/{ => ir}/TreeBuilding.scala | 2 +- .../src/main/scala/sigma/compiler/{ => ir}/TypeDescs.scala | 2 +- .../main/scala/sigma/compiler/{ => ir}/core/Variance.scala | 0 .../main/scala/sigma/compiler/{ => ir}/meta/SSymName.scala | 0 .../scala/sigma/compiler/{ => ir}/primitives/Equal.scala | 4 ++-- .../sigma/compiler/{ => ir}/primitives/Functions.scala | 4 ++-- .../sigma/compiler/{ => ir}/primitives/IfThenElse.scala | 4 ++-- .../sigma/compiler/{ => ir}/primitives/LogicalOps.scala | 4 ++-- .../sigma/compiler/{ => ir}/primitives/NumericOps.scala | 4 ++-- .../sigma/compiler/{ => ir}/primitives/OrderingOps.scala | 4 ++-- .../scala/sigma/compiler/{ => ir}/primitives/Thunks.scala | 4 ++-- .../scala/sigma/compiler/{ => ir}/primitives/Tuples.scala | 4 ++-- .../scala/sigma/compiler/{ => ir}/primitives/UnBinOps.scala | 4 ++-- .../sigma/compiler/{ => ir}/primitives/UniversalOps.scala | 4 ++-- .../src/main/scala/sigmastate/lang/SigmaCompiler.scala | 2 +- .../main/scala/sigmastate/lang/SigmaTemplateCompiler.scala | 2 +- sc/shared/src/main/scala/special/collection/CollsUnit.scala | 2 +- .../src/main/scala/special/collection/impl/CollsImpl.scala | 4 ++-- sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala | 2 +- .../src/main/scala/special/sigma/impl/SigmaDslImpl.scala | 4 ++-- .../main/scala/special/sigma/wrappers/WrappersModule.scala | 2 +- .../src/main/scala/special/wrappers/WrappersModule.scala | 2 +- sc/shared/src/main/scala/wrappers/scala/WOptions.scala | 2 +- .../src/main/scala/wrappers/scala/impl/WOptionsImpl.scala | 4 ++-- sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala | 2 +- .../src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala | 4 ++-- .../src/main/scala/wrappers/special/WSpecialPredefs.scala | 2 +- .../scala/wrappers/special/impl/WSpecialPredefsImpl.scala | 4 ++-- .../test/scala/org/ergoplatform/dsl/TestContractSpec.scala | 2 +- sc/shared/src/test/scala/scalan/BaseLiftableTests.scala | 2 +- sc/shared/src/test/scala/scalan/LibraryTests.scala | 2 +- sc/shared/src/test/scala/scalan/TestContexts.scala | 2 +- sc/shared/src/test/scala/scalan/TestLibrary.scala | 2 +- sc/shared/src/test/scala/sigma/CollsStagingTests.scala | 2 +- sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala | 2 +- sc/shared/src/test/scala/sigma/SigmaDslTesting.scala | 2 +- sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala | 2 +- .../scala/sigmastate/ScriptVersionSwitchSpecification.scala | 2 +- .../src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala | 2 +- .../test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala | 2 +- .../scala/sigmastate/helpers/CompilerTestingCommons.scala | 2 +- .../serialization/ErgoTreeSerializerSpecification.scala | 2 +- .../scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala | 2 +- .../utxo/UsingContextPropertiesSpecification.scala | 2 +- .../blockchain/BlockchainSimulationTestingCommons.scala | 2 +- .../test/scala/sigmastate/utxo/examples/IcoExample.scala | 2 +- .../scala/sigmastate/utxo/examples/LetsSpecification.scala | 2 +- 70 files changed, 85 insertions(+), 85 deletions(-) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/AstGraphs.scala (99%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/Base.scala (99%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/DefRewriting.scala (99%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/Entities.scala (98%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/Exceptions.scala (100%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/GraphBuilding.scala (99%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/GraphIRReflection.scala (99%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/IRContext.scala (98%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/MethodCalls.scala (99%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/ModuleInfo.scala (94%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/Modules.scala (94%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/MutableLazy.scala (100%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/ProgramGraphs.scala (98%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/Transforming.scala (99%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/TreeBuilding.scala (99%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/TypeDescs.scala (99%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/core/Variance.scala (100%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/meta/SSymName.scala (100%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/primitives/Equal.scala (92%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/primitives/Functions.scala (99%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/primitives/IfThenElse.scala (96%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/primitives/LogicalOps.scala (96%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/primitives/NumericOps.scala (97%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/primitives/OrderingOps.scala (96%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/primitives/Thunks.scala (99%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/primitives/Tuples.scala (97%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/primitives/UnBinOps.scala (97%) rename sc/shared/src/main/scala/sigma/compiler/{ => ir}/primitives/UniversalOps.scala (98%) diff --git a/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala b/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala index 3dfd285e93..6264cd2f82 100644 --- a/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala +++ b/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala @@ -9,7 +9,7 @@ import scala.scalajs.js import scala.scalajs.js.annotation.JSExportTopLevel import sigma.js.Value import sigma.ast.ErgoTree.HeaderType -import sigma.compiler.CompiletimeIRContext +import sigma.compiler.ir.CompiletimeIRContext import sigma.ast.syntax.ValueOps diff --git a/sc/js/src/test/scala/scalan/Platform.scala b/sc/js/src/test/scala/scalan/Platform.scala index afb5ff72c1..697453a5d2 100644 --- a/sc/js/src/test/scala/scalan/Platform.scala +++ b/sc/js/src/test/scala/scalan/Platform.scala @@ -1,6 +1,6 @@ package scalan -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import scala.annotation.unused diff --git a/sc/jvm/src/test/scala/scalan/Platform.scala b/sc/jvm/src/test/scala/scalan/Platform.scala index 3a194a7d50..7c9d48b135 100644 --- a/sc/jvm/src/test/scala/scalan/Platform.scala +++ b/sc/jvm/src/test/scala/scalan/Platform.scala @@ -3,7 +3,7 @@ package scalan import scalan.compilation.GraphVizExport import sigma.util.FileUtil import org.scalatest.Assertions -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext object Platform { /** Output graph given by symbols in `sfs` to files. diff --git a/sc/jvm/src/test/scala/scalan/compilation/GraphVizExport.scala b/sc/jvm/src/test/scala/scalan/compilation/GraphVizExport.scala index 1072de00e2..020e066080 100644 --- a/sc/jvm/src/test/scala/scalan/compilation/GraphVizExport.scala +++ b/sc/jvm/src/test/scala/scalan/compilation/GraphVizExport.scala @@ -3,7 +3,7 @@ package scalan.compilation import java.awt.Desktop import java.io.{File, PrintWriter} import scalan.core.ScalaNameUtil -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.util.{FileUtil, ProcessUtil, StringUtil} import scala.annotation.unused diff --git a/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala b/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala index 7fc0e454ed..c10c0123b0 100644 --- a/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala +++ b/sc/jvm/src/test/scala/sigmastate/InterpreterReflectionGeneratorTests.scala @@ -2,7 +2,7 @@ package sigmastate import org.scalatest.matchers.should.Matchers import org.scalatest.propspec.AnyPropSpec -import sigma.compiler.{IRContext, TypeDescs} +import sigma.compiler.ir.{IRContext, TypeDescs} import sigma.reflection.ReflectionData.registerClassEntry import sigma.reflection.SRConstructor diff --git a/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala b/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala index 963e1c56d1..c102f4eda8 100644 --- a/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala +++ b/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala @@ -1,6 +1,6 @@ package sigmastate -import sigma.compiler.{Base, TypeDescs} +import sigma.compiler.ir.{Base, TypeDescs} import sigma.reflection._ import scala.annotation.unused import scala.collection.mutable @@ -30,7 +30,7 @@ object ReflectionGenerator { } val knownPackages = Array( - "sigma.compiler.primitives.", + "sigma.compiler.ir.primitives.", "sigma.", "sigma.", "special.wrappers.", @@ -40,7 +40,7 @@ object ReflectionGenerator { "sigmastate.utxo.", "sigmastate.", "wrappers.scala.", - "sigma.compiler.", + "sigma.compiler.ir.", "scala.collection.", "scala." ) diff --git a/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala b/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala index 1b84e7f0d6..60b82a54a2 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala @@ -6,7 +6,7 @@ import sigma.ast.SType import sigma.ast.syntax.SigmaPropValue import sigma.ast.Value import sigma.ast.syntax.ValueOps -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext object ErgoScriptPredef { import sigmastate.interpreter.Interpreter._ diff --git a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala index 128351efea..ffe7239c62 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/dsl/ContractSpec.scala @@ -9,7 +9,7 @@ import sigma.{Coll, SigmaDslBuilder, SigmaProp} import scala.util.Try import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition, Token} import sigma.ast.{ErgoTree, EvaluatedValue, SType} -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import scala.language.implicitConversions diff --git a/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala b/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala index 5929299a3b..2511bef439 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/dsl/ErgoContractSpec.scala @@ -3,7 +3,7 @@ package org.ergoplatform.dsl import sigma.Coll import org.ergoplatform.dsl.ContractSyntax.{ErgoScript, Proposition, Token} import org.ergoplatform.ErgoBox.{BoxId, NonMandatoryRegisterId, TokenId} -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.interpreter.CostedProverResult class ErgoContractSpec(implicit val IR: IRContext) extends ContractSpec { diff --git a/sc/shared/src/main/scala/sigma/compiler/AstGraphs.scala b/sc/shared/src/main/scala/sigma/compiler/ir/AstGraphs.scala similarity index 99% rename from sc/shared/src/main/scala/sigma/compiler/AstGraphs.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/AstGraphs.scala index 3d6acb40ff..7f798dc8f3 100644 --- a/sc/shared/src/main/scala/sigma/compiler/AstGraphs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/AstGraphs.scala @@ -1,4 +1,4 @@ -package sigma.compiler +package sigma.compiler.ir import debox.{cfor, Buffer => DBuffer, Map => DMap, Set => DSet} import sigma.data.emptyDBufferOfInt diff --git a/sc/shared/src/main/scala/sigma/compiler/Base.scala b/sc/shared/src/main/scala/sigma/compiler/ir/Base.scala similarity index 99% rename from sc/shared/src/main/scala/sigma/compiler/Base.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/Base.scala index 3d6b763c5a..939d364953 100644 --- a/sc/shared/src/main/scala/sigma/compiler/Base.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/Base.scala @@ -1,4 +1,4 @@ -package sigma.compiler +package sigma.compiler.ir import debox.{cfor, Buffer => DBuffer} import scalan.MutableLazy diff --git a/sc/shared/src/main/scala/sigma/compiler/DefRewriting.scala b/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala similarity index 99% rename from sc/shared/src/main/scala/sigma/compiler/DefRewriting.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala index 0cc86c0644..fe289cafe0 100644 --- a/sc/shared/src/main/scala/sigma/compiler/DefRewriting.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala @@ -1,4 +1,4 @@ -package sigma.compiler +package sigma.compiler.ir import scalan.DelayInvokeException import sigma.data.ExactNumeric diff --git a/sc/shared/src/main/scala/sigma/compiler/Entities.scala b/sc/shared/src/main/scala/sigma/compiler/ir/Entities.scala similarity index 98% rename from sc/shared/src/main/scala/sigma/compiler/Entities.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/Entities.scala index bfda787fc3..dfaeff207c 100644 --- a/sc/shared/src/main/scala/sigma/compiler/Entities.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/Entities.scala @@ -1,4 +1,4 @@ -package sigma.compiler +package sigma.compiler.ir /** A slice in the Scalan cake with base classes for various descriptors. */ trait Entities extends TypeDescs { self: IRContext => diff --git a/sc/shared/src/main/scala/sigma/compiler/Exceptions.scala b/sc/shared/src/main/scala/sigma/compiler/ir/Exceptions.scala similarity index 100% rename from sc/shared/src/main/scala/sigma/compiler/Exceptions.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/Exceptions.scala diff --git a/sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala b/sc/shared/src/main/scala/sigma/compiler/ir/GraphBuilding.scala similarity index 99% rename from sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/GraphBuilding.scala index bbc1361dfe..71029b4628 100644 --- a/sc/shared/src/main/scala/sigma/compiler/GraphBuilding.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/GraphBuilding.scala @@ -1,4 +1,4 @@ -package sigma.compiler +package sigma.compiler.ir import org.ergoplatform._ import scalan.MutableLazy diff --git a/sc/shared/src/main/scala/sigma/compiler/GraphIRReflection.scala b/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala similarity index 99% rename from sc/shared/src/main/scala/sigma/compiler/GraphIRReflection.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala index 59f1116569..32d95354c3 100644 --- a/sc/shared/src/main/scala/sigma/compiler/GraphIRReflection.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala @@ -1,6 +1,6 @@ -package sigma.compiler +package sigma.compiler.ir -import sigma.compiler.primitives.Thunks +import sigma.compiler.ir.primitives.Thunks import sigma.{Colls, SigmaDsl} import sigma.data.RType import sigma.reflection.ReflectionData.registerClassEntry diff --git a/sc/shared/src/main/scala/sigma/compiler/IRContext.scala b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala similarity index 98% rename from sc/shared/src/main/scala/sigma/compiler/IRContext.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala index 3c204c440e..7fae587ac4 100644 --- a/sc/shared/src/main/scala/sigma/compiler/IRContext.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala @@ -1,7 +1,7 @@ -package sigma.compiler +package sigma.compiler.ir import scalan._ -import sigma.compiler.primitives._ +import sigma.compiler.ir.primitives._ import sigma.data.{Nullable, RType} import sigma.util.MemoizedFunc import sigma.{CollsModule, SigmaDslModule} diff --git a/sc/shared/src/main/scala/sigma/compiler/MethodCalls.scala b/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala similarity index 99% rename from sc/shared/src/main/scala/sigma/compiler/MethodCalls.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala index 4b534930d8..de96900c62 100644 --- a/sc/shared/src/main/scala/sigma/compiler/MethodCalls.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala @@ -1,4 +1,4 @@ -package sigma.compiler +package sigma.compiler.ir import debox.{cfor, Buffer => DBuffer} import scalan.DelayInvokeException diff --git a/sc/shared/src/main/scala/sigma/compiler/ModuleInfo.scala b/sc/shared/src/main/scala/sigma/compiler/ir/ModuleInfo.scala similarity index 94% rename from sc/shared/src/main/scala/sigma/compiler/ModuleInfo.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/ModuleInfo.scala index 8c2030b1c7..ccd71ffdc0 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ModuleInfo.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/ModuleInfo.scala @@ -1,4 +1,4 @@ -package sigma.compiler +package sigma.compiler.ir import scalan.meta.SSymName diff --git a/sc/shared/src/main/scala/sigma/compiler/Modules.scala b/sc/shared/src/main/scala/sigma/compiler/ir/Modules.scala similarity index 94% rename from sc/shared/src/main/scala/sigma/compiler/Modules.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/Modules.scala index 527dcd6eb8..cafee1ef84 100644 --- a/sc/shared/src/main/scala/sigma/compiler/Modules.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/Modules.scala @@ -1,4 +1,4 @@ -package sigma.compiler +package sigma.compiler.ir trait Modules extends Base { self: IRContext => diff --git a/sc/shared/src/main/scala/sigma/compiler/MutableLazy.scala b/sc/shared/src/main/scala/sigma/compiler/ir/MutableLazy.scala similarity index 100% rename from sc/shared/src/main/scala/sigma/compiler/MutableLazy.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/MutableLazy.scala diff --git a/sc/shared/src/main/scala/sigma/compiler/ProgramGraphs.scala b/sc/shared/src/main/scala/sigma/compiler/ir/ProgramGraphs.scala similarity index 98% rename from sc/shared/src/main/scala/sigma/compiler/ProgramGraphs.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/ProgramGraphs.scala index 4ed6cab9b9..cd0384c996 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ProgramGraphs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/ProgramGraphs.scala @@ -1,4 +1,4 @@ -package sigma.compiler +package sigma.compiler.ir import debox.{cfor, Buffer => DBuffer} import sigma.data.{DFunc, Nullable} diff --git a/sc/shared/src/main/scala/sigma/compiler/Transforming.scala b/sc/shared/src/main/scala/sigma/compiler/ir/Transforming.scala similarity index 99% rename from sc/shared/src/main/scala/sigma/compiler/Transforming.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/Transforming.scala index 33504ee961..2412c756f1 100644 --- a/sc/shared/src/main/scala/sigma/compiler/Transforming.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/Transforming.scala @@ -1,4 +1,4 @@ -package sigma.compiler +package sigma.compiler.ir import debox.{cfor, Buffer => DBuffer} import sigma.data.{Lazy, Nullable} diff --git a/sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala b/sc/shared/src/main/scala/sigma/compiler/ir/TreeBuilding.scala similarity index 99% rename from sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/TreeBuilding.scala index de6437645f..4c54ef711b 100644 --- a/sc/shared/src/main/scala/sigma/compiler/TreeBuilding.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/TreeBuilding.scala @@ -1,4 +1,4 @@ -package sigma.compiler +package sigma.compiler.ir import org.ergoplatform._ import sigma.ast._ diff --git a/sc/shared/src/main/scala/sigma/compiler/TypeDescs.scala b/sc/shared/src/main/scala/sigma/compiler/ir/TypeDescs.scala similarity index 99% rename from sc/shared/src/main/scala/sigma/compiler/TypeDescs.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/TypeDescs.scala index 6e2de8d952..4346d117ea 100644 --- a/sc/shared/src/main/scala/sigma/compiler/TypeDescs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/TypeDescs.scala @@ -1,4 +1,4 @@ -package sigma.compiler +package sigma.compiler.ir import debox.cfor import scalan.core.{Contravariant, Covariant, Variance} diff --git a/sc/shared/src/main/scala/sigma/compiler/core/Variance.scala b/sc/shared/src/main/scala/sigma/compiler/ir/core/Variance.scala similarity index 100% rename from sc/shared/src/main/scala/sigma/compiler/core/Variance.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/core/Variance.scala diff --git a/sc/shared/src/main/scala/sigma/compiler/meta/SSymName.scala b/sc/shared/src/main/scala/sigma/compiler/ir/meta/SSymName.scala similarity index 100% rename from sc/shared/src/main/scala/sigma/compiler/meta/SSymName.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/meta/SSymName.scala diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/Equal.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Equal.scala similarity index 92% rename from sc/shared/src/main/scala/sigma/compiler/primitives/Equal.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/primitives/Equal.scala index fc6e67fbfd..a778465e4c 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/Equal.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Equal.scala @@ -1,6 +1,6 @@ -package sigma.compiler.primitives +package sigma.compiler.ir.primitives -import sigma.compiler.{Base, IRContext} +import sigma.compiler.ir.{Base, IRContext} import scala.annotation.unused diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Functions.scala similarity index 99% rename from sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/primitives/Functions.scala index 3498c4ae0c..04d3283c01 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/Functions.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Functions.scala @@ -1,7 +1,7 @@ -package sigma.compiler.primitives +package sigma.compiler.ir.primitives import debox.{cfor, Buffer => DBuffer} -import sigma.compiler.{Base, IRContext, ProgramGraphs} +import sigma.compiler.ir.{Base, IRContext, ProgramGraphs} import sigma.data.{Lazy, Nullable, emptyDBufferOfInt} import sigma.util.GraphUtil diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/IfThenElse.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/IfThenElse.scala similarity index 96% rename from sc/shared/src/main/scala/sigma/compiler/primitives/IfThenElse.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/primitives/IfThenElse.scala index e09036fcaf..aee57ff1f9 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/IfThenElse.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/IfThenElse.scala @@ -1,6 +1,6 @@ -package sigma.compiler.primitives +package sigma.compiler.ir.primitives -import sigma.compiler.{Base, IRContext} +import sigma.compiler.ir.{Base, IRContext} trait IfThenElse extends Base { self: IRContext => diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/LogicalOps.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/LogicalOps.scala similarity index 96% rename from sc/shared/src/main/scala/sigma/compiler/primitives/LogicalOps.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/primitives/LogicalOps.scala index faf186bf04..6420e46f5c 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/LogicalOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/LogicalOps.scala @@ -1,6 +1,6 @@ -package sigma.compiler.primitives +package sigma.compiler.ir.primitives -import sigma.compiler.{Base, IRContext} +import sigma.compiler.ir.{Base, IRContext} /** Slice in Scala cake with definitions of logical operations. */ trait LogicalOps extends Base { self: IRContext => diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/NumericOps.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/NumericOps.scala similarity index 97% rename from sc/shared/src/main/scala/sigma/compiler/primitives/NumericOps.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/primitives/NumericOps.scala index de3f2e6fed..d22140870a 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/NumericOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/NumericOps.scala @@ -1,6 +1,6 @@ -package sigma.compiler.primitives +package sigma.compiler.ir.primitives -import sigma.compiler.{Base, IRContext} +import sigma.compiler.ir.{Base, IRContext} import sigma.data.{ExactIntegral, ExactNumeric} /** Slice in Scala cake with definitions of numeric operations. */ diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/OrderingOps.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/OrderingOps.scala similarity index 96% rename from sc/shared/src/main/scala/sigma/compiler/primitives/OrderingOps.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/primitives/OrderingOps.scala index 31d4c88365..ea2b9f5a34 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/OrderingOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/OrderingOps.scala @@ -1,6 +1,6 @@ -package sigma.compiler.primitives +package sigma.compiler.ir.primitives -import sigma.compiler.{Base, IRContext} +import sigma.compiler.ir.{Base, IRContext} import sigma.data.ExactOrdering import scala.language.implicitConversions diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/Thunks.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Thunks.scala similarity index 99% rename from sc/shared/src/main/scala/sigma/compiler/primitives/Thunks.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/primitives/Thunks.scala index 2b5c97fcba..8674918907 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/Thunks.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Thunks.scala @@ -1,8 +1,8 @@ -package sigma.compiler.primitives +package sigma.compiler.ir.primitives import debox.{cfor, Buffer => DBuffer, Set => DSet} import scalan.core.Covariant -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.data.{AVHashMap, DFunc, Lazy, Nullable, RType} import sigma.reflection.RClass import sigma.util.GraphUtil diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/Tuples.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Tuples.scala similarity index 97% rename from sc/shared/src/main/scala/sigma/compiler/primitives/Tuples.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/primitives/Tuples.scala index d0455d0106..b6b9861ac7 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/Tuples.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Tuples.scala @@ -2,9 +2,9 @@ * Author: Alexander Slesarenko * Date: 7/25/12 */ -package sigma.compiler.primitives +package sigma.compiler.ir.primitives -import sigma.compiler.{Base, IRContext} +import sigma.compiler.ir.{Base, IRContext} import sigma.data.AVHashMap import scala.language.implicitConversions diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/UnBinOps.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/UnBinOps.scala similarity index 97% rename from sc/shared/src/main/scala/sigma/compiler/primitives/UnBinOps.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/primitives/UnBinOps.scala index 4bb9b6b9ab..a3a92e2f10 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/UnBinOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/UnBinOps.scala @@ -1,6 +1,6 @@ -package sigma.compiler.primitives +package sigma.compiler.ir.primitives -import sigma.compiler.{Base, IRContext} +import sigma.compiler.ir.{Base, IRContext} trait UnBinOps extends Base { self: IRContext => diff --git a/sc/shared/src/main/scala/sigma/compiler/primitives/UniversalOps.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/UniversalOps.scala similarity index 98% rename from sc/shared/src/main/scala/sigma/compiler/primitives/UniversalOps.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/primitives/UniversalOps.scala index b83e152b4f..a5852647ac 100644 --- a/sc/shared/src/main/scala/sigma/compiler/primitives/UniversalOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/UniversalOps.scala @@ -1,6 +1,6 @@ -package sigma.compiler.primitives +package sigma.compiler.ir.primitives -import sigma.compiler.{Base, IRContext} +import sigma.compiler.ir.{Base, IRContext} trait UniversalOps extends Base { self: IRContext => case class HashCode[A]() extends UnOp[A, Int]("hashCode") { diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala index f12a385973..0a2bb9a355 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala @@ -12,7 +12,7 @@ import sigmastate.lang.parsers.ParserException import sigma.ast._ import sigma.ast.syntax.SValue import SCollectionMethods.{ExistsMethod, ForallMethod, MapMethod} -import sigma.compiler.{GraphIRReflection, IRContext} +import sigma.compiler.ir.{GraphIRReflection, IRContext} import sigmastate.InterpreterReflection /** diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala b/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala index 8c8a84d29e..09d27b2489 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala +++ b/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala @@ -4,7 +4,7 @@ import fastparse.Parsed import org.ergoplatform.sdk.{ContractTemplate, Parameter} import sigma.ast.SourceContext import sigma.ast.syntax.SValue -import sigma.compiler.CompiletimeIRContext +import sigma.compiler.ir.CompiletimeIRContext import sigmastate.lang.parsers.ParserException /** Compiler which compiles Ergo contract templates into a [[ContractTemplate]]. */ diff --git a/sc/shared/src/main/scala/special/collection/CollsUnit.scala b/sc/shared/src/main/scala/special/collection/CollsUnit.scala index 53bf6f0530..f000b61ed6 100644 --- a/sc/shared/src/main/scala/special/collection/CollsUnit.scala +++ b/sc/shared/src/main/scala/special/collection/CollsUnit.scala @@ -1,5 +1,5 @@ package sigma { - import sigma.compiler.{Base, IRContext} + import sigma.compiler.ir.{Base, IRContext} /** Staged version of collection interfaces which is used in graph-based IR to represent * methods of Coll and CollBuilder. diff --git a/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala b/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala index a14b2eb3b4..09c888bf49 100644 --- a/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala +++ b/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala @@ -2,12 +2,12 @@ package sigma import scala.language.{existentials, implicitConversions} import scalan._ -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import scala.collection.compat.immutable.ArraySeq package impl { - import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, IRContext} + import sigma.compiler.ir.{Base, GraphIRReflection, ModuleInfo, IRContext} import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} diff --git a/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala b/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala index a6fb60870c..46c93558af 100644 --- a/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala +++ b/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala @@ -1,6 +1,6 @@ package sigma { import scalan._ - import sigma.compiler.{Base, IRContext} + import sigma.compiler.ir.{Base, IRContext} trait SigmaDsl extends Base { self: IRContext => trait BigInt extends Def[BigInt] { diff --git a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala index a76ddb47d4..6b26a2b100 100644 --- a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala +++ b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala @@ -2,12 +2,12 @@ package sigma import scala.language.{existentials, implicitConversions} import scalan._ -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import scala.collection.compat.immutable.ArraySeq package impl { - import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, IRContext} + import sigma.compiler.ir.{Base, GraphIRReflection, ModuleInfo, IRContext} import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} diff --git a/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala b/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala index 6620d9db8f..7d0bcc6b59 100644 --- a/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala +++ b/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala @@ -1,6 +1,6 @@ package sigma.wrappers -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext trait WrappersModule extends special.wrappers.WrappersModule { self: IRContext => } diff --git a/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala b/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala index 0d67f6147a..0003fd6464 100644 --- a/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala +++ b/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala @@ -1,6 +1,6 @@ package special.wrappers -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import wrappers.scala.WOptionsModule import wrappers.scalan.WRTypesModule import wrappers.special.WSpecialPredefsModule diff --git a/sc/shared/src/main/scala/wrappers/scala/WOptions.scala b/sc/shared/src/main/scala/wrappers/scala/WOptions.scala index 4f41d0d025..b59692ebd1 100644 --- a/sc/shared/src/main/scala/wrappers/scala/WOptions.scala +++ b/sc/shared/src/main/scala/wrappers/scala/WOptions.scala @@ -1,6 +1,6 @@ package wrappers.scala { import scalan._ - import sigma.compiler.{Base, IRContext} + import sigma.compiler.ir.{Base, IRContext} import special.wrappers.WrappersModule trait WOptions extends Base { self: IRContext => diff --git a/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala b/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala index 915a271de9..8bb0b1e5e1 100644 --- a/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala +++ b/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala @@ -2,14 +2,14 @@ package wrappers.scala import scala.language.{existentials, implicitConversions} import scalan._ -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import special.wrappers.WrappersModule import special.wrappers.OptionWrapSpec import scala.collection.compat.immutable.ArraySeq package impl { - import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, IRContext} + import sigma.compiler.ir.{Base, GraphIRReflection, ModuleInfo, IRContext} import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} diff --git a/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala b/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala index 99f87242df..41242c4ce3 100644 --- a/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala +++ b/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala @@ -1,6 +1,6 @@ package wrappers.scalan { import scalan._ - import sigma.compiler.{Base, IRContext} + import sigma.compiler.ir.{Base, IRContext} trait WRTypes extends Base { self: IRContext => diff --git a/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala b/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala index 55923c757b..0e8b32230a 100644 --- a/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala +++ b/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala @@ -1,6 +1,6 @@ package wrappers.scalan -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import scala.language.{existentials, implicitConversions} import sigma.data.RType import special.wrappers.RTypeWrapSpec @@ -8,7 +8,7 @@ import special.wrappers.RTypeWrapSpec import scala.collection.compat.immutable.ArraySeq package impl { - import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, IRContext} + import sigma.compiler.ir.{Base, GraphIRReflection, ModuleInfo, IRContext} import sigma.reflection.{RClass, RMethod} // Abs ----------------------------------- diff --git a/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala b/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala index 33f39f2458..45065b324b 100644 --- a/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala +++ b/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala @@ -1,6 +1,6 @@ package wrappers.special { import scalan._ - import sigma.compiler.{Base, IRContext} + import sigma.compiler.ir.{Base, IRContext} trait WSpecialPredefs extends Base { self: IRContext => trait WSpecialPredef extends Def[WSpecialPredef]; diff --git a/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala b/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala index 7ec5d9bb53..6e763850bd 100644 --- a/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala +++ b/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala @@ -2,10 +2,10 @@ package wrappers.special import scala.language.{existentials, implicitConversions} import scalan._ -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext package impl { - import sigma.compiler.{Base, GraphIRReflection, ModuleInfo, IRContext} + import sigma.compiler.ir.{Base, GraphIRReflection, ModuleInfo, IRContext} import sigma.data.Nullable import sigma.reflection.RClass diff --git a/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala b/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala index b6abfc1391..0216f71f21 100644 --- a/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala +++ b/sc/shared/src/test/scala/org/ergoplatform/dsl/TestContractSpec.scala @@ -20,7 +20,7 @@ import sigmastate.helpers.TestingHelpers._ import sigma.ast.syntax.ValueOps import sigma.{AnyValue, Evaluation, SigmaProp} import ErgoTree.ZeroHeader -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext case class TestContractSpec(testSuite: CompilerTestingCommons)(implicit val IR: IRContext) extends ContractSpec { diff --git a/sc/shared/src/test/scala/scalan/BaseLiftableTests.scala b/sc/shared/src/test/scala/scalan/BaseLiftableTests.scala index ae1cc75e73..a9da1792ec 100644 --- a/sc/shared/src/test/scala/scalan/BaseLiftableTests.scala +++ b/sc/shared/src/test/scala/scalan/BaseLiftableTests.scala @@ -1,6 +1,6 @@ package scalan -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext trait BaseLiftableTests { self: BaseCtxTests => diff --git a/sc/shared/src/test/scala/scalan/LibraryTests.scala b/sc/shared/src/test/scala/scalan/LibraryTests.scala index ef7c9f8b07..b21bd2daf1 100644 --- a/sc/shared/src/test/scala/scalan/LibraryTests.scala +++ b/sc/shared/src/test/scala/scalan/LibraryTests.scala @@ -1,6 +1,6 @@ package scalan -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.util.BenchmarkUtil.{measure, measureTime} class Benchmark[T <: IRContext](createContext: => T) { diff --git a/sc/shared/src/test/scala/scalan/TestContexts.scala b/sc/shared/src/test/scala/scalan/TestContexts.scala index 8a0caae69f..82a6d6b21c 100644 --- a/sc/shared/src/test/scala/scalan/TestContexts.scala +++ b/sc/shared/src/test/scala/scalan/TestContexts.scala @@ -1,6 +1,6 @@ package scalan -import sigma.compiler.{GraphIRReflection, IRContext} +import sigma.compiler.ir.{GraphIRReflection, IRContext} import sigma.reflection.RMethod import sigma.{BaseNestedTests, BaseShouldTests, BaseTests, TestUtils} diff --git a/sc/shared/src/test/scala/scalan/TestLibrary.scala b/sc/shared/src/test/scala/scalan/TestLibrary.scala index 91eb2d2e0b..cb3608d4c3 100644 --- a/sc/shared/src/test/scala/scalan/TestLibrary.scala +++ b/sc/shared/src/test/scala/scalan/TestLibrary.scala @@ -1,6 +1,6 @@ package scalan -import sigma.compiler.{GraphIRReflection, IRContext} +import sigma.compiler.ir.{GraphIRReflection, IRContext} trait TestLibrary extends IRContext { import CollBuilder._ diff --git a/sc/shared/src/test/scala/sigma/CollsStagingTests.scala b/sc/shared/src/test/scala/sigma/CollsStagingTests.scala index 82e77937fe..b26c7d4119 100644 --- a/sc/shared/src/test/scala/sigma/CollsStagingTests.scala +++ b/sc/shared/src/test/scala/sigma/CollsStagingTests.scala @@ -3,7 +3,7 @@ package sigma import scala.language.reflectiveCalls import special.wrappers.WrappersTests import scalan._ -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.data.CollOverArrayBuilder class CollsStagingTests extends WrappersTests { diff --git a/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala b/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala index 5b951bec38..bcd4b21129 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslStaginTests.scala @@ -2,7 +2,7 @@ package sigma import org.scalatest.BeforeAndAfterAll import scalan.{BaseCtxTests, BaseLiftableTests} -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.data.TrivialProp import sigma.eval.Extensions.toAnyValue import sigmastate.eval._ diff --git a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala index 11dd9b7e68..31e873699b 100644 --- a/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala +++ b/sc/shared/src/test/scala/sigma/SigmaDslTesting.scala @@ -31,7 +31,7 @@ import sigmastate.helpers.{CompilerTestingCommons, ErgoLikeContextTesting, ErgoL import sigmastate.interpreter.Interpreter.{ScriptEnv, VerificationResult} import sigmastate.interpreter._ import sigma.ast.Apply -import sigma.compiler.{CompiletimeIRContext, IRContext} +import sigma.compiler.ir.{CompiletimeIRContext, IRContext} import sigma.eval.Extensions.SigmaBooleanOps import sigma.interpreter.{ContextExtension, ProverResult} import sigma.serialization.ValueSerializer diff --git a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala index 0a94ca85bd..19c0a4b134 100644 --- a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala +++ b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala @@ -7,7 +7,7 @@ import sigma.ast.{ErgoTree, SType, TransformingSigmaBuilder, Value} import org.ergoplatform.ErgoAddressEncoder.TestnetNetworkPrefix import sigma.ast.syntax.{SValue, SigmaPropValue} import sigma.serialization.ValueSerializer -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.ast.syntax.ValueOps import sigmastate.helpers.{NegativeTesting, SigmaPPrint} diff --git a/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala b/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala index 42c2b8706b..ecc1dace81 100644 --- a/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/ScriptVersionSwitchSpecification.scala @@ -14,7 +14,7 @@ import sigmastate.interpreter.CErgoTreeEvaluator.DefaultEvalSettings import sigma.eval.EvalSettings.EvaluationMode import sigmastate.interpreter._ import sigma.ast.syntax.ValueOps -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.data.CBox import sigma.eval.EvalSettings import sigma.exceptions.InterpreterException diff --git a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala index 2d8b613fa3..90d9cb8b6d 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala @@ -14,7 +14,7 @@ import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeConte import sigmastate.interpreter.Interpreter.ScriptEnv import sigmastate.interpreter.CErgoTreeEvaluator import sigma.ast.syntax.ValueOps -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.interpreter.ContextExtension import sigmastate.lang.{CompilerResult, CompilerSettings, LangTests, SigmaCompiler} import sigma.serialization.ErgoTreeSerializer.DefaultSerializer diff --git a/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala b/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala index e8fc16e953..11ef6f4fac 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/ErgoTreeBuildingTest.scala @@ -8,7 +8,7 @@ import scalan.BaseCtxTests import sigma.ast.syntax.ValueOps import sigmastate.lang.LangTests import sigma.ast.Apply -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext class ErgoTreeBuildingTest extends BaseCtxTests with LangTests with ExampleContracts with ErgoScriptTestkit { diff --git a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala index 9539bfb135..179fd6b436 100644 --- a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala +++ b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala @@ -12,7 +12,7 @@ import sigma.data.{RType, SigmaBoolean} import sigma.validation.ValidationException import sigma.validation.ValidationRules.CheckSerializableTypeCode import sigma.ast.syntax.{SValue, SigmaPropValue} -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.eval.{CostDetails, EvalSettings, Extensions, GivenCost, TracedCost} import sigmastate.helpers.TestingHelpers._ import sigma.interpreter.ContextExtension.VarBinding diff --git a/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala b/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala index bbdc4cbdce..f7129a7723 100644 --- a/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/serialization/ErgoTreeSerializerSpecification.scala @@ -10,7 +10,7 @@ import sigma.util.Extensions.SigmaPropOps import sigma.validation.ValidationException import ErgoTree.EmptyConstants import ErgoTree.HeaderType -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.eval.Extensions.SigmaBooleanOps import sigmastate._ import sigmastate.helpers.CompilerTestingCommons diff --git a/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala index 7cc36f798d..6b0c0080c9 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/AVLTreeScriptsSpecification.scala @@ -18,7 +18,7 @@ import sigma.ast.syntax._ import sigma.Coll import sigma.ast.SAvlTree import sigma.ast.syntax.{GetVarByteArray, OptionValueOps} -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.data.{AvlTreeData, AvlTreeFlags, CSigmaProp, TrivialProp} import sigma.eval.SigmaDsl import sigma.interpreter.ProverResult diff --git a/sc/shared/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala index 5405c32b58..77e78aa6bf 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/UsingContextPropertiesSpecification.scala @@ -7,7 +7,7 @@ import sigmastate.helpers.CompilerTestingCommons import org.ergoplatform.dsl.{ContractSpec, SigmaContractSyntax, TestContractSpec} import org.ergoplatform.ErgoBox import scorex.crypto.hash.Blake2b256 -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.data.{CSigmaProp, TrivialProp} class UsingContextPropertiesSpecification extends CompilerTestingCommons diff --git a/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala b/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala index 4fe0ecc136..16b4e3e232 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/blockchain/BlockchainSimulationTestingCommons.scala @@ -17,7 +17,7 @@ import scorex.util._ import sigma.Colls import sigma.data.{AvlTreeData, AvlTreeFlags} import ErgoTree.ZeroHeader -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.eval.Extensions.SigmaBooleanOps import sigma.interpreter.ContextExtension import sigmastate.interpreter.Interpreter.{ScriptNameProp, emptyEnv} diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala index 9b5c796af8..556c56bc03 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/IcoExample.scala @@ -22,7 +22,7 @@ import sigmastate.helpers.{CompilerTestingCommons, ContextEnrichingTestProvingIn import sigmastate.interpreter.Interpreter.ScriptNameProp import sigmastate.interpreter.Interpreter import sigma.ast.syntax._ -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.eval.SigmaDsl import sigma.serialization.ErgoTreeSerializer import sigma.serialization.ErgoTreeSerializer.DefaultSerializer diff --git a/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala b/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala index db3f3bc46b..556fbf9c06 100644 --- a/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/utxo/examples/LetsSpecification.scala @@ -15,7 +15,7 @@ import sigmastate.helpers.TestingHelpers._ import sigmastate.interpreter.Interpreter.ScriptNameProp import sigma.serialization.ErgoTreeSerializer import sigma.ast.syntax._ -import sigma.compiler.IRContext +import sigma.compiler.ir.IRContext import sigma.eval.SigmaDsl import scala.util.Random From 7247cf81c9c31a2e5336bde70adbe65315341923 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 16 May 2024 11:23:23 +0100 Subject: [PATCH 54/65] refactor-ir-cake: move classes around in sigma.compiler.ir --- .../src/main/scala/sigma/compiler/{ir => }/Exceptions.scala | 2 +- sc/shared/src/main/scala/sigma/compiler/ir/Base.scala | 2 +- .../src/main/scala/sigma/compiler/ir/DefRewriting.scala | 1 - .../src/main/scala/sigma/compiler/ir/GraphBuilding.scala | 2 +- sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala | 1 + .../src/main/scala/sigma/compiler/ir/MethodCalls.scala | 1 - sc/shared/src/main/scala/sigma/compiler/ir/Modules.scala | 2 ++ .../scala/sigma/compiler/ir/{ => core}/MutableLazy.scala | 2 +- .../scala/sigma/compiler/ir/{ => meta}/ModuleInfo.scala | 4 +--- .../src/main/scala/sigma/compiler/ir/meta/SSymName.scala | 6 +----- .../src/main/scala/special/collection/impl/CollsImpl.scala | 3 ++- .../src/main/scala/special/sigma/impl/SigmaDslImpl.scala | 3 ++- .../src/main/scala/wrappers/scala/impl/WOptionsImpl.scala | 3 ++- .../src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala | 3 ++- .../scala/wrappers/special/impl/WSpecialPredefsImpl.scala | 4 +++- 15 files changed, 20 insertions(+), 19 deletions(-) rename sc/shared/src/main/scala/sigma/compiler/{ir => }/Exceptions.scala (93%) rename sc/shared/src/main/scala/sigma/compiler/ir/{ => core}/MutableLazy.scala (96%) rename sc/shared/src/main/scala/sigma/compiler/ir/{ => meta}/ModuleInfo.scala (88%) diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/Exceptions.scala b/sc/shared/src/main/scala/sigma/compiler/Exceptions.scala similarity index 93% rename from sc/shared/src/main/scala/sigma/compiler/ir/Exceptions.scala rename to sc/shared/src/main/scala/sigma/compiler/Exceptions.scala index 8ab128a06e..9147df943a 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/Exceptions.scala +++ b/sc/shared/src/main/scala/sigma/compiler/Exceptions.scala @@ -1,4 +1,4 @@ -package scalan +package sigma.compiler.ir /** * Can be thrown in staged method body to prevent body unfolding. diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/Base.scala b/sc/shared/src/main/scala/sigma/compiler/ir/Base.scala index 939d364953..48e3e5d09e 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/Base.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/Base.scala @@ -1,7 +1,7 @@ package sigma.compiler.ir import debox.{cfor, Buffer => DBuffer} -import scalan.MutableLazy +import sigma.compiler.ir.core.MutableLazy import sigma.data.OverloadHack.Overloaded1 import sigma.data.{AVHashMap, Nullable, RType} import sigma.reflection.RConstructor diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala b/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala index fe289cafe0..a37eed2558 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala @@ -1,6 +1,5 @@ package sigma.compiler.ir -import scalan.DelayInvokeException import sigma.data.ExactNumeric trait DefRewriting { scalan: IRContext => diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/GraphBuilding.scala b/sc/shared/src/main/scala/sigma/compiler/ir/GraphBuilding.scala index 71029b4628..7c7b80d39a 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/GraphBuilding.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/GraphBuilding.scala @@ -1,11 +1,11 @@ package sigma.compiler.ir import org.ergoplatform._ -import scalan.MutableLazy import sigma.ast.TypeCodes.LastConstantCode import sigma.ast.Value.Typed import sigma.ast.syntax.{SValue, ValueOps} import sigma.ast._ +import sigma.compiler.ir.core.MutableLazy import sigma.crypto.EcPointType import sigma.data.ExactIntegral.{ByteIsExactIntegral, IntIsExactIntegral, LongIsExactIntegral, ShortIsExactIntegral} import sigma.data.ExactOrdering.{ByteIsExactOrdering, IntIsExactOrdering, LongIsExactOrdering, ShortIsExactOrdering} diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala index 7fae587ac4..b61e76e285 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala @@ -1,6 +1,7 @@ package sigma.compiler.ir import scalan._ +import sigma.compiler.ir.core.MutableLazy import sigma.compiler.ir.primitives._ import sigma.data.{Nullable, RType} import sigma.util.MemoizedFunc diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala b/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala index de96900c62..fff69557b3 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala @@ -1,7 +1,6 @@ package sigma.compiler.ir import debox.{cfor, Buffer => DBuffer} -import scalan.DelayInvokeException import sigma.reflection.RMethod import sigma.util.CollectionUtil.TraversableOps diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/Modules.scala b/sc/shared/src/main/scala/sigma/compiler/ir/Modules.scala index cafee1ef84..b14d4471d1 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/Modules.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/Modules.scala @@ -1,5 +1,7 @@ package sigma.compiler.ir +import sigma.compiler.ir.meta.ModuleInfo + trait Modules extends Base { self: IRContext => /** Whether staged modules should be registered when cake is constructed and initialized. */ diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/MutableLazy.scala b/sc/shared/src/main/scala/sigma/compiler/ir/core/MutableLazy.scala similarity index 96% rename from sc/shared/src/main/scala/sigma/compiler/ir/MutableLazy.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/core/MutableLazy.scala index 5b6a579476..efaab623a3 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/MutableLazy.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/core/MutableLazy.scala @@ -1,4 +1,4 @@ -package scalan +package sigma.compiler.ir.core import scala.language.implicitConversions diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/ModuleInfo.scala b/sc/shared/src/main/scala/sigma/compiler/ir/meta/ModuleInfo.scala similarity index 88% rename from sc/shared/src/main/scala/sigma/compiler/ir/ModuleInfo.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/meta/ModuleInfo.scala index ccd71ffdc0..3ccdca18ac 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/ModuleInfo.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/meta/ModuleInfo.scala @@ -1,6 +1,4 @@ -package sigma.compiler.ir - -import scalan.meta.SSymName +package sigma.compiler.ir.meta /** Information about generated Special library module. * Instances are created in generated code. diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/meta/SSymName.scala b/sc/shared/src/main/scala/sigma/compiler/ir/meta/SSymName.scala index b0f8dae6d2..944b505250 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/meta/SSymName.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/meta/SSymName.scala @@ -1,17 +1,13 @@ -package scalan.meta +package sigma.compiler.ir.meta import sigma.util.StringUtil.StringUtilExtensions -case class ImportItem(packageName: String, importedNames: List[String]) - case class SSymName(packageName: String, name: String) { import SSymName._ def mkFullName = fullNameString(packageName, name) } object SSymName { - /** Wildcard character used to signify importing all names from namespace */ - val ImportAllWildcard = "*" def fullNameString(packageName: String, name: String): String = if (packageName.isNullOrEmpty) name else s"$packageName.$name" } \ No newline at end of file diff --git a/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala b/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala index 09c888bf49..dcfdf25217 100644 --- a/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala +++ b/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala @@ -7,7 +7,8 @@ import sigma.compiler.ir.IRContext import scala.collection.compat.immutable.ArraySeq package impl { - import sigma.compiler.ir.{Base, GraphIRReflection, ModuleInfo, IRContext} + import sigma.compiler.ir.meta.ModuleInfo + import sigma.compiler.ir.{Base, GraphIRReflection, IRContext} import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} diff --git a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala index 6b26a2b100..17ad187b91 100644 --- a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala +++ b/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala @@ -7,7 +7,8 @@ import sigma.compiler.ir.IRContext import scala.collection.compat.immutable.ArraySeq package impl { - import sigma.compiler.ir.{Base, GraphIRReflection, ModuleInfo, IRContext} + import sigma.compiler.ir.meta.ModuleInfo + import sigma.compiler.ir.{Base, GraphIRReflection, IRContext} import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} diff --git a/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala b/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala index 8bb0b1e5e1..048b27b772 100644 --- a/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala +++ b/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala @@ -9,7 +9,8 @@ import special.wrappers.OptionWrapSpec import scala.collection.compat.immutable.ArraySeq package impl { - import sigma.compiler.ir.{Base, GraphIRReflection, ModuleInfo, IRContext} + import sigma.compiler.ir.meta.ModuleInfo + import sigma.compiler.ir.{Base, GraphIRReflection, IRContext} import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} diff --git a/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala b/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala index 0e8b32230a..d90498e4c5 100644 --- a/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala +++ b/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala @@ -8,7 +8,8 @@ import special.wrappers.RTypeWrapSpec import scala.collection.compat.immutable.ArraySeq package impl { - import sigma.compiler.ir.{Base, GraphIRReflection, ModuleInfo, IRContext} + import sigma.compiler.ir.meta.ModuleInfo + import sigma.compiler.ir.{Base, GraphIRReflection, IRContext} import sigma.reflection.{RClass, RMethod} // Abs ----------------------------------- diff --git a/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala b/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala index 6e763850bd..66820b6792 100644 --- a/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala +++ b/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala @@ -5,7 +5,9 @@ import scalan._ import sigma.compiler.ir.IRContext package impl { - import sigma.compiler.ir.{Base, GraphIRReflection, ModuleInfo, IRContext} + import sigma.compiler.ir.core.MutableLazy + import sigma.compiler.ir.meta.ModuleInfo + import sigma.compiler.ir.{Base, GraphIRReflection, IRContext} import sigma.data.Nullable import sigma.reflection.RClass From 80114f1561e8b5d889543b992bb046553ad45c4e Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 16 May 2024 11:39:09 +0100 Subject: [PATCH 55/65] refactor-ir-cake: SigmaCompiler moved to sigma.compiler package --- .../main/scala/sigmastate/lang/js/SigmaCompiler.scala | 4 ++-- .../scala/org/ergoplatform/ErgoScriptPredef.scala | 2 +- .../src/main/scala/sigma/compiler/Exceptions.scala | 2 +- .../lang => sigma/compiler}/SigmaCompiler.scala | 4 +++- .../compiler}/SigmaTemplateCompiler.scala | 3 ++- .../main/scala/sigma/compiler/ir/DefRewriting.scala | 1 + .../main/scala/sigma/compiler/ir/MethodCalls.scala | 1 + .../lang => sigma/compiler/phases}/SigmaBinder.scala | 2 +- .../lang => sigma/compiler/phases}/SigmaTyper.scala | 11 +++++------ .../src/test/scala/sigmastate/CompilerTestsBase.scala | 2 +- .../test/scala/sigmastate/ErgoTreeSpecification.scala | 2 +- .../scala/sigmastate/eval/ErgoScriptTestkit.scala | 3 ++- .../sigmastate/helpers/CompilerTestingCommons.scala | 2 +- .../test/scala/sigmastate/lang/SigmaBinderTest.scala | 1 + .../sigmastate/lang/SigmaTemplateCompilerTest.scala | 1 + .../test/scala/sigmastate/lang/SigmaTyperTest.scala | 1 + 16 files changed, 25 insertions(+), 17 deletions(-) rename sc/shared/src/main/scala/{sigmastate/lang => sigma/compiler}/SigmaCompiler.scala (98%) rename sc/shared/src/main/scala/{sigmastate/lang => sigma/compiler}/SigmaTemplateCompiler.scala (96%) rename sc/shared/src/main/scala/{sigmastate/lang => sigma/compiler/phases}/SigmaBinder.scala (99%) rename sc/shared/src/main/scala/{sigmastate/lang => sigma/compiler/phases}/SigmaTyper.scala (99%) diff --git a/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala b/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala index 6264cd2f82..2fc7556875 100644 --- a/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala +++ b/sc/js/src/main/scala/sigmastate/lang/js/SigmaCompiler.scala @@ -15,7 +15,7 @@ import sigma.ast.syntax.ValueOps /** Wrapper exported to JS. */ @JSExportTopLevel("SigmaCompiler") -class SigmaCompiler(_compiler: sigmastate.lang.SigmaCompiler) extends js.Object { +class SigmaCompiler(_compiler: sigma.compiler.SigmaCompiler) extends js.Object { /** Compiles ErgoScript code to ErgoTree. * @@ -59,7 +59,7 @@ object SigmaCompiler extends js.Object { * @return SigmaCompiler instance */ private def create(networkPrefix: Byte): SigmaCompiler = { - val compiler = sigmastate.lang.SigmaCompiler(networkPrefix) + val compiler = sigma.compiler.SigmaCompiler(networkPrefix) new SigmaCompiler(compiler) } } diff --git a/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala b/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala index 60b82a54a2..9eec42a4fb 100644 --- a/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala +++ b/sc/shared/src/main/scala/org/ergoplatform/ErgoScriptPredef.scala @@ -1,11 +1,11 @@ package org.ergoplatform -import sigmastate.lang.SigmaCompiler import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix import sigma.ast.SType import sigma.ast.syntax.SigmaPropValue import sigma.ast.Value import sigma.ast.syntax.ValueOps +import sigma.compiler.SigmaCompiler import sigma.compiler.ir.IRContext object ErgoScriptPredef { diff --git a/sc/shared/src/main/scala/sigma/compiler/Exceptions.scala b/sc/shared/src/main/scala/sigma/compiler/Exceptions.scala index 9147df943a..75b1ecb6a3 100644 --- a/sc/shared/src/main/scala/sigma/compiler/Exceptions.scala +++ b/sc/shared/src/main/scala/sigma/compiler/Exceptions.scala @@ -1,4 +1,4 @@ -package sigma.compiler.ir +package sigma.compiler /** * Can be thrown in staged method body to prevent body unfolding. diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala b/sc/shared/src/main/scala/sigma/compiler/SigmaCompiler.scala similarity index 98% rename from sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala rename to sc/shared/src/main/scala/sigma/compiler/SigmaCompiler.scala index 0a2bb9a355..942154409b 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaCompiler.scala +++ b/sc/shared/src/main/scala/sigma/compiler/SigmaCompiler.scala @@ -1,4 +1,4 @@ -package sigmastate.lang +package sigma.compiler import fastparse.Parsed import fastparse.Parsed.Success @@ -13,7 +13,9 @@ import sigma.ast._ import sigma.ast.syntax.SValue import SCollectionMethods.{ExistsMethod, ForallMethod, MapMethod} import sigma.compiler.ir.{GraphIRReflection, IRContext} +import sigma.compiler.phases.{SigmaBinder, SigmaTyper} import sigmastate.InterpreterReflection +import sigmastate.lang.SigmaParser /** * @param networkPrefix network prefix to decode an ergo address from string (PK op) diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala b/sc/shared/src/main/scala/sigma/compiler/SigmaTemplateCompiler.scala similarity index 96% rename from sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala rename to sc/shared/src/main/scala/sigma/compiler/SigmaTemplateCompiler.scala index 09d27b2489..0b30f9830a 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaTemplateCompiler.scala +++ b/sc/shared/src/main/scala/sigma/compiler/SigmaTemplateCompiler.scala @@ -1,10 +1,11 @@ -package sigmastate.lang +package sigma.compiler import fastparse.Parsed import org.ergoplatform.sdk.{ContractTemplate, Parameter} import sigma.ast.SourceContext import sigma.ast.syntax.SValue import sigma.compiler.ir.CompiletimeIRContext +import sigmastate.lang.{ContractParser, ParsedContractTemplate} import sigmastate.lang.parsers.ParserException /** Compiler which compiles Ergo contract templates into a [[ContractTemplate]]. */ diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala b/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala index a37eed2558..d7bb3a9e4d 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala @@ -1,5 +1,6 @@ package sigma.compiler.ir +import sigma.compiler.DelayInvokeException import sigma.data.ExactNumeric trait DefRewriting { scalan: IRContext => diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala b/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala index fff69557b3..5ecdb823a7 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala @@ -1,6 +1,7 @@ package sigma.compiler.ir import debox.{cfor, Buffer => DBuffer} +import sigma.compiler.DelayInvokeException import sigma.reflection.RMethod import sigma.util.CollectionUtil.TraversableOps diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala b/sc/shared/src/main/scala/sigma/compiler/phases/SigmaBinder.scala similarity index 99% rename from sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala rename to sc/shared/src/main/scala/sigma/compiler/phases/SigmaBinder.scala index 82aaea7e30..af5be938be 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaBinder.scala +++ b/sc/shared/src/main/scala/sigma/compiler/phases/SigmaBinder.scala @@ -1,4 +1,4 @@ -package sigmastate.lang +package sigma.compiler.phases import org.ergoplatform.ErgoAddressEncoder.NetworkPrefix import sigma.ast.NoType diff --git a/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala b/sc/shared/src/main/scala/sigma/compiler/phases/SigmaTyper.scala similarity index 99% rename from sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala rename to sc/shared/src/main/scala/sigma/compiler/phases/SigmaTyper.scala index 416f2d7fbb..679d98a18f 100644 --- a/sc/shared/src/main/scala/sigmastate/lang/SigmaTyper.scala +++ b/sc/shared/src/main/scala/sigma/compiler/phases/SigmaTyper.scala @@ -1,15 +1,14 @@ -package sigmastate.lang +package sigma.compiler.phases import sigma.ast.SCollection.{SBooleanArray, SByteArray} +import sigma.ast.SigmaPredef._ import sigma.ast._ -import sigma.ast.syntax.SValue +import sigma.ast.syntax.{SValue, _} import sigma.data.{Nullable, SigmaBoolean} -import sigma.util.Extensions.Ensuring -import sigmastate.exceptions._ -import SigmaPredef._ -import sigma.ast.syntax._ import sigma.exceptions.TyperException import sigma.serialization.OpCodes +import sigma.util.Extensions.Ensuring +import sigmastate.exceptions._ import scala.collection.mutable.ArrayBuffer diff --git a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala index 19c0a4b134..f1d5c6aa89 100644 --- a/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala +++ b/sc/shared/src/test/scala/sigmastate/CompilerTestsBase.scala @@ -1,7 +1,6 @@ package sigmastate import scala.util.DynamicVariable -import sigmastate.lang.{CompilerResult, CompilerSettings, SigmaCompiler} import sigmastate.interpreter.Interpreter.ScriptEnv import sigma.ast.{ErgoTree, SType, TransformingSigmaBuilder, Value} import org.ergoplatform.ErgoAddressEncoder.TestnetNetworkPrefix @@ -9,6 +8,7 @@ import sigma.ast.syntax.{SValue, SigmaPropValue} import sigma.serialization.ValueSerializer import sigma.compiler.ir.IRContext import sigma.ast.syntax.ValueOps +import sigma.compiler.{CompilerResult, CompilerSettings, SigmaCompiler} import sigmastate.helpers.{NegativeTesting, SigmaPPrint} trait CompilerTestsBase extends TestsBase with NegativeTesting { diff --git a/sc/shared/src/test/scala/sigmastate/ErgoTreeSpecification.scala b/sc/shared/src/test/scala/sigmastate/ErgoTreeSpecification.scala index b0b6273fad..7539bd5e48 100644 --- a/sc/shared/src/test/scala/sigmastate/ErgoTreeSpecification.scala +++ b/sc/shared/src/test/scala/sigmastate/ErgoTreeSpecification.scala @@ -17,9 +17,9 @@ import sigmastate.helpers.{ErgoLikeContextTesting, SigmaPPrint} import sigmastate.interpreter.Interpreter.ReductionResult import sigmastate.interpreter.CErgoTreeEvaluator import sigma.ast.syntax._ +import sigma.compiler.CompilerSettings import sigma.eval.EvalSettings import sigma.exceptions.{CostLimitException, InterpreterException} -import sigmastate.lang.CompilerSettings import sigma.serialization.ErgoTreeSerializer.DefaultSerializer import sigmastate.Plus import sigmastate.utils.Helpers.TryOps diff --git a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala index 90d9cb8b6d..da9ed70efd 100644 --- a/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala +++ b/sc/shared/src/test/scala/sigmastate/eval/ErgoScriptTestkit.scala @@ -14,9 +14,10 @@ import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeConte import sigmastate.interpreter.Interpreter.ScriptEnv import sigmastate.interpreter.CErgoTreeEvaluator import sigma.ast.syntax.ValueOps +import sigma.compiler.{CompilerResult, CompilerSettings, SigmaCompiler} import sigma.compiler.ir.IRContext import sigma.interpreter.ContextExtension -import sigmastate.lang.{CompilerResult, CompilerSettings, LangTests, SigmaCompiler} +import sigmastate.lang.LangTests import sigma.serialization.ErgoTreeSerializer.DefaultSerializer import sigmastate.CompilerTestsBase import sigma.{ContractsTestkit, Context => DContext} diff --git a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala index 179fd6b436..3b1d6ba3dc 100644 --- a/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala +++ b/sc/shared/src/test/scala/sigmastate/helpers/CompilerTestingCommons.scala @@ -12,6 +12,7 @@ import sigma.data.{RType, SigmaBoolean} import sigma.validation.ValidationException import sigma.validation.ValidationRules.CheckSerializableTypeCode import sigma.ast.syntax.{SValue, SigmaPropValue} +import sigma.compiler.{CompilerSettings, SigmaCompiler} import sigma.compiler.ir.IRContext import sigma.eval.{CostDetails, EvalSettings, Extensions, GivenCost, TracedCost} import sigmastate.helpers.TestingHelpers._ @@ -19,7 +20,6 @@ import sigma.interpreter.ContextExtension.VarBinding import sigmastate.interpreter.CErgoTreeEvaluator.DefaultProfiler import sigmastate.interpreter.Interpreter.ScriptEnv import sigmastate.interpreter._ -import sigmastate.lang.{CompilerSettings, SigmaCompiler} import sigma.serialization.SigmaSerializer import sigmastate.CompilerTestsBase import sigmastate.eval.CContext diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaBinderTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaBinderTest.scala index 1f758370a0..b4b4ad20cd 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaBinderTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaBinderTest.scala @@ -11,6 +11,7 @@ import sigmastate._ import sigmastate.interpreter.Interpreter.ScriptEnv import SigmaPredef.PredefinedFuncRegistry import sigma.ast.syntax._ +import sigma.compiler.phases.SigmaBinder import sigma.eval.SigmaDsl import sigma.exceptions.BinderException diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala index 966a7c4c74..a03d160654 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaTemplateCompilerTest.scala @@ -7,6 +7,7 @@ import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks import sigma.VersionContext import sigma.ast.ErgoTree.HeaderType import sigma.ast.{BinAnd, BoolToSigmaProp, ConstantPlaceholder, ErgoTree, FalseLeaf, GT, Height, IntConstant, LT, SBoolean, SInt, SLong, SString, TrueLeaf} +import sigma.compiler.SigmaTemplateCompiler import sigma.exceptions.TyperException import sigmastate.CompilerTestsBase import sigmastate.interpreter.Interpreter.ScriptEnv diff --git a/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala b/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala index 5bb38c7998..6b93b098ea 100644 --- a/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala +++ b/sc/shared/src/test/scala/sigmastate/lang/SigmaTyperTest.scala @@ -19,6 +19,7 @@ import sigmastate.lang.parsers.ParserException import sigma.serialization.ErgoTreeSerializer import sigma.serialization.generators.ObjectGenerators import sigma.ast.Select +import sigma.compiler.phases.{SigmaBinder, SigmaTyper} import sigma.exceptions.TyperException class SigmaTyperTest extends AnyPropSpec From 66daf525f870626897521ea7ac4fda961b6b32e5 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 16 May 2024 12:14:06 +0100 Subject: [PATCH 56/65] refactor-ir-cake: wrappers moved to sigma.compiler.ir.wrappers package --- .../test/scala/sigmastate/ReflectionGenerator.scala | 4 ++-- .../scala/sigma/compiler/ir/GraphIRReflection.scala | 8 ++++---- .../src/main/scala/sigma/compiler/ir/IRContext.scala | 2 +- .../src/main/scala/sigma/compiler/ir/TypeDescs.scala | 2 +- .../compiler/ir}/wrappers/WrapSpec.scala | 2 +- .../sigma/compiler/ir/wrappers/WrappersModule.scala | 11 +++++++++++ .../compiler/ir}/wrappers/WrappersSpec.scala | 2 +- .../compiler/ir}/wrappers/scala/WOptions.scala | 4 ++-- .../ir}/wrappers/scala/impl/WOptionsImpl.scala | 10 +++++----- .../compiler/ir}/wrappers/scalan/WRTypes.scala | 2 +- .../ir}/wrappers/scalan/impl/WRTypesImpl.scala | 6 +++--- .../ir}/wrappers/special/WSpecialPredefs.scala | 2 +- .../wrappers/special/impl/WSpecialPredefsImpl.scala | 6 +++--- .../scala/special/sigma/wrappers/WrappersModule.scala | 2 +- .../main/scala/special/wrappers/WrappersModule.scala | 11 ----------- .../scala/special/wrappers/WSpecialPredefTests.scala | 1 - 16 files changed, 37 insertions(+), 38 deletions(-) rename sc/shared/src/main/scala/{special => sigma/compiler/ir}/wrappers/WrapSpec.scala (76%) create mode 100644 sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersModule.scala rename sc/shared/src/main/scala/{special => sigma/compiler/ir}/wrappers/WrappersSpec.scala (95%) rename sc/shared/src/main/scala/{ => sigma/compiler/ir}/wrappers/scala/WOptions.scala (82%) rename sc/shared/src/main/scala/{ => sigma/compiler/ir}/wrappers/scala/impl/WOptionsImpl.scala (96%) rename sc/shared/src/main/scala/{ => sigma/compiler/ir}/wrappers/scalan/WRTypes.scala (85%) rename sc/shared/src/main/scala/{ => sigma/compiler/ir}/wrappers/scalan/impl/WRTypesImpl.scala (95%) rename sc/shared/src/main/scala/{ => sigma/compiler/ir}/wrappers/special/WSpecialPredefs.scala (85%) rename sc/shared/src/main/scala/{ => sigma/compiler/ir}/wrappers/special/impl/WSpecialPredefsImpl.scala (89%) delete mode 100644 sc/shared/src/main/scala/special/wrappers/WrappersModule.scala diff --git a/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala b/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala index c102f4eda8..324542505e 100644 --- a/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala +++ b/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala @@ -33,13 +33,13 @@ object ReflectionGenerator { "sigma.compiler.ir.primitives.", "sigma.", "sigma.", - "special.wrappers.", + "sigma.compiler.ir.wrappers.", "sigma.ast.", "sigmastate.lang.Terms.", "sigmastate.interpreter.", "sigmastate.utxo.", "sigmastate.", - "wrappers.scala.", + "sigma.compiler.ir.wrappers.scala.", "sigma.compiler.ir.", "scala.collection.", "scala." diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala b/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala index 32d95354c3..200bbf12a7 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala @@ -5,8 +5,8 @@ import sigma.{Colls, SigmaDsl} import sigma.data.RType import sigma.reflection.ReflectionData.registerClassEntry import sigma.reflection.{ReflectionData, mkConstructor, mkMethod} -import special.wrappers.{OptionWrapSpec, RTypeWrapSpec} -import wrappers.scalan.WRTypes +import sigma.compiler.ir.wrappers.{OptionWrapSpec, RTypeWrapSpec} +import sigma.compiler.ir.wrappers.scalan.WRTypes /** Registrations of reflection metadata for graph-ir module (see README.md). * Such metadata is only used on JS platform to support reflection-like interfaces of @@ -21,7 +21,7 @@ object GraphIRReflection { /** Forces initialization of reflection data. */ val reflection = ReflectionData - { val clazz = classOf[wrappers.scala.WOptions#WOption[_]] + { val clazz = classOf[sigma.compiler.ir.wrappers.scala.WOptions#WOption[_]] val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( @@ -557,7 +557,7 @@ object GraphIRReflection { ) } - { val clazz = classOf[wrappers.special.WSpecialPredefs#WSpecialPredefCompanion] + { val clazz = classOf[sigma.compiler.ir.wrappers.special.WSpecialPredefs#WSpecialPredefCompanion] val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala index b61e76e285..c28d42ab12 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala @@ -6,7 +6,7 @@ import sigma.compiler.ir.primitives._ import sigma.data.{Nullable, RType} import sigma.util.MemoizedFunc import sigma.{CollsModule, SigmaDslModule} -import special.wrappers.WrappersModule +import sigma.compiler.ir.wrappers.WrappersModule /** Aggregate cake with all inter-dependent modules assembled together. * Each instance of this class contains independent IR context, thus many diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/TypeDescs.scala b/sc/shared/src/main/scala/sigma/compiler/ir/TypeDescs.scala index 4346d117ea..8d938029e3 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/TypeDescs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/TypeDescs.scala @@ -5,7 +5,7 @@ import scalan.core.{Contravariant, Covariant, Variance} import sigma.data.{AVHashMap, Lazy, Nullable, RType} import sigma.reflection.{RClass, RConstructor, RMethod} import sigma.util.CollectionUtil -import special.wrappers.WrapSpec +import sigma.compiler.ir.wrappers.WrapSpec import scala.annotation.implicitNotFound import scala.collection.immutable.ListMap diff --git a/sc/shared/src/main/scala/special/wrappers/WrapSpec.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrapSpec.scala similarity index 76% rename from sc/shared/src/main/scala/special/wrappers/WrapSpec.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrapSpec.scala index dd07f1144c..b9c21227b2 100644 --- a/sc/shared/src/main/scala/special/wrappers/WrapSpec.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrapSpec.scala @@ -1,4 +1,4 @@ -package special.wrappers +package sigma.compiler.ir.wrappers /** Base type for all wrapper specification classes. * @see OptionWrapSpec as an example */ diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersModule.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersModule.scala new file mode 100644 index 0000000000..d02a8c4e5b --- /dev/null +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersModule.scala @@ -0,0 +1,11 @@ +package sigma.compiler.ir.wrappers + +import sigma.compiler.ir.IRContext +import sigma.compiler.ir.wrappers.scala.WOptionsModule +import sigma.compiler.ir.wrappers.scalan.WRTypesModule +import sigma.compiler.ir.wrappers.special.WSpecialPredefsModule + +trait WrappersModule + extends WSpecialPredefsModule + with WOptionsModule + with WRTypesModule { self: IRContext => } \ No newline at end of file diff --git a/sc/shared/src/main/scala/special/wrappers/WrappersSpec.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersSpec.scala similarity index 95% rename from sc/shared/src/main/scala/special/wrappers/WrappersSpec.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersSpec.scala index d520ce9006..096bfc5220 100644 --- a/sc/shared/src/main/scala/special/wrappers/WrappersSpec.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersSpec.scala @@ -1,4 +1,4 @@ -package special.wrappers +package sigma.compiler.ir.wrappers import sigma.data.RType diff --git a/sc/shared/src/main/scala/wrappers/scala/WOptions.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/WOptions.scala similarity index 82% rename from sc/shared/src/main/scala/wrappers/scala/WOptions.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/WOptions.scala index b59692ebd1..1ddb7ead40 100644 --- a/sc/shared/src/main/scala/wrappers/scala/WOptions.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/WOptions.scala @@ -1,7 +1,7 @@ -package wrappers.scala { +package sigma.compiler.ir.wrappers.scala { import scalan._ import sigma.compiler.ir.{Base, IRContext} - import special.wrappers.WrappersModule + import sigma.compiler.ir.wrappers.WrappersModule trait WOptions extends Base { self: IRContext => trait WOption[A] extends Def[WOption[A]] { diff --git a/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/impl/WOptionsImpl.scala similarity index 96% rename from sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/impl/WOptionsImpl.scala index 048b27b772..da601f06c1 100644 --- a/sc/shared/src/main/scala/wrappers/scala/impl/WOptionsImpl.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/impl/WOptionsImpl.scala @@ -1,10 +1,10 @@ -package wrappers.scala +package sigma.compiler.ir.wrappers.scala import scala.language.{existentials, implicitConversions} import scalan._ import sigma.compiler.ir.IRContext -import special.wrappers.WrappersModule -import special.wrappers.OptionWrapSpec +import sigma.compiler.ir.wrappers.WrappersModule +import sigma.compiler.ir.wrappers.OptionWrapSpec import scala.collection.compat.immutable.ArraySeq @@ -239,9 +239,9 @@ class WOptionCls extends EntityObject("WOption") { registerEntityObject("WOption", WOption) } -object WOptionsModule extends ModuleInfo("wrappers.scala", "WOptions") { +object WOptionsModule extends ModuleInfo("sigma.compiler.ir.wrappers.scala", "WOptions") { val reflection = GraphIRReflection } } -trait WOptionsModule extends wrappers.scala.impl.WOptionsDefs {self: IRContext =>} +trait WOptionsModule extends sigma.compiler.ir.wrappers.scala.impl.WOptionsDefs {self: IRContext =>} diff --git a/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/WRTypes.scala similarity index 85% rename from sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/WRTypes.scala index 41242c4ce3..10ce21e9ef 100644 --- a/sc/shared/src/main/scala/wrappers/scalan/WRTypes.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/WRTypes.scala @@ -1,4 +1,4 @@ -package wrappers.scalan { +package sigma.compiler.ir.wrappers.scalan { import scalan._ import sigma.compiler.ir.{Base, IRContext} diff --git a/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/impl/WRTypesImpl.scala similarity index 95% rename from sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/impl/WRTypesImpl.scala index d90498e4c5..1f7524bc3c 100644 --- a/sc/shared/src/main/scala/wrappers/scalan/impl/WRTypesImpl.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/impl/WRTypesImpl.scala @@ -1,9 +1,9 @@ -package wrappers.scalan +package sigma.compiler.ir.wrappers.scalan import sigma.compiler.ir.IRContext import scala.language.{existentials, implicitConversions} import sigma.data.RType -import special.wrappers.RTypeWrapSpec +import sigma.compiler.ir.wrappers.RTypeWrapSpec import scala.collection.compat.immutable.ArraySeq @@ -118,4 +118,4 @@ object WRTypesModule extends ModuleInfo("wrappers.scalan", "WRTypes") { } } -trait WRTypesModule extends wrappers.scalan.impl.WRTypesDefs {self: IRContext =>} +trait WRTypesModule extends sigma.compiler.ir.wrappers.scalan.impl.WRTypesDefs {self: IRContext =>} diff --git a/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/WSpecialPredefs.scala similarity index 85% rename from sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/WSpecialPredefs.scala index 45065b324b..a1b9adeaa0 100644 --- a/sc/shared/src/main/scala/wrappers/special/WSpecialPredefs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/WSpecialPredefs.scala @@ -1,4 +1,4 @@ -package wrappers.special { +package sigma.compiler.ir.wrappers.special { import scalan._ import sigma.compiler.ir.{Base, IRContext} diff --git a/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/impl/WSpecialPredefsImpl.scala similarity index 89% rename from sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/impl/WSpecialPredefsImpl.scala index 66820b6792..a403aa0e5a 100644 --- a/sc/shared/src/main/scala/wrappers/special/impl/WSpecialPredefsImpl.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/impl/WSpecialPredefsImpl.scala @@ -1,4 +1,4 @@ -package wrappers.special +package sigma.compiler.ir.wrappers.special import scala.language.{existentials, implicitConversions} import scalan._ @@ -64,9 +64,9 @@ object WSpecialPredef extends EntityObject("WSpecialPredef") { } -object WSpecialPredefsModule extends ModuleInfo("wrappers.special", "WSpecialPredefs") { +object WSpecialPredefsModule extends ModuleInfo("sigma.compiler.ir.wrappers.special", "WSpecialPredefs") { val reflection = GraphIRReflection } } -trait WSpecialPredefsModule extends wrappers.special.impl.WSpecialPredefsDefs {self: IRContext =>} +trait WSpecialPredefsModule extends sigma.compiler.ir.wrappers.special.impl.WSpecialPredefsDefs {self: IRContext =>} diff --git a/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala b/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala index 7d0bcc6b59..d0dbb06e11 100644 --- a/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala +++ b/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala @@ -3,4 +3,4 @@ package sigma.wrappers import sigma.compiler.ir.IRContext trait WrappersModule - extends special.wrappers.WrappersModule { self: IRContext => } + extends sigma.compiler.ir.wrappers.WrappersModule { self: IRContext => } diff --git a/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala b/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala deleted file mode 100644 index 0003fd6464..0000000000 --- a/sc/shared/src/main/scala/special/wrappers/WrappersModule.scala +++ /dev/null @@ -1,11 +0,0 @@ -package special.wrappers - -import sigma.compiler.ir.IRContext -import wrappers.scala.WOptionsModule -import wrappers.scalan.WRTypesModule -import wrappers.special.WSpecialPredefsModule - -trait WrappersModule - extends WSpecialPredefsModule - with WOptionsModule - with WRTypesModule { self: IRContext => } \ No newline at end of file diff --git a/sc/shared/src/test/scala/special/wrappers/WSpecialPredefTests.scala b/sc/shared/src/test/scala/special/wrappers/WSpecialPredefTests.scala index e1097ebf6c..75123cf5bd 100644 --- a/sc/shared/src/test/scala/special/wrappers/WSpecialPredefTests.scala +++ b/sc/shared/src/test/scala/special/wrappers/WSpecialPredefTests.scala @@ -2,7 +2,6 @@ package special.wrappers import scala.language.reflectiveCalls -import sigma.data.RType class WSpecialPredefTests extends WrappersTests { From baab0a8d22dc663b543ab35f8519178b04a1e460 Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 16 May 2024 12:44:29 +0100 Subject: [PATCH 57/65] refactor-ir-cake: wrappers moved to sigma.compiler.ir.wrappers package (part 2) --- .../sigma/compiler/ir/GraphIRReflection.scala | 8 ++++---- .../main/scala/sigma/compiler/ir/IRContext.scala | 14 ++++++++------ .../compiler/ir/wrappers/WrappersModule.scala | 11 ----------- .../sigma/compiler/ir/wrappers/WrappersSpec.scala | 4 +--- .../compiler/ir/wrappers/scala/WOptions.scala | 2 -- .../ir/wrappers/scala/impl/WOptionsImpl.scala | 2 -- .../compiler/ir/wrappers/scalan/WRTypes.scala | 1 - .../compiler/ir/wrappers/sigma}/CollsUnit.scala | 8 ++++---- .../compiler/ir/wrappers}/sigma/SigmaDslUnit.scala | 8 ++++---- .../ir/wrappers/sigma}/impl/CollsImpl.scala | 6 +++--- .../ir/wrappers}/sigma/impl/SigmaDslImpl.scala | 6 ++++-- .../special/impl/WSpecialPredefsImpl.scala | 1 - .../special/sigma/wrappers/WrappersModule.scala | 6 ------ 13 files changed, 28 insertions(+), 49 deletions(-) delete mode 100644 sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersModule.scala rename sc/shared/src/main/scala/{special/collection => sigma/compiler/ir/wrappers/sigma}/CollsUnit.scala (95%) rename sc/shared/src/main/scala/{special => sigma/compiler/ir/wrappers}/sigma/SigmaDslUnit.scala (98%) rename sc/shared/src/main/scala/{special/collection => sigma/compiler/ir/wrappers/sigma}/impl/CollsImpl.scala (99%) rename sc/shared/src/main/scala/{special => sigma/compiler/ir/wrappers}/sigma/impl/SigmaDslImpl.scala (99%) delete mode 100644 sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala b/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala index 200bbf12a7..9482cdc048 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala @@ -1,12 +1,12 @@ package sigma.compiler.ir import sigma.compiler.ir.primitives.Thunks -import sigma.{Colls, SigmaDsl} import sigma.data.RType import sigma.reflection.ReflectionData.registerClassEntry import sigma.reflection.{ReflectionData, mkConstructor, mkMethod} import sigma.compiler.ir.wrappers.{OptionWrapSpec, RTypeWrapSpec} import sigma.compiler.ir.wrappers.scalan.WRTypes +import sigma.compiler.ir.wrappers.sigma.SigmaDsl /** Registrations of reflection metadata for graph-ir module (see README.md). * Such metadata is only used on JS platform to support reflection-like interfaces of @@ -71,7 +71,7 @@ object GraphIRReflection { ) ) - { val clazz = classOf[sigma.SigmaDsl#SigmaProp] + { val clazz = classOf[sigma.compiler.ir.wrappers.sigma.SigmaDsl#SigmaProp] val ctx = null.asInstanceOf[SigmaDsl] // ok! type level only registerClassEntry(clazz, methods = Map( @@ -120,7 +120,7 @@ object GraphIRReflection { ) } - { val clazz = classOf[Colls#CollBuilder] + { val clazz = classOf[sigma.compiler.ir.wrappers.sigma.Colls#CollBuilder] val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( @@ -142,7 +142,7 @@ object GraphIRReflection { } { - val clazz = classOf[Colls#Coll[_]] + val clazz = classOf[sigma.compiler.ir.wrappers.sigma.Colls#Coll[_]] val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala index c28d42ab12..123bc6f209 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala @@ -1,12 +1,13 @@ package sigma.compiler.ir -import scalan._ import sigma.compiler.ir.core.MutableLazy import sigma.compiler.ir.primitives._ import sigma.data.{Nullable, RType} import sigma.util.MemoizedFunc -import sigma.{CollsModule, SigmaDslModule} -import sigma.compiler.ir.wrappers.WrappersModule +import sigma.compiler.ir.wrappers.scala.WOptionsModule +import sigma.compiler.ir.wrappers.scalan.WRTypesModule +import sigma.compiler.ir.wrappers.sigma.{CollsModule, SigmaDslModule} +import sigma.compiler.ir.wrappers.special.WSpecialPredefsModule /** Aggregate cake with all inter-dependent modules assembled together. * Each instance of this class contains independent IR context, thus many @@ -43,12 +44,13 @@ trait IRContext with Entities with Modules with DefRewriting - with WrappersModule with CollsModule - with sigma.wrappers.WrappersModule with SigmaDslModule with TreeBuilding - with GraphBuilding { + with GraphBuilding + with WSpecialPredefsModule + with WOptionsModule + with WRTypesModule { import Coll._ import CollBuilder._ diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersModule.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersModule.scala deleted file mode 100644 index d02a8c4e5b..0000000000 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersModule.scala +++ /dev/null @@ -1,11 +0,0 @@ -package sigma.compiler.ir.wrappers - -import sigma.compiler.ir.IRContext -import sigma.compiler.ir.wrappers.scala.WOptionsModule -import sigma.compiler.ir.wrappers.scalan.WRTypesModule -import sigma.compiler.ir.wrappers.special.WSpecialPredefsModule - -trait WrappersModule - extends WSpecialPredefsModule - with WOptionsModule - with WRTypesModule { self: IRContext => } \ No newline at end of file diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersSpec.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersSpec.scala index 096bfc5220..4c0c5f05eb 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersSpec.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/WrappersSpec.scala @@ -1,7 +1,5 @@ package sigma.compiler.ir.wrappers - -import sigma.data.RType - +import _root_.sigma.data.RType /** Base class for wrappers of such types as WOption, WRType etc. * Used in graph IR to implement method invocation. */ diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/WOptions.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/WOptions.scala index 1ddb7ead40..d6c0971214 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/WOptions.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/WOptions.scala @@ -1,7 +1,5 @@ package sigma.compiler.ir.wrappers.scala { - import scalan._ import sigma.compiler.ir.{Base, IRContext} - import sigma.compiler.ir.wrappers.WrappersModule trait WOptions extends Base { self: IRContext => trait WOption[A] extends Def[WOption[A]] { diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/impl/WOptionsImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/impl/WOptionsImpl.scala index da601f06c1..307e380a76 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/impl/WOptionsImpl.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/impl/WOptionsImpl.scala @@ -1,9 +1,7 @@ package sigma.compiler.ir.wrappers.scala import scala.language.{existentials, implicitConversions} -import scalan._ import sigma.compiler.ir.IRContext -import sigma.compiler.ir.wrappers.WrappersModule import sigma.compiler.ir.wrappers.OptionWrapSpec import scala.collection.compat.immutable.ArraySeq diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/WRTypes.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/WRTypes.scala index 10ce21e9ef..d83c538b8c 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/WRTypes.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/WRTypes.scala @@ -1,5 +1,4 @@ package sigma.compiler.ir.wrappers.scalan { - import scalan._ import sigma.compiler.ir.{Base, IRContext} diff --git a/sc/shared/src/main/scala/special/collection/CollsUnit.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/CollsUnit.scala similarity index 95% rename from sc/shared/src/main/scala/special/collection/CollsUnit.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/CollsUnit.scala index f000b61ed6..9b4a002a14 100644 --- a/sc/shared/src/main/scala/special/collection/CollsUnit.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/CollsUnit.scala @@ -1,5 +1,6 @@ -package sigma { - import sigma.compiler.ir.{Base, IRContext} +package sigma.compiler.ir.wrappers.sigma + +import sigma.compiler.ir.{Base, IRContext} /** Staged version of collection interfaces which is used in graph-based IR to represent * methods of Coll and CollBuilder. @@ -34,5 +35,4 @@ package sigma { 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]]; }; - } -} \ No newline at end of file + } \ No newline at end of file diff --git a/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/SigmaDslUnit.scala similarity index 98% rename from sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/SigmaDslUnit.scala index 46c93558af..7b9d499c7e 100644 --- a/sc/shared/src/main/scala/special/sigma/SigmaDslUnit.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/SigmaDslUnit.scala @@ -1,5 +1,6 @@ -package sigma { - import scalan._ +package sigma.compiler.ir.wrappers.sigma + +import scalan._ import sigma.compiler.ir.{Base, IRContext} trait SigmaDsl extends Base { self: IRContext => @@ -124,5 +125,4 @@ package sigma { trait ContextCompanion; trait SigmaContractCompanion; trait SigmaDslBuilderCompanion - } -} \ No newline at end of file + } \ No newline at end of file diff --git a/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/CollsImpl.scala similarity index 99% rename from sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/CollsImpl.scala index dcfdf25217..fd3f72a642 100644 --- a/sc/shared/src/main/scala/special/collection/impl/CollsImpl.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/CollsImpl.scala @@ -1,8 +1,8 @@ -package sigma +package sigma.compiler.ir.wrappers.sigma import scala.language.{existentials, implicitConversions} -import scalan._ import sigma.compiler.ir.IRContext +import sigma.compiler.ir.wrappers.sigma.impl.CollsDefs import scala.collection.compat.immutable.ArraySeq @@ -643,4 +643,4 @@ object CollsModule extends ModuleInfo("sigma", "Colls") { } } -trait CollsModule extends sigma.impl.CollsDefs {self: IRContext =>} +trait CollsModule extends CollsDefs {self: IRContext =>} diff --git a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/SigmaDslImpl.scala similarity index 99% rename from sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/SigmaDslImpl.scala index 17ad187b91..201c974512 100644 --- a/sc/shared/src/main/scala/special/sigma/impl/SigmaDslImpl.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/SigmaDslImpl.scala @@ -1,13 +1,15 @@ -package sigma +package sigma.compiler.ir.wrappers.sigma import scala.language.{existentials, implicitConversions} import scalan._ import sigma.compiler.ir.IRContext +import sigma.compiler.ir.wrappers.sigma.impl.SigmaDslDefs import scala.collection.compat.immutable.ArraySeq package impl { import sigma.compiler.ir.meta.ModuleInfo + import sigma.compiler.ir.wrappers.sigma.SigmaDsl import sigma.compiler.ir.{Base, GraphIRReflection, IRContext} import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} @@ -2327,4 +2329,4 @@ object SigmaDslModule extends ModuleInfo("sigma", "SigmaDsl") { } } -trait SigmaDslModule extends sigma.impl.SigmaDslDefs {self: IRContext =>} +trait SigmaDslModule extends SigmaDslDefs {self: IRContext =>} diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/impl/WSpecialPredefsImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/impl/WSpecialPredefsImpl.scala index a403aa0e5a..a468646ffb 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/impl/WSpecialPredefsImpl.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/impl/WSpecialPredefsImpl.scala @@ -1,7 +1,6 @@ package sigma.compiler.ir.wrappers.special import scala.language.{existentials, implicitConversions} -import scalan._ import sigma.compiler.ir.IRContext package impl { diff --git a/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala b/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala deleted file mode 100644 index d0dbb06e11..0000000000 --- a/sc/shared/src/main/scala/special/sigma/wrappers/WrappersModule.scala +++ /dev/null @@ -1,6 +0,0 @@ -package sigma.wrappers - -import sigma.compiler.ir.IRContext - -trait WrappersModule - extends sigma.compiler.ir.wrappers.WrappersModule { self: IRContext => } From 7c18eef30ecc58ea8a32a46e1654efcbf94b72ce Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 16 May 2024 12:52:26 +0100 Subject: [PATCH 58/65] refactor-ir-cake: wrappers moved to sigma.compiler.ir.wrappers package (part 3) --- .../main/scala/sigma/compiler/ir/GraphIRReflection.scala | 5 ++--- .../src/main/scala/sigma/compiler/ir/IRContext.scala | 4 +--- .../compiler/ir/wrappers/{scalan => sigma}/WRTypes.scala | 8 ++++---- .../ir/wrappers/{special => sigma}/WSpecialPredefs.scala | 9 ++++----- .../ir/wrappers/{scalan => sigma}/impl/WRTypesImpl.scala | 5 +++-- .../{special => sigma}/impl/WSpecialPredefsImpl.scala | 5 +++-- 6 files changed, 17 insertions(+), 19 deletions(-) rename sc/shared/src/main/scala/sigma/compiler/ir/wrappers/{scalan => sigma}/WRTypes.scala (66%) rename sc/shared/src/main/scala/sigma/compiler/ir/wrappers/{special => sigma}/WSpecialPredefs.scala (64%) rename sc/shared/src/main/scala/sigma/compiler/ir/wrappers/{scalan => sigma}/impl/WRTypesImpl.scala (95%) rename sc/shared/src/main/scala/sigma/compiler/ir/wrappers/{special => sigma}/impl/WSpecialPredefsImpl.scala (94%) diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala b/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala index 9482cdc048..5ef38a97ef 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala @@ -5,8 +5,7 @@ import sigma.data.RType import sigma.reflection.ReflectionData.registerClassEntry import sigma.reflection.{ReflectionData, mkConstructor, mkMethod} import sigma.compiler.ir.wrappers.{OptionWrapSpec, RTypeWrapSpec} -import sigma.compiler.ir.wrappers.scalan.WRTypes -import sigma.compiler.ir.wrappers.sigma.SigmaDsl +import sigma.compiler.ir.wrappers.sigma.{SigmaDsl, WRTypes, WSpecialPredefs} /** Registrations of reflection metadata for graph-ir module (see README.md). * Such metadata is only used on JS platform to support reflection-like interfaces of @@ -557,7 +556,7 @@ object GraphIRReflection { ) } - { val clazz = classOf[sigma.compiler.ir.wrappers.special.WSpecialPredefs#WSpecialPredefCompanion] + { val clazz = classOf[WSpecialPredefs#WSpecialPredefCompanion] val ctx = null.asInstanceOf[IRContext] // ok! type level only registerClassEntry(clazz, methods = Map( diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala index 123bc6f209..b32c69a430 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala @@ -5,9 +5,7 @@ import sigma.compiler.ir.primitives._ import sigma.data.{Nullable, RType} import sigma.util.MemoizedFunc import sigma.compiler.ir.wrappers.scala.WOptionsModule -import sigma.compiler.ir.wrappers.scalan.WRTypesModule -import sigma.compiler.ir.wrappers.sigma.{CollsModule, SigmaDslModule} -import sigma.compiler.ir.wrappers.special.WSpecialPredefsModule +import sigma.compiler.ir.wrappers.sigma.{CollsModule, SigmaDslModule, WRTypesModule, WSpecialPredefsModule} /** Aggregate cake with all inter-dependent modules assembled together. * Each instance of this class contains independent IR context, thus many diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/WRTypes.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WRTypes.scala similarity index 66% rename from sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/WRTypes.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WRTypes.scala index d83c538b8c..b4981dda4f 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/WRTypes.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WRTypes.scala @@ -1,5 +1,6 @@ -package sigma.compiler.ir.wrappers.scalan { - import sigma.compiler.ir.{Base, IRContext} +package sigma.compiler.ir.wrappers.sigma + +import sigma.compiler.ir.{Base, IRContext} trait WRTypes extends Base { self: IRContext => @@ -8,5 +9,4 @@ package sigma.compiler.ir.wrappers.scalan { def name: Ref[String] }; trait WRTypeCompanion - } -} \ No newline at end of file + } \ No newline at end of file diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/WSpecialPredefs.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WSpecialPredefs.scala similarity index 64% rename from sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/WSpecialPredefs.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WSpecialPredefs.scala index a1b9adeaa0..c7529d1ca6 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/WSpecialPredefs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WSpecialPredefs.scala @@ -1,11 +1,10 @@ -package sigma.compiler.ir.wrappers.special { - import scalan._ - import sigma.compiler.ir.{Base, IRContext} +package sigma.compiler.ir.wrappers.sigma + +import sigma.compiler.ir.{Base, IRContext} trait WSpecialPredefs extends Base { self: IRContext => trait WSpecialPredef extends Def[WSpecialPredef]; trait WSpecialPredefCompanion { def some[A](x: Ref[A]): Ref[WOption[A]]; } - } -} \ No newline at end of file + } \ No newline at end of file diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/impl/WRTypesImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WRTypesImpl.scala similarity index 95% rename from sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/impl/WRTypesImpl.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WRTypesImpl.scala index 1f7524bc3c..20d3bdf965 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scalan/impl/WRTypesImpl.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WRTypesImpl.scala @@ -1,4 +1,4 @@ -package sigma.compiler.ir.wrappers.scalan +package sigma.compiler.ir.wrappers.sigma import sigma.compiler.ir.IRContext import scala.language.{existentials, implicitConversions} @@ -9,6 +9,7 @@ import scala.collection.compat.immutable.ArraySeq package impl { import sigma.compiler.ir.meta.ModuleInfo + import sigma.compiler.ir.wrappers.sigma.WRTypes import sigma.compiler.ir.{Base, GraphIRReflection, IRContext} import sigma.reflection.{RClass, RMethod} @@ -118,4 +119,4 @@ object WRTypesModule extends ModuleInfo("wrappers.scalan", "WRTypes") { } } -trait WRTypesModule extends sigma.compiler.ir.wrappers.scalan.impl.WRTypesDefs {self: IRContext =>} +trait WRTypesModule extends sigma.compiler.ir.wrappers.sigma.impl.WRTypesDefs {self: IRContext =>} diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/impl/WSpecialPredefsImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WSpecialPredefsImpl.scala similarity index 94% rename from sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/impl/WSpecialPredefsImpl.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WSpecialPredefsImpl.scala index a468646ffb..4624a052ee 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/special/impl/WSpecialPredefsImpl.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WSpecialPredefsImpl.scala @@ -1,4 +1,4 @@ -package sigma.compiler.ir.wrappers.special +package sigma.compiler.ir.wrappers.sigma import scala.language.{existentials, implicitConversions} import sigma.compiler.ir.IRContext @@ -6,6 +6,7 @@ import sigma.compiler.ir.IRContext package impl { import sigma.compiler.ir.core.MutableLazy import sigma.compiler.ir.meta.ModuleInfo + import sigma.compiler.ir.wrappers.sigma.WSpecialPredefs import sigma.compiler.ir.{Base, GraphIRReflection, IRContext} import sigma.data.Nullable import sigma.reflection.RClass @@ -68,4 +69,4 @@ object WSpecialPredefsModule extends ModuleInfo("sigma.compiler.ir.wrappers.spec } } -trait WSpecialPredefsModule extends sigma.compiler.ir.wrappers.special.impl.WSpecialPredefsDefs {self: IRContext =>} +trait WSpecialPredefsModule extends sigma.compiler.ir.wrappers.sigma.impl.WSpecialPredefsDefs {self: IRContext =>} From 3dd55aa2f743a4720e5016c12b90623a5ce1ed2c Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 16 May 2024 15:18:19 +0100 Subject: [PATCH 59/65] refactor-ir-cake: SizeOf, CostOf removed from IR + more ScalaDocs --- .../scala/sigma/compiler/ir/AstGraphs.scala | 3 + .../sigma/compiler/ir/DefRewriting.scala | 5 + .../scala/sigma/compiler/ir/IRContext.scala | 3 +- .../scala/sigma/compiler/ir/MethodCalls.scala | 3 + .../scala/sigma/compiler/ir/Modules.scala | 3 + .../sigma/compiler/ir/ProgramGraphs.scala | 1 + .../sigma/compiler/ir/Transforming.scala | 5 + .../scala/sigma/compiler/ir/TypeDescs.scala | 4 + .../sigma/compiler/ir/primitives/Equal.scala | 1 + .../compiler/ir/primitives/Functions.scala | 5 +- .../compiler/ir/primitives/IfThenElse.scala | 1 + .../compiler/ir/primitives/LogicalOps.scala | 2 +- .../ir/primitives/MiscelaneousOps.scala | 41 +++++++++ .../compiler/ir/primitives/NumericOps.scala | 2 +- .../compiler/ir/primitives/OrderingOps.scala | 2 +- .../sigma/compiler/ir/primitives/Tuples.scala | 1 + .../compiler/ir/primitives/UnBinOps.scala | 1 + .../compiler/ir/primitives/UniversalOps.scala | 92 ------------------- 18 files changed, 75 insertions(+), 100 deletions(-) create mode 100644 sc/shared/src/main/scala/sigma/compiler/ir/primitives/MiscelaneousOps.scala delete mode 100644 sc/shared/src/main/scala/sigma/compiler/ir/primitives/UniversalOps.scala diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/AstGraphs.scala b/sc/shared/src/main/scala/sigma/compiler/ir/AstGraphs.scala index 7f798dc8f3..79a078ad19 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/AstGraphs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/AstGraphs.scala @@ -6,6 +6,9 @@ import sigma.data.emptyDBufferOfInt import scala.collection._ +/** Defines reusable abstraction of AstGraph, the base class for [[ProgramGraph]], + * [[Lambda]] and [[ThunkDef]]. + */ trait AstGraphs extends Transforming { self: IRContext => /** GraphNode is created for each symbol of the AstGraph and represents graph linking structure */ diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala b/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala index d7bb3a9e4d..62deffad31 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/DefRewriting.scala @@ -3,6 +3,11 @@ package sigma.compiler.ir import sigma.compiler.DelayInvokeException import sigma.data.ExactNumeric +/** Defines methods to implement graph rewriting optimization rules. + * The rules are defines as a series of pattern matching with stackable overriding. + * Can be mixed in into traits to add new rules (pattern cases) and call `super` + * implementation as a fallback case. + */ trait DefRewriting { scalan: IRContext => /** Rewrites given node to another equivalent node and returns its reference. diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala index b32c69a430..908e4ccb33 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala @@ -34,7 +34,7 @@ trait IRContext with LogicalOps with OrderingOps with Equal - with UniversalOps + with MiscelaneousOps with Functions with IfThenElse with Transforming @@ -90,6 +90,7 @@ trait IRContext def colBuilder: Ref[CollBuilder] + /** Type descriptor for [[WRType]] */ implicit lazy val wRTypeAnyElement: Elem[WRType[Any]] = wRTypeElement(AnyElement) /** During compilation represent a global value Global, see also SGlobal type. */ diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala b/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala index 5ecdb823a7..876f0e9d7e 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/MethodCalls.scala @@ -7,6 +7,9 @@ import sigma.util.CollectionUtil.TraversableOps import scala.annotation.{tailrec, unused} +/** Defines graph-ir representation of method calls, new object creation as well as the + * related utility methods. + */ trait MethodCalls extends Base { self: IRContext => def delayInvoke = throw new DelayInvokeException diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/Modules.scala b/sc/shared/src/main/scala/sigma/compiler/ir/Modules.scala index b14d4471d1..b58bacb5fb 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/Modules.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/Modules.scala @@ -2,6 +2,9 @@ package sigma.compiler.ir import sigma.compiler.ir.meta.ModuleInfo +/** Defines registration of IR modules. + * @see ModuleInfo + */ trait Modules extends Base { self: IRContext => /** Whether staged modules should be registered when cake is constructed and initialized. */ diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/ProgramGraphs.scala b/sc/shared/src/main/scala/sigma/compiler/ir/ProgramGraphs.scala index cd0384c996..6f447d97f9 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/ProgramGraphs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/ProgramGraphs.scala @@ -6,6 +6,7 @@ import sigma.util.GraphUtil import scala.collection.compat.immutable.ArraySeq +/** Defines implementation of [[ProgramGraph]] and related utilities. */ trait ProgramGraphs extends AstGraphs { self: IRContext => type PGraph = ProgramGraph diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/Transforming.scala b/sc/shared/src/main/scala/sigma/compiler/ir/Transforming.scala index 2412c756f1..876f2b5db1 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/Transforming.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/Transforming.scala @@ -7,6 +7,11 @@ import sigma.reflection.RMethod import java.util import scala.language.existentials +/** Implements utilites for graph transformation and rewriting. + * @see Pass + * @see MapTransformer + * @see Rewriter + */ trait Transforming { self: IRContext => /** Descriptor of a current compiler pass. diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/TypeDescs.scala b/sc/shared/src/main/scala/sigma/compiler/ir/TypeDescs.scala index 8d938029e3..366107edca 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/TypeDescs.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/TypeDescs.scala @@ -12,6 +12,10 @@ import scala.collection.immutable.ListMap import scala.collection.mutable import scala.language.implicitConversions +/** Defines [[Elem]] descriptor of types in IRContext together with related utilities. + * @see MethodDesc + * @see TypeDesc + */ abstract class TypeDescs extends Base { self: IRContext => /** Helper type case method. */ diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Equal.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Equal.scala index a778465e4c..ec27fff12b 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Equal.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Equal.scala @@ -4,6 +4,7 @@ import sigma.compiler.ir.{Base, IRContext} import scala.annotation.unused +/** Defines IR representation of equality operations. */ trait Equal extends Base { self: IRContext => /** Binary operation representing structural equality between arguments. */ case class Equals[A: Elem]() extends BinOp[A, Boolean]("==") { diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Functions.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Functions.scala index 04d3283c01..cd028de9b6 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Functions.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Functions.scala @@ -8,6 +8,7 @@ import sigma.util.GraphUtil import java.util import scala.language.implicitConversions +/** Defines IR representation of functions (Lambdas) and function application. */ trait Functions extends Base with ProgramGraphs { self: IRContext => implicit class LambdaOps[A,B](f: Ref[A => B]) { @@ -143,10 +144,6 @@ trait Functions extends Base with ProgramGraphs { self: IRContext => // emitDepGraph(roots, FileUtil.file(cwd, dir), "nested_lambda")(defaultGraphVizConfig) assert(false, s"Invalid nested lambda $l inside $this") } - case op @ OpCost(_, _, args, opCost) => - if (args.contains(opCost)) { - !!!(s"Invalid OpCost($op)") - } case _ => } } diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/IfThenElse.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/IfThenElse.scala index aee57ff1f9..0ce94a83c1 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/IfThenElse.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/IfThenElse.scala @@ -2,6 +2,7 @@ package sigma.compiler.ir.primitives import sigma.compiler.ir.{Base, IRContext} +/** Defines IR representation of conditional expressions `if (c) t else e`. */ trait IfThenElse extends Base { self: IRContext => /** If c then t else e construction with standard lazy evaluation of branches. diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/LogicalOps.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/LogicalOps.scala index 6420e46f5c..183b4a8e84 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/LogicalOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/LogicalOps.scala @@ -2,7 +2,7 @@ package sigma.compiler.ir.primitives import sigma.compiler.ir.{Base, IRContext} -/** Slice in Scala cake with definitions of logical operations. */ +/** Slice in IRContext cake with definitions of logical operations. */ trait LogicalOps extends Base { self: IRContext => /** Logical AND binary operation. */ val And = new EndoBinOp[Boolean]("&&") { diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/MiscelaneousOps.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/MiscelaneousOps.scala new file mode 100644 index 0000000000..633306da8c --- /dev/null +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/MiscelaneousOps.scala @@ -0,0 +1,41 @@ +package sigma.compiler.ir.primitives + +import sigma.compiler.ir.{Base, IRContext} + +trait MiscelaneousOps extends Base { self: IRContext => + case class HashCode[A]() extends UnOp[A, Int]("hashCode") { + override def applySeq(x: A): Int = x.hashCode + } + + case class ToString[A]() extends UnOp[A, String]("toString") { + override def applySeq(x: A): String = x.toString + } + + case class Downcast[From, To](input: Ref[From], eTo: Elem[To]) extends BaseDef[To]()(eTo) { + override def transform(t: Transformer) = Downcast(t(input), eTo) + } + case class Upcast[From, To](input: Ref[From], eTo: Elem[To]) extends BaseDef[To]()(eTo) { + override def transform(t: Transformer) = Upcast(t(input), eTo) + } + + def downcast[To:Elem](value: Ref[_]): Ref[To] = Downcast(value, element[To]) + def upcast[To:Elem](value: Ref[_]): Ref[To] = Upcast(value, element[To]) + + implicit class RepUniversalOps[A](x: Ref[A]) { + def hashCodeRep: Ref[Int] = HashCode[A]().apply(x) + def toStringRep = ToString[A]().apply(x) + } + + case class Convert[From,To](eFrom: Elem[From], eTo: Elem[To], x: Ref[Def[_]], conv: Ref[From => To]) + extends BaseDef[To]()(eTo) { + override def transform(t: Transformer) = Convert(eFrom, eTo, t(x), t(conv)) + } + + def tryConvert[From, To](eFrom: Elem[From], eTo: Elem[To], x: Ref[Def[_]], conv: Ref[From => To]): Ref[To] = { + if (x.elem <:< eFrom) + conv(asRep[From](x)) + else + Convert(eFrom, eTo, x, conv) + } + +} diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/NumericOps.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/NumericOps.scala index d22140870a..4e732bbb5f 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/NumericOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/NumericOps.scala @@ -3,7 +3,7 @@ package sigma.compiler.ir.primitives import sigma.compiler.ir.{Base, IRContext} import sigma.data.{ExactIntegral, ExactNumeric} -/** Slice in Scala cake with definitions of numeric operations. */ +/** Slice in IRContext cake with definitions of numeric operations. */ trait NumericOps extends Base { self: IRContext => /** Extension methods over `Ref[T]` where T is instance of ExactNumeric type-class. */ diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/OrderingOps.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/OrderingOps.scala index ea2b9f5a34..be8f934706 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/OrderingOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/OrderingOps.scala @@ -5,7 +5,7 @@ import sigma.data.ExactOrdering import scala.language.implicitConversions -/** Slice in Scala cake with definitions of comparison operations. */ +/** Slice in IRContext cake with definitions of comparison operations. */ trait OrderingOps extends Base { self: IRContext => implicit def repOrderingToOrderingOps[T](x: Ref[T])(implicit n: ExactOrdering[T]) = new OrderingOpsCls(x) implicit def OrderingToOrderingOps[T](x: T)(implicit n: ExactOrdering[T], et: Elem[T]) = new OrderingOpsCls(toRep(x)) diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Tuples.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Tuples.scala index b6b9861ac7..59a5d810b9 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Tuples.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/Tuples.scala @@ -9,6 +9,7 @@ import sigma.data.AVHashMap import scala.language.implicitConversions +/** Slice in [[IRContext]] cake with definitions of pairs and tuples. */ trait Tuples extends Base { self: IRContext => object Pair { def apply[A, B](a: Ref[A], b: Ref[B]) = zipPair[A, B]((a, b)) diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/UnBinOps.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/UnBinOps.scala index a3a92e2f10..23f8bc3800 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/UnBinOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/UnBinOps.scala @@ -2,6 +2,7 @@ package sigma.compiler.ir.primitives import sigma.compiler.ir.{Base, IRContext} +/** Defines IR representation of unary and binary operations. */ trait UnBinOps extends Base { self: IRContext => /** Base class for descriptors of unary operations. */ diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/UniversalOps.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/UniversalOps.scala deleted file mode 100644 index a5852647ac..0000000000 --- a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/UniversalOps.scala +++ /dev/null @@ -1,92 +0,0 @@ -package sigma.compiler.ir.primitives - -import sigma.compiler.ir.{Base, IRContext} - -trait UniversalOps extends Base { self: IRContext => - case class HashCode[A]() extends UnOp[A, Int]("hashCode") { - override def applySeq(x: A): Int = x.hashCode - } - - case class ToString[A]() extends UnOp[A, String]("toString") { - override def applySeq(x: A): String = x.toString - } - - /** Represents calculation of size in bytes of the given value. - * The descriptor value.elem can be used to decompose value into components. - */ - case class SizeOf[T](value: Ref[T]) extends BaseDef[Long] { - override def transform(t: Transformer) = SizeOf(t(value)) - } - - def sizeOf[T](value: Ref[T]): Ref[Long] = SizeOf(value) - - /** Special graph node to represent accumulation of the operation costs. - * In general, due to node sharing it is incorrect to just sum up all the `args` costs - * and add `resCost` to that value. - * Example:
- * - * val x = .. - * val y = op1(x) - * val z = op2(x) - * val res = op3(y, z) - * - * The naive summation will lead to the cost of x` is accumulated both into `cost of y` - * and into `cost of z`, so in the `cost of res` it is accumulated twice. - * To avoid this problem OpCost nodes require special handling in during evaluation. - * - * @param lambdaVar the variable of the lambda in which scope this node is created. - * This makes this node belong to the lambda body, even if it doesn't - * otherwise depend on lambda argument. - * @param costedValueId The id of the node for which this node represents cost - * @param args costs of the arguments, which are here represent dependency information. - * @param opCost operation cost, which should be added to the current scope accumulated cost - */ - case class OpCost(lambdaVar: Sym, costedValueId: Int, args: Seq[Ref[Int]], opCost: Ref[Int]) extends BaseDef[Int] { - /** When this node is mirrored (as part of mirrorLambda) we apply transformer t for all arguments - * with standard data flow semantics. - * However this is not correct to do for lambdaVar. - * Instead we use current lambda from the top of the stack, which is always points to the most nested - * lambda. - */ - override def transform(t: Transformer) = OpCost(lambdaStack.head.x, costedValueId, t(args), t(opCost)) - } - - def opCost(costedValue: Sym, args: Seq[Ref[Int]], opCost: Ref[Int]): Ref[Int] = { - val id = costedValue.node.nodeId - val lamVar = lambdaStack.head.x - OpCost(lamVar, id, args, opCost) - } - - def assertValueIdForOpCost[A,B](value: Ref[A], cost: Ref[B]): Unit = { - assert(if (cost.node.isInstanceOf[OpCost]) value.node.nodeId == cost.node.asInstanceOf[OpCost].costedValueId else true, - s"${value.node} value node id (${value.node.nodeId}) is not equal to OpCost.costedValueId (${cost.node.asInstanceOf[OpCost].costedValueId})") - } - - case class Downcast[From, To](input: Ref[From], eTo: Elem[To]) extends BaseDef[To]()(eTo) { - override def transform(t: Transformer) = Downcast(t(input), eTo) - } - case class Upcast[From, To](input: Ref[From], eTo: Elem[To]) extends BaseDef[To]()(eTo) { - override def transform(t: Transformer) = Upcast(t(input), eTo) - } - - def downcast[To:Elem](value: Ref[_]): Ref[To] = Downcast(value, element[To]) - def upcast[To:Elem](value: Ref[_]): Ref[To] = Upcast(value, element[To]) - - implicit class RepUniversalOps[A](x: Ref[A]) { - def hashCodeRep: Ref[Int] = HashCode[A]().apply(x) - def toStringRep = ToString[A]().apply(x) - } - - case class Convert[From,To](eFrom: Elem[From], eTo: Elem[To], x: Ref[Def[_]], conv: Ref[From => To]) - extends BaseDef[To]()(eTo) { - override def transform(t: Transformer) = Convert(eFrom, eTo, t(x), t(conv)) - } - - def tryConvert[From, To](eFrom: Elem[From], eTo: Elem[To], x: Ref[Def[_]], conv: Ref[From => To]): Ref[To] = { - if (x.elem <:< eFrom) - conv(asRep[From](x)) - else - Convert(eFrom, eTo, x, conv) - } - -} From f56df6a148a08fe0558141df93762742f6bc082a Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Thu, 16 May 2024 16:08:20 +0100 Subject: [PATCH 60/65] refactor-ir-cake: removed WSpecialPredefs.scala --- .../sigma/compiler/ir/GraphIRReflection.scala | 12 +--- .../scala/sigma/compiler/ir/IRContext.scala | 13 +--- .../sigma/compiler/ir/TreeBuilding.scala | 2 +- .../{MiscelaneousOps.scala => MiscOps.scala} | 5 +- .../compiler/ir/wrappers/scala/WOptions.scala | 1 + .../ir/wrappers/scala/impl/WOptionsImpl.scala | 1 + .../ir/wrappers/sigma/SigmaDslUnit.scala | 1 + .../compiler/ir/wrappers/sigma/WRTypes.scala | 1 + .../ir/wrappers/sigma/WSpecialPredefs.scala | 10 --- .../ir/wrappers/sigma/impl/CollsImpl.scala | 3 +- .../ir/wrappers/sigma/impl/SigmaDslImpl.scala | 1 + .../ir/wrappers/sigma/impl/WRTypesImpl.scala | 1 + .../sigma/impl/WSpecialPredefsImpl.scala | 72 ------------------- .../wrappers/WSpecialPredefTests.scala | 23 ------ 14 files changed, 16 insertions(+), 130 deletions(-) rename sc/shared/src/main/scala/sigma/compiler/ir/primitives/{MiscelaneousOps.scala => MiscOps.scala} (89%) delete mode 100644 sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WSpecialPredefs.scala delete mode 100644 sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WSpecialPredefsImpl.scala delete mode 100644 sc/shared/src/test/scala/special/wrappers/WSpecialPredefTests.scala diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala b/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala index 5ef38a97ef..69736a0224 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/GraphIRReflection.scala @@ -5,7 +5,7 @@ import sigma.data.RType import sigma.reflection.ReflectionData.registerClassEntry import sigma.reflection.{ReflectionData, mkConstructor, mkMethod} import sigma.compiler.ir.wrappers.{OptionWrapSpec, RTypeWrapSpec} -import sigma.compiler.ir.wrappers.sigma.{SigmaDsl, WRTypes, WSpecialPredefs} +import sigma.compiler.ir.wrappers.sigma.{SigmaDsl, WRTypes} /** Registrations of reflection metadata for graph-ir module (see README.md). * Such metadata is only used on JS platform to support reflection-like interfaces of @@ -556,16 +556,6 @@ object GraphIRReflection { ) } - { val clazz = classOf[WSpecialPredefs#WSpecialPredefCompanion] - val ctx = null.asInstanceOf[IRContext] // 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]]) - } - ) - ) - } { val clazz = classOf[OptionWrapSpec] registerClassEntry(clazz, diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala index 908e4ccb33..c60bc0882f 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/IRContext.scala @@ -5,7 +5,7 @@ import sigma.compiler.ir.primitives._ import sigma.data.{Nullable, RType} import sigma.util.MemoizedFunc import sigma.compiler.ir.wrappers.scala.WOptionsModule -import sigma.compiler.ir.wrappers.sigma.{CollsModule, SigmaDslModule, WRTypesModule, WSpecialPredefsModule} +import sigma.compiler.ir.wrappers.sigma.{CollsModule, SigmaDslModule, WRTypesModule} /** Aggregate cake with all inter-dependent modules assembled together. * Each instance of this class contains independent IR context, thus many @@ -34,7 +34,7 @@ trait IRContext with LogicalOps with OrderingOps with Equal - with MiscelaneousOps + with MiscOps with Functions with IfThenElse with Transforming @@ -46,7 +46,6 @@ trait IRContext with SigmaDslModule with TreeBuilding with GraphBuilding - with WSpecialPredefsModule with WOptionsModule with WRTypesModule { @@ -54,7 +53,6 @@ trait IRContext import CollBuilder._ import WOption._ import WRType._ - import WSpecialPredef._ /** Pass configuration which is used to turn-off constant propagation. * USED IN TESTS ONLY. @@ -74,11 +72,7 @@ trait IRContext _liftElemMemo(eT).asInstanceOf[Ref[WRType[T]]] // asRep cannot be used for AnyRef } - private val _specialPredef: LazyRep[WSpecialPredefCompanionCtor] = MutableLazy(RWSpecialPredef.value) - def specialPredef: Ref[WSpecialPredefCompanionCtor] = _specialPredef.value - override protected def onReset(): Unit = { - _specialPredef.reset() _liftElemMemo.reset() super.onReset() } @@ -86,7 +80,6 @@ trait IRContext val CM = CollMethods private val CBM = CollBuilderMethods private val WOptionM = WOptionMethods - private val SPCM = WSpecialPredefCompanionMethods def colBuilder: Ref[CollBuilder] @@ -150,8 +143,6 @@ trait IRContext } case WOptionM.getOrElse(opt, _) => opt.node match { - // Rule: Some(x).getOrElse(_) ==> x - case SPCM.some(x) => x case WOptionConst(Some(x), lA) => lA.lift(x) case _ => super.rewriteDef(d) } diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/TreeBuilding.scala b/sc/shared/src/main/scala/sigma/compiler/ir/TreeBuilding.scala index 4c54ef711b..725e3b1d19 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/TreeBuilding.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/TreeBuilding.scala @@ -128,7 +128,7 @@ trait TreeBuilding extends Base { IR: IRContext => */ object IsInternalDef { def unapply(d: Def[_]): Option[Def[_]] = d match { - case _: SigmaDslBuilder | _: CollBuilder | _: WSpecialPredefCompanion => Some(d) + case _: SigmaDslBuilder | _: CollBuilder => Some(d) case _ => None } } diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/MiscelaneousOps.scala b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/MiscOps.scala similarity index 89% rename from sc/shared/src/main/scala/sigma/compiler/ir/primitives/MiscelaneousOps.scala rename to sc/shared/src/main/scala/sigma/compiler/ir/primitives/MiscOps.scala index 633306da8c..58382a279c 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/primitives/MiscelaneousOps.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/primitives/MiscOps.scala @@ -2,7 +2,10 @@ package sigma.compiler.ir.primitives import sigma.compiler.ir.{Base, IRContext} -trait MiscelaneousOps extends Base { self: IRContext => +/** Defines IR representation of miscellaneous operations that doesn't fit into any + * specific category. + */ +trait MiscOps extends Base { self: IRContext => case class HashCode[A]() extends UnOp[A, Int]("hashCode") { override def applySeq(x: A): Int = x.hashCode } diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/WOptions.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/WOptions.scala index d6c0971214..2ed1237e6b 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/WOptions.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/WOptions.scala @@ -1,6 +1,7 @@ package sigma.compiler.ir.wrappers.scala { import sigma.compiler.ir.{Base, IRContext} + /** Defines IR representation of Option type. */ trait WOptions extends Base { self: IRContext => trait WOption[A] extends Def[WOption[A]] { implicit def eA: Elem[A]; diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/impl/WOptionsImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/impl/WOptionsImpl.scala index 307e380a76..514415d2bd 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/impl/WOptionsImpl.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/scala/impl/WOptionsImpl.scala @@ -13,6 +13,7 @@ package impl { import sigma.reflection.{RClass, RMethod} // Abs ----------------------------------- +/** IR representation of Option type and methods. */ trait WOptionsDefs extends Base with WOptions { self: IRContext => diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/SigmaDslUnit.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/SigmaDslUnit.scala index 7b9d499c7e..2a6a341686 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/SigmaDslUnit.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/SigmaDslUnit.scala @@ -3,6 +3,7 @@ package sigma.compiler.ir.wrappers.sigma import scalan._ import sigma.compiler.ir.{Base, IRContext} + /** IR representation of ErgoScript (Sigma) language types and methods. */ trait SigmaDsl extends Base { self: IRContext => trait BigInt extends Def[BigInt] { def add(that: Ref[BigInt]): Ref[BigInt]; diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WRTypes.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WRTypes.scala index b4981dda4f..0bd2b47e5b 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WRTypes.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WRTypes.scala @@ -3,6 +3,7 @@ package sigma.compiler.ir.wrappers.sigma import sigma.compiler.ir.{Base, IRContext} + /** IR representation of RType. */ trait WRTypes extends Base { self: IRContext => trait WRType[A] extends Def[WRType[A]] { implicit def eA: Elem[A]; diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WSpecialPredefs.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WSpecialPredefs.scala deleted file mode 100644 index c7529d1ca6..0000000000 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/WSpecialPredefs.scala +++ /dev/null @@ -1,10 +0,0 @@ -package sigma.compiler.ir.wrappers.sigma - -import sigma.compiler.ir.{Base, IRContext} - - trait WSpecialPredefs extends Base { self: IRContext => - trait WSpecialPredef extends Def[WSpecialPredef]; - trait WSpecialPredefCompanion { - def some[A](x: Ref[A]): Ref[WOption[A]]; - } - } \ No newline at end of file diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/CollsImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/CollsImpl.scala index fd3f72a642..0a18ea586a 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/CollsImpl.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/CollsImpl.scala @@ -12,7 +12,8 @@ package impl { import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} - // Abs ----------------------------------- +// Abs ----------------------------------- +/** Implementation part of IR represenation related to Coll type and methods. */ trait CollsDefs extends Base with Colls { self: IRContext => diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/SigmaDslImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/SigmaDslImpl.scala index 201c974512..c113cb7de3 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/SigmaDslImpl.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/SigmaDslImpl.scala @@ -14,6 +14,7 @@ package impl { import sigma.data.{Nullable, RType} import sigma.reflection.{RClass, RMethod} +/** Implementation part of IR represenation related to Sigma types and methods. */ // Abs ----------------------------------- trait SigmaDslDefs extends Base with SigmaDsl { self: IRContext => diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WRTypesImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WRTypesImpl.scala index 20d3bdf965..beddba3085 100644 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WRTypesImpl.scala +++ b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WRTypesImpl.scala @@ -13,6 +13,7 @@ package impl { import sigma.compiler.ir.{Base, GraphIRReflection, IRContext} import sigma.reflection.{RClass, RMethod} +/** Implementation of IR nodes related to [[RType]]. */ // Abs ----------------------------------- trait WRTypesDefs extends Base with WRTypes { self: IRContext => diff --git a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WSpecialPredefsImpl.scala b/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WSpecialPredefsImpl.scala deleted file mode 100644 index 4624a052ee..0000000000 --- a/sc/shared/src/main/scala/sigma/compiler/ir/wrappers/sigma/impl/WSpecialPredefsImpl.scala +++ /dev/null @@ -1,72 +0,0 @@ -package sigma.compiler.ir.wrappers.sigma - -import scala.language.{existentials, implicitConversions} -import sigma.compiler.ir.IRContext - -package impl { - import sigma.compiler.ir.core.MutableLazy - import sigma.compiler.ir.meta.ModuleInfo - import sigma.compiler.ir.wrappers.sigma.WSpecialPredefs - import sigma.compiler.ir.{Base, GraphIRReflection, IRContext} - import sigma.data.Nullable - import sigma.reflection.RClass - - // Abs ----------------------------------- -trait WSpecialPredefsDefs extends Base with WSpecialPredefs { - self: IRContext => - - registerModule(WSpecialPredefsModule) - -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() - } - -} - -object WSpecialPredefsModule extends ModuleInfo("sigma.compiler.ir.wrappers.special", "WSpecialPredefs") { - val reflection = GraphIRReflection -} -} - -trait WSpecialPredefsModule extends sigma.compiler.ir.wrappers.sigma.impl.WSpecialPredefsDefs {self: IRContext =>} diff --git a/sc/shared/src/test/scala/special/wrappers/WSpecialPredefTests.scala b/sc/shared/src/test/scala/special/wrappers/WSpecialPredefTests.scala deleted file mode 100644 index 75123cf5bd..0000000000 --- a/sc/shared/src/test/scala/special/wrappers/WSpecialPredefTests.scala +++ /dev/null @@ -1,23 +0,0 @@ -package special.wrappers - - -import scala.language.reflectiveCalls - -class WSpecialPredefTests extends WrappersTests { - - lazy val ctx = new WrappersCtx - import ctx._ - import WSpecialPredef._ - - lazy val SPCM = WSpecialPredefCompanionMethods - - test("some") { - val x: Ref[Int] = 10 - val opt = RWSpecialPredef.some(x) - opt match { - case SPCM.some(_x) => _x shouldBe x - case _ => assert(false) - } - } - -} From 12a958ce2467635ce1ddb33feb6f42817255b0f4 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Fri, 17 May 2024 18:34:10 +0300 Subject: [PATCH 61/65] Option[T] (de)serialization --- .../src/main/scala/sigma/ast/SType.scala | 3 ++- .../serialization/CoreDataSerializer.scala | 10 ++++++++++ .../DataSerializerSpecification.scala | 18 ++++++++++++++++-- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/core/shared/src/main/scala/sigma/ast/SType.scala b/core/shared/src/main/scala/sigma/ast/SType.scala index f75cbc9e8b..6656ede3c9 100644 --- a/core/shared/src/main/scala/sigma/ast/SType.scala +++ b/core/shared/src/main/scala/sigma/ast/SType.scala @@ -602,7 +602,8 @@ object STypeApply { /** Type description of optional values. Instances of `Option` * are either constructed by `Some` or by `None` constructors. */ case class SOption[ElemType <: SType](elemType: ElemType) extends SProduct with SGenericType { - override type WrappedType = Option[ElemType#WrappedType] + type ElemWrappedType = ElemType#WrappedType + override type WrappedType = Option[ElemWrappedType] override val typeCode: TypeCode = SOption.OptionTypeCode override def toString = s"Option[$elemType]" override def toTermString: String = s"Option[${elemType.toTermString}]" diff --git a/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala b/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala index 479b199da5..7b4ec81c7d 100644 --- a/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala +++ b/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala @@ -68,6 +68,12 @@ class CoreDataSerializer { i += 1 } + case SOption(elemType) => + val o = v.asInstanceOf[Option[elemType.WrappedType]] + w.putOption(o){case (w, v) => + serialize(v, elemType, w) + } + // TODO v6.0 (3h): support Option[T] (see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/659) case _ => CheckSerializableTypeCode(tpe.typeCode) @@ -118,6 +124,10 @@ class CoreDataSerializer { }.toArray[Any] val coll = Colls.fromArray(arr)(sigma.AnyType) Evaluation.toDslTuple(coll, tuple) + case tOption: SOption[_] => + r.getOption[tOption.ElemWrappedType] { + deserialize(tOption.elemType, r).asInstanceOf[tOption.ElemWrappedType] + } case t => CheckSerializableTypeCode(t.typeCode) throw new SerializerException(s"Not defined DataSerializer for type $t") diff --git a/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala index 7cd9967e54..3ddaffde89 100644 --- a/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala @@ -3,7 +3,7 @@ package sigma.serialization import java.math.BigInteger import org.ergoplatform.ErgoBox import org.scalacheck.Arbitrary._ -import sigma.data.{DataValueComparer, RType, SigmaBoolean, TupleColl} +import sigma.data.{DataValueComparer, OptionType, RType, SigmaBoolean, TupleColl} import sigma.ast.SCollection.SByteArray import sigmastate.eval._ import sigma.{AvlTree, Colls, Evaluation} @@ -14,7 +14,7 @@ import sigma.Extensions.ArrayOps import sigma.crypto.EcPointType import sigma.eval.SigmaDsl import sigma.util.Extensions.{BigIntegerOps, EcpOps, SigmaBooleanOps} -import sigmastate.interpreter.{CostAccumulator, CErgoTreeEvaluator} +import sigmastate.interpreter.{CErgoTreeEvaluator, CostAccumulator} import sigmastate.interpreter.CErgoTreeEvaluator.DefaultProfiler import sigmastate.utils.Helpers @@ -92,6 +92,19 @@ class DataSerializerSpecification extends SerializationSpecification { } } + def testOption[T <: SType](tpe: T) = { + implicit val wWrapped: Gen[T#WrappedType] = wrappedTypeGen(tpe) + val tT = Evaluation.stypeToRType(tpe) + forAll { in: T#WrappedType => + roundtrip[SType](Some(in).asWrappedType, SOption(tpe)) + roundtrip[SOption[T]](None, SOption(tpe)) + roundtrip[SOption[T]](Some(in), SOption(tpe)) + roundtrip[SOption[SCollection[T]]](Some(Colls.fromItems(in)(tT)), SOption(SCollectionType(tpe))) + roundtrip[SCollection[SOption[T]]](Colls.fromItems(Option(in), None.asInstanceOf[Option[T#WrappedType]])(OptionType(tT)), SCollectionType(SOption(tpe))) + roundtrip[SOption[SOption[T]]](Some(Some(in)), SOption(SOption(tpe))) + } + } + property("Data serialization round trip") { forAll { x: Byte => roundtrip[SByte.type](x, SByte) } forAll { x: Boolean => roundtrip[SBoolean.type](x, SBoolean) } @@ -105,6 +118,7 @@ class DataSerializerSpecification extends SerializationSpecification { forAll { x: Array[Byte] => roundtrip[SByteArray](x.toColl, SByteArray) } forAll { t: SPredefType => testCollection(t) } forAll { t: SPredefType => testTuples(t) } + forAll { t: SPredefType => testOption(t) } } property("Should check limits and fail") { From 4f2fb23cef3165625f7fb9224e412691c91d54f0 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Fri, 17 May 2024 18:44:03 +0300 Subject: [PATCH 62/65] versioning and tests --- .../serialization/CoreDataSerializer.scala | 4 +-- .../DataSerializerSpecification.scala | 27 +++++++++++++------ 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala b/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala index 7b4ec81c7d..b8174aa31e 100644 --- a/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala +++ b/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala @@ -68,7 +68,7 @@ class CoreDataSerializer { i += 1 } - case SOption(elemType) => + case SOption(elemType) if VersionContext.current.isV6SoftForkActivated => val o = v.asInstanceOf[Option[elemType.WrappedType]] w.putOption(o){case (w, v) => serialize(v, elemType, w) @@ -124,7 +124,7 @@ class CoreDataSerializer { }.toArray[Any] val coll = Colls.fromArray(arr)(sigma.AnyType) Evaluation.toDslTuple(coll, tuple) - case tOption: SOption[_] => + case tOption: SOption[_] if VersionContext.current.isV6SoftForkActivated => r.getOption[tOption.ElemWrappedType] { deserialize(tOption.elemType, r).asInstanceOf[tOption.ElemWrappedType] } diff --git a/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala index 3ddaffde89..18c1f6a092 100644 --- a/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala @@ -6,7 +6,7 @@ import org.scalacheck.Arbitrary._ import sigma.data.{DataValueComparer, OptionType, RType, SigmaBoolean, TupleColl} import sigma.ast.SCollection.SByteArray import sigmastate.eval._ -import sigma.{AvlTree, Colls, Evaluation} +import sigma.{AvlTree, Colls, Evaluation, VersionContext} import sigma.ast.SType.AnyOps import sigma.ast._ import org.scalacheck.Gen @@ -95,13 +95,24 @@ class DataSerializerSpecification extends SerializationSpecification { def testOption[T <: SType](tpe: T) = { implicit val wWrapped: Gen[T#WrappedType] = wrappedTypeGen(tpe) val tT = Evaluation.stypeToRType(tpe) - forAll { in: T#WrappedType => - roundtrip[SType](Some(in).asWrappedType, SOption(tpe)) - roundtrip[SOption[T]](None, SOption(tpe)) - roundtrip[SOption[T]](Some(in), SOption(tpe)) - roundtrip[SOption[SCollection[T]]](Some(Colls.fromItems(in)(tT)), SOption(SCollectionType(tpe))) - roundtrip[SCollection[SOption[T]]](Colls.fromItems(Option(in), None.asInstanceOf[Option[T#WrappedType]])(OptionType(tT)), SCollectionType(SOption(tpe))) - roundtrip[SOption[SOption[T]]](Some(Some(in)), SOption(SOption(tpe))) + + an[Exception] should be thrownBy ( + VersionContext.withVersions((VersionContext.V6SoftForkVersion - 1).toByte, 1) { + forAll { in: T#WrappedType => + roundtrip[SType](Some(in).asWrappedType, SOption(tpe)) + roundtrip[SOption[SCollection[T]]](Some(Colls.fromItems(in)(tT)), SOption(SCollectionType(tpe))) + } + }) + + VersionContext.withVersions(VersionContext.V6SoftForkVersion, 1) { + forAll { in: T#WrappedType => + roundtrip[SType](Some(in).asWrappedType, SOption(tpe)) + roundtrip[SOption[T]](None, SOption(tpe)) + roundtrip[SOption[T]](Some(in), SOption(tpe)) + roundtrip[SOption[SCollection[T]]](Some(Colls.fromItems(in)(tT)), SOption(SCollectionType(tpe))) + roundtrip[SCollection[SOption[T]]](Colls.fromItems(Option(in), None.asInstanceOf[Option[T#WrappedType]])(OptionType(tT)), SCollectionType(SOption(tpe))) + roundtrip[SOption[SOption[T]]](Some(Some(in)), SOption(SOption(tpe))) + } } } From 553bee8eeace5c90d2e7fd30a73a276b01f66d7b Mon Sep 17 00:00:00 2001 From: Alexander Slesarenko Date: Tue, 21 May 2024 11:18:18 +0200 Subject: [PATCH 63/65] refactor-ir-cake: add ScalaDoc --- .../test/scala/sigmastate/ReflectionGenerator.scala | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala b/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala index 324542505e..dd5262e700 100644 --- a/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala +++ b/sc/jvm/src/test/scala/sigmastate/ReflectionGenerator.scala @@ -5,6 +5,17 @@ import sigma.reflection._ import scala.annotation.unused import scala.collection.mutable +/** Generates code for registering classes in the ReflectionData. + * It is not used in the runtime. + * + * The generated invocations of `registerClassEntry`, `mkMethod`, `mkConstructor` may + * require manual adjustments. + * + * It uses [[sigma.reflection.Platform.unknownClasses]] to collect classes which were + * accessed during runtime + * + * @see [[ReflectionData]] + */ object ReflectionGenerator { def normalizeName(name: String): String = { From bc71b2f27006ce0069c9179626403496aa4a58cd Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Mon, 3 Jun 2024 15:02:08 +0300 Subject: [PATCH 64/65] todo removed, tests improved --- .../src/main/scala/sigma/serialization/CoreDataSerializer.scala | 1 - .../scala/sigma/serialization/DataSerializerSpecification.scala | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala b/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala index b8174aa31e..233494392a 100644 --- a/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala +++ b/core/shared/src/main/scala/sigma/serialization/CoreDataSerializer.scala @@ -74,7 +74,6 @@ class CoreDataSerializer { serialize(v, elemType, w) } - // TODO v6.0 (3h): support Option[T] (see https://github.com/ScorexFoundation/sigmastate-interpreter/issues/659) case _ => CheckSerializableTypeCode(tpe.typeCode) throw new SerializerException(s"Don't know how to serialize ($v, $tpe)") diff --git a/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala index 18c1f6a092..a42cf2c9e3 100644 --- a/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala @@ -111,6 +111,7 @@ class DataSerializerSpecification extends SerializationSpecification { roundtrip[SOption[T]](Some(in), SOption(tpe)) roundtrip[SOption[SCollection[T]]](Some(Colls.fromItems(in)(tT)), SOption(SCollectionType(tpe))) roundtrip[SCollection[SOption[T]]](Colls.fromItems(Option(in), None.asInstanceOf[Option[T#WrappedType]])(OptionType(tT)), SCollectionType(SOption(tpe))) + roundtrip[SOption[SOption[T]]](None, SOption(SOption(tpe))) roundtrip[SOption[SOption[T]]](Some(Some(in)), SOption(SOption(tpe))) } } From ea91fae58992c1a162e0343e30ceb5eea3aaac06 Mon Sep 17 00:00:00 2001 From: Alexander Chepurnoy Date: Mon, 3 Jun 2024 22:26:59 +0300 Subject: [PATCH 65/65] Some(None) test --- .../scala/sigma/serialization/DataSerializerSpecification.scala | 1 + 1 file changed, 1 insertion(+) diff --git a/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala b/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala index a42cf2c9e3..2d9da3a87e 100644 --- a/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala +++ b/interpreter/shared/src/test/scala/sigma/serialization/DataSerializerSpecification.scala @@ -113,6 +113,7 @@ class DataSerializerSpecification extends SerializationSpecification { roundtrip[SCollection[SOption[T]]](Colls.fromItems(Option(in), None.asInstanceOf[Option[T#WrappedType]])(OptionType(tT)), SCollectionType(SOption(tpe))) roundtrip[SOption[SOption[T]]](None, SOption(SOption(tpe))) roundtrip[SOption[SOption[T]]](Some(Some(in)), SOption(SOption(tpe))) + roundtrip[SOption[SOption[T]]](Some(None), SOption(SOption(tpe))) } } }