Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(compiler): Reimplement noXor compiler flag [LNG-347] #1096

Merged
merged 10 commits into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion api/api/.js/src/main/scala/api/AquaAPI.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import aqua.io.*
import aqua.js.{FunctionDefJs, ServiceDefJs, VarJson}
import aqua.logging.{LogFormatter, LogLevels}
import aqua.model.AquaContext
import aqua.model.transform.{Transform, TransformConfig}
import aqua.parser.lexer.{LiteralToken, Token}
import aqua.parser.{ArrowReturnError, BlockIndentError, LexerError, ParserError}
import aqua.raw.ops.Call
Expand Down
1 change: 0 additions & 1 deletion api/api/.js/src/main/scala/api/types/InputTypes.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package api.types
import aqua.api.AquaAPIConfig
import aqua.api.TargetType.*
import aqua.js.{FunctionDefJs, ServiceDefJs}
import aqua.model.transform.TransformConfig

import cats.data.Validated.{invalidNec, validNec}
import cats.data.{Chain, NonEmptyChain, Validated, ValidatedNec}
Expand Down
5 changes: 3 additions & 2 deletions api/api/.jvm/src/main/scala/aqua/api/Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ object Test extends IOApp.Simple {
.compilePath(
"./aqua-src/antithesis.aqua",
Imports.fromMap(Map("/" -> Map("" -> List("./aqua")))),
AquaAPIConfig(targetType = TypeScriptType),
AquaAPIConfig(targetType = TypeScriptType, noXor = true),
TypeScriptBackend(false, "IFluenceClient$$")
).timed
)
.timed
.flatMap { case (duration, res) =>
println("Compilation time: " + duration.toMillis)
val (warnings, result) = res.value.run
Expand Down
8 changes: 5 additions & 3 deletions api/api/src/main/scala/aqua/api/APICompilation.scala
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,16 @@ object APICompilation {
LogLevels.levelFromString(aquaConfig.logLevel),
Constants.parse(aquaConfig.constants)
).tupled.toResult.flatTraverse { case (level, constants) =>
val transformConfig = aquaConfig.getTransformConfig.copy(constants = constants)
val transformConfig = aquaConfig.getTransformConfig
val config = aquaConfig.getCompilerConfig.copy(constants = constants)

LogFormatter.initLogger(Some(level))

new FuncCompiler[IO](
Some(RelativePath(Path(pathStr))),
imports.toIO,
transformConfig
transformConfig,
config
).compile().map { contextV =>
for {
context <- contextV.toResult
Expand Down Expand Up @@ -140,7 +142,7 @@ object APICompilation {
LogFormatter.initLogger(Some(level))

val transformConfig = aquaConfig.getTransformConfig
val config = AquaCompilerConf(constants ++ transformConfig.constantsList)
val config = aquaConfig.getCompilerConfig.copy(constants = constants)

CompilerAPI
.compile[IO, AquaFileError, FileModuleId, FileSpan.F](
Expand Down
14 changes: 12 additions & 2 deletions api/api/src/main/scala/aqua/api/AquaAPIConfig.scala
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
package aqua.api

import aqua.compiler.AquaCompilerConf
import aqua.model.transform.TransformConfig

enum TargetType:
Expand All @@ -8,7 +10,7 @@ case class AquaAPIConfig(
targetType: TargetType = TargetType.AirType,
logLevel: String = "info",
constants: List[String] = Nil,
noXor: Boolean = false, // TODO: Remove
noXor: Boolean = false,
noRelay: Boolean = false,
tracing: Boolean = false,
noEmptyResponse: Boolean = true
Expand All @@ -17,10 +19,18 @@ case class AquaAPIConfig(
def getTransformConfig: TransformConfig = {
val config = TransformConfig(
tracing = Option.when(tracing)(TransformConfig.TracingConfig.default),
noEmptyResponse = noEmptyResponse
noEmptyResponse = noEmptyResponse,
noXor = noXor
)

if (noRelay) config.copy(relayVarName = None)
else config
}

def getCompilerConfig: AquaCompilerConf = {
val config = AquaCompilerConf()

if (noRelay) config.copy(relayVarName = None)
else config
}
}
6 changes: 3 additions & 3 deletions aqua-run/src/main/scala/aqua/run/FuncCompiler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ import scribe.Logging
class FuncCompiler[F[_]: Files: AquaIO: Async](
input: Option[AquaPath],
imports: Imports,
transformConfig: TransformConfig
transformConfig: TransformConfig,
config: AquaCompilerConf
) extends Logging {

type Result = [A] =>> CompileResult[FileModuleId, AquaFileError, FileSpan.F][A]

private def compileToContext(
path: Path,
config: AquaCompilerConf = AquaCompilerConf(transformConfig.constantsList)
path: Path
): F[Result[Chain[AquaContext]]] = {
val sources = new AquaFileSources[F](path, imports)
CompilerAPI.compileToContext[F, AquaFileError, FileModuleId, FileSpan.F](
Expand Down
51 changes: 9 additions & 42 deletions aqua-src/antithesis.aqua
Original file line number Diff line number Diff line change
@@ -1,48 +1,15 @@
aqua Main

export bugLNG346
export main

ability Promise:
yield() -> string
service Srv("srv"):
call(x: i32) -> i32

func done_nil() -> string:
<- ""
func main(a: i32, b: i32) -> i32:
res: *i32
if a > b:
on "peer" via "relay":
res <- Srv.call(a)

func done() -> Promise:
<- Promise(yield = done_nil)
<- res!

ability Compute:
yield() -> string

alias WorkerYield: -> string
alias Yield: WorkerYield -> Promise

func wait_for() -> Yield:
wait = func (cb: -> string) -> Promise:
yield = func () -> string:
e <- cb()
<- e
<- Promise(yield = yield)
<- wait

ability Function:
run(dealId: string) -> string

func simple{Compute}(yield: Yield) -> Function:
deal_run = func () -> string:
c_yield = func () -> string:
<- Compute.yield()
yieeld <- yield(c_yield)
res <- yieeld.yield()
<- res
<- Function(run = deal_run)

func bugLNG346() -> string:
res: *string
yieeld = func () -> string:
res <<- "hello"
<- ""
c = Compute(yield = yieeld)
fn = simple{c}(wait_for())
r <- fn.run("")
<- res!
6 changes: 5 additions & 1 deletion compiler/src/main/scala/aqua/compiler/AquaCompilerConf.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,9 @@ import aqua.raw.ConstantRaw
* What should compiler care about during compilation – before generator backend takes its role
*
* @param constantsList List of known constants
* @param relayVarName Name of the relay variable
*/
case class AquaCompilerConf(constantsList: List[ConstantRaw])
case class AquaCompilerConf(
constants: List[ConstantRaw] = Nil,
relayVarName: Option[String] = Some("-relay-")
)
4 changes: 2 additions & 2 deletions compiler/src/main/scala/aqua/compiler/CompilerAPI.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import aqua.backend.Backend
import aqua.compiler.AquaError.*
import aqua.model.AquaContext
import aqua.parser.{Ast, ParserError}
import aqua.raw.RawContext
import aqua.raw.{ConstantRaw, RawContext}
import aqua.semantics.header.{HeaderHandler, HeaderSem}
import aqua.semantics.rules.locations.{DummyLocationsInterpreter, LocationsAlgebra}
import aqua.semantics.{FileId, RawSemantics}
Expand Down Expand Up @@ -48,7 +48,7 @@ object CompilerAPI extends Logging {
.implicits(
RawContext.blank.copy(
parts = Chain
.fromSeq(config.constantsList)
.fromSeq(config.constants ++ ConstantRaw.defaultConstants(config.relayVarName))
.map(const => RawContext.blank -> const)
)
)
Expand Down
90 changes: 90 additions & 0 deletions compiler/src/test/scala/aqua/compiler/AquaCompilerSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -883,4 +883,94 @@ class AquaCompilerSpec extends AnyFlatSpec with Matchers with Inside {
}
}
}

it should "not generate error propagation in `if` with `noXor = true`" in {
val src = Map(
"index.aqua" ->
"""aqua Test
|
|export main
|
|service Srv("srv"):
| call()
|
|func main(a: i32):
| if a > 0:
| Srv.call()
|""".stripMargin
)

val transformCfg = TransformConfig(noEmptyResponse = true, relayVarName = None, noXor = true)

insideRes(src, transformCfg = transformCfg)("main") { case main :: Nil =>
val aArg = VarModel("-a-arg-", ScalarType.i32)
val gt = CallModel.Export("gt", ScalarType.bool)
val expected = XorRes.wrap(
SeqRes.wrap(
getDataSrv("a", aArg.name, aArg.baseType),
CallServiceRes(
LiteralModel.quote("cmp"),
"gt",
CallRes(aArg :: LiteralModel.number(0) :: Nil, Some(gt)),
initPeer
).leaf,
XorRes.wrap(
MatchMismatchRes(gt.asVar, LiteralModel.bool(true), true).wrap(
CallServiceRes(
LiteralModel.quote("srv"),
"call",
CallRes(Nil, None),
initPeer
).leaf
)
)
),
errorCall(transformCfg, 0, initPeer)
)

main.body.equalsOrShowDiff(expected) should be(true)
}
}

it should "not generate error propagation in `on` with `noXor = true`" in {
val src = Map(
"index.aqua" ->
"""aqua Test
|
|export main
|
|service Srv("srv"):
| call()
|
|func main():
| on "peer" via "relay":
| Srv.call()
| Srv.call()
|""".stripMargin
)

val transformCfg = TransformConfig(noEmptyResponse = true, relayVarName = None, noXor = true)

insideRes(src, transformCfg = transformCfg)("main") { case main :: Nil =>
def call(peer: ValueModel) =
CallServiceRes(
LiteralModel.quote("srv"),
"call",
CallRes(Nil, None),
peer
).leaf

val expected = XorRes.wrap(
SeqRes.wrap(
through(LiteralModel.quote("relay")),
call(LiteralModel.quote("peer")),
through(LiteralModel.quote("relay")),
call(initPeer)
),
errorCall(transformCfg, 0, initPeer)
)

main.body.equalsOrShowDiff(expected) should be(true)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package aqua.lsp

import aqua.compiler.{AquaCompiler, AquaCompilerConf, AquaError, AquaSources}
import aqua.parser.{Ast, ParserError}
import aqua.raw.RawContext
import aqua.raw.{ConstantRaw, RawContext}
import aqua.semantics.FileId
import aqua.semantics.header.{HeaderHandler, HeaderSem}
import aqua.semantics.rules.locations.LocationsAlgebra
import aqua.semantics.FileId

import cats.data.Validated.validNec
import cats.data.{Chain, State, Validated, ValidatedNec}
import cats.syntax.either.*
Expand All @@ -24,7 +25,7 @@ object LSPCompiler {
LspContext.blank.copy(raw =
RawContext.blank.copy(
parts = Chain
.fromSeq(config.constantsList)
.fromSeq(config.constants ++ ConstantRaw.defaultConstants(config.relayVarName))
.map(const => RawContext.blank -> const)
)
)
Expand Down
10 changes: 5 additions & 5 deletions model/inline/src/main/scala/aqua/model/inline/ArrowInliner.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package aqua.model.inline
import aqua.errors.Errors.internalError
import aqua.model
import aqua.model.*
import aqua.model.inline.state.{Arrows, Exports, Mangler}
import aqua.model.inline.state.*
import aqua.raw.ops.RawTag
import aqua.raw.value.{ValueRaw, VarRaw}
import aqua.types.*
Expand All @@ -27,7 +27,7 @@ import scribe.Logging
*/
object ArrowInliner extends Logging {

def callArrow[S: Exports: Arrows: Mangler](
def callArrow[S: Exports: Arrows: Mangler: Config](
arrow: FuncArrow,
call: CallModel
): State[S, OpModel.Tree] =
Expand All @@ -43,7 +43,7 @@ object ArrowInliner extends Logging {
)

// push results to streams if they are exported to streams
private def pushStreamResults[S: Mangler: Exports: Arrows](
private def pushStreamResults[S: Mangler: Exports: Arrows: Config](
outsideStreamNames: Set[String],
exportTo: List[CallModel.Export],
results: List[ValueRaw]
Expand Down Expand Up @@ -140,7 +140,7 @@ object ArrowInliner extends Logging {
}

// Apply a callable function, get its fully resolved body & optional value, if any
private def inline[S: Mangler: Arrows: Exports](
private def inline[S: Mangler: Arrows: Exports: Config](
fn: FuncArrow,
call: CallModel,
outsideDeclaredStreams: Set[String]
Expand Down Expand Up @@ -542,7 +542,7 @@ object ArrowInliner extends Logging {
_ <- Exports[S].resolved(exportsResolved)
} yield (fn.copy(body = treeWithCanons, ret = ret), SeqModel.wrap(canons))

private[inline] def callArrowRet[S: Exports: Arrows: Mangler](
private[inline] def callArrowRet[S: Exports: Arrows: Mangler: Config](
arrow: FuncArrow,
call: CallModel
): State[S, (OpModel.Tree, List[ValueModel])] = for {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package aqua.model.inline

import aqua.model.*
import aqua.model.inline.RawValueInliner.unfold
import aqua.model.inline.raw.RawInliner
import aqua.model.inline.state.{Arrows, Exports, Mangler}
import aqua.model.*
import aqua.model.inline.state.*
import aqua.raw.value.MakeStructRaw
import aqua.types.{StreamMapType, StructType}

import cats.data.{Chain, NonEmptyMap, State}
import cats.syntax.foldable.*
import cats.syntax.bifunctor.*
import cats.syntax.foldable.*
import cats.syntax.functor.*

object MakeStructRawInliner extends RawInliner[MakeStructRaw] {
Expand Down Expand Up @@ -58,7 +58,7 @@ object MakeStructRawInliner extends RawInliner[MakeStructRaw] {
constructThroughMap(mapName, mapType, CallModel.Export(resultName, resultType), fields)
}

override def apply[S: Mangler: Exports: Arrows](
override def apply[S: Mangler: Exports: Arrows: Config](
raw: MakeStructRaw,
propertiesAllowed: Boolean
): State[S, (ValueModel, Inline)] = {
Expand Down
Loading
Loading