From d434c20cfb8623a243cd30f187907bb4b199dc99 Mon Sep 17 00:00:00 2001 From: Jason Zaugg Date: Wed, 7 Nov 2012 20:08:33 +0100 Subject: Abstract over the future implementation. - Refactor the base macro implementation to be parameterized by a FutureSystem, which is defines the triple of types (Future, Promise, ExecutionContext) and the operations on those types (at the AST level) - Cleanup generation of ASTs, in particular, use reify more widely. --- src/main/scala/scala/async/Async.scala | 213 ++++++++++++++------------ src/main/scala/scala/async/ExprBuilder.scala | 157 +++++++++++-------- src/main/scala/scala/async/FutureSystem.scala | 138 +++++++++++++++++ 3 files changed, 341 insertions(+), 167 deletions(-) create mode 100644 src/main/scala/scala/async/FutureSystem.scala (limited to 'src/main/scala') diff --git a/src/main/scala/scala/async/Async.scala b/src/main/scala/scala/async/Async.scala index d4b950e..d64e04a 100644 --- a/src/main/scala/scala/async/Async.scala +++ b/src/main/scala/scala/async/Async.scala @@ -7,131 +7,140 @@ import language.experimental.macros import scala.reflect.macros.Context import scala.collection.mutable.ListBuffer -import scala.concurrent.{ Future, Promise, ExecutionContext, future } +import scala.concurrent.{Future, Promise, ExecutionContext, future} import ExecutionContext.Implicits.global import scala.util.control.NonFatal -import scala.util.continuations.{ shift, reset, cpsParam } +import scala.util.continuations.{shift, reset, cpsParam} -/* Extending `ControlThrowable`, by default, also avoids filling in the stack trace. */ -class FallbackToCpsException extends scala.util.control.ControlThrowable /* * @author Philipp Haller */ -object Async extends AsyncUtils { +object Async extends AsyncBase { + lazy val futureSystem = ScalaConcurrentFutureSystem + type FS = ScalaConcurrentFutureSystem.type - def async[T](body: T): Future[T] = macro asyncImpl[T] + def async[T](body: T) = macro asyncImpl[T] + override def asyncImpl[T: c.WeakTypeTag](c: Context)(body: c.Expr[T]): c.Expr[Future[T]] = super.asyncImpl[T](c)(body) +} + +object AsyncId extends AsyncBase { + lazy val futureSystem = IdentityFutureSystem + type FS = IdentityFutureSystem.type + + def async[T](body: T) = macro asyncImpl[T] + + override def asyncImpl[T: c.WeakTypeTag](c: Context)(body: c.Expr[T]): c.Expr[T] = super.asyncImpl[T](c)(body) +} + +/** + * A base class for the `async` macro. Subclasses must provide: + * + * - Concrete types for a given future system + * - Tree manipulations to create and complete the equivalent of Future and Promise + * in that system. + * - The `async` macro declaration itself, and a forwarder for the macro implementation. + * (The latter is temporarily needed to workaround a bug in the macro system) + * + * The default implementation, [[scala.async.Async]], binds the macro to `scala.concurrent._`. + */ +abstract class AsyncBase extends AsyncUtils { + self => + + type FS <: FutureSystem + val futureSystem: FS + + /** + * A call to `await` must be nested in an enclosing `async` block. + * + * A call to await does not block the thread, rather it is a delimiter + * used by the enclosing `async` macro. Code following the `await` + * call + @ @param awaitable The future from which a value is awaited + * @tparam T The type of that value + * @return The value + */ // TODO Replace with `@compileTimeOnly when this is implemented SI-6539 @deprecated("`await` must be enclosed in an `async` block", "0.1") - def await[T](awaitable: Future[T]): T = ??? - - /* Fall back for `await` when it is called at an unsupported position. - */ - def awaitCps[T, U](awaitable: Future[T], p: Promise[U]): T @cpsParam[U, Unit] = - shift { - (k: (T => U)) => - awaitable onComplete { - case tr => p.success(k(tr.get)) - } - } - - def asyncImpl[T: c.WeakTypeTag](c: Context)(body: c.Expr[T]): c.Expr[Future[T]] = { + def await[T](awaitable: futureSystem.Fut[T]): T = ??? + + def asyncImpl[T: c.WeakTypeTag](c: Context)(body: c.Expr[T]) = { import c.universe._ import Flag._ - - val builder = new ExprBuilder[c.type](c) - val awaitMethod = awaitSym(c) - - try { - body.tree match { - case Block(stats, expr) => - val asyncBlockBuilder = new builder.AsyncBlockBuilder(stats, expr, 0, 1000, 1000, Map()) - vprintln(s"states of current method:") - asyncBlockBuilder.asyncStates foreach vprintln + val builder = new ExprBuilder[c.type, self.FS](c, self.futureSystem) - val handlerExpr = asyncBlockBuilder.mkCombinedHandlerExpr() + import builder.defn._ + import builder.futureSystemOps - vprintln(s"GENERATED handler expr:") - vprintln(handlerExpr) + val awaitMethod = awaitSym(c) - val handlerForLastState: c.Expr[PartialFunction[Int, Unit]] = { - val tree = Apply(Select(Ident("result"), newTermName("success")), - List(asyncBlockBuilder.asyncStates.last.body)) - builder.mkHandler(asyncBlockBuilder.asyncStates.last.state, c.Expr[Unit](tree)) - } + body.tree match { + case Block(stats, expr) => + val asyncBlockBuilder = new builder.AsyncBlockBuilder(stats, expr, 0, 1000, 1000, Map()) - vprintln("GENERATED handler for last state:") - vprintln(handlerForLastState) - - val localVarTrees = asyncBlockBuilder.asyncStates.init.flatMap(_.allVarDefs).toList - - /* - def resume(): Unit = { - try { - (handlerExpr.splice orElse handlerForLastState.splice)(state) - } catch { - case NonFatal(t) => result.failure(t) - } - } - */ - val nonFatalModule = c.mirror.staticModule("scala.util.control.NonFatal") - val resumeFunTree: c.Tree = DefDef(Modifiers(), newTermName("resume"), List(), List(List()), Ident(definitions.UnitClass), - Try(Apply(Select( - Apply(Select(handlerExpr.tree, newTermName("orElse")), List(handlerForLastState.tree)), - newTermName("apply")), List(Ident(newTermName("state")))), - List( - CaseDef( - Apply(Ident(nonFatalModule), List(Bind(newTermName("t"), Ident(nme.WILDCARD)))), - EmptyTree, - Block(List( - Apply(Select(Ident(newTermName("result")), newTermName("failure")), List(Ident(newTermName("t"))))), - Literal(Constant(()))))), EmptyTree)) - - reify { - val result = Promise[T]() - var state = 0 - future { - c.Expr(Block( - localVarTrees :+ resumeFunTree, - Apply(Ident(newTermName("resume")), List()))).splice - } - result.future - } + vprintln(s"states of current method:") + asyncBlockBuilder.asyncStates foreach vprintln - case _ => - // issue error message - reify { - sys.error("expression not supported by async") - } - } - } catch { - case _: FallbackToCpsException => - // replace `await` invocations with `awaitCps` invocations - val awaitReplacer = new Transformer { - val awaitCpsMethod = awaitCpsSym(c) - override def transform(tree: Tree): Tree = tree match { - case Apply(fun @ TypeApply(_, List(futArgTpt)), args) if fun.symbol == awaitMethod => - val typeApp = treeCopy.TypeApply(fun, Ident(awaitCpsMethod), List(TypeTree(futArgTpt.tpe), TypeTree(body.tree.tpe))) - treeCopy.Apply(tree, typeApp, args.map(arg => c.resetAllAttrs(arg.duplicate)) :+ Ident(newTermName("p"))) - - case _ => - super.transform(tree) - } + val handlerExpr = asyncBlockBuilder.mkCombinedHandlerExpr() + + vprintln(s"GENERATED handler expr:") + vprintln(handlerExpr) + + val handlerForLastState: c.Expr[PartialFunction[Int, Unit]] = { + val lastState = asyncBlockBuilder.asyncStates.last + val lastStateBody = c.Expr[T](lastState.body) + builder.mkHandler(lastState.state, futureSystemOps.completeProm(c.Expr[futureSystem.Prom[T]](Ident("result")), reify(scala.util.Success(lastStateBody.splice)))) } - - val newBody = awaitReplacer.transform(body.tree) - - reify { - val p = Promise[T]() - future { - reset { - c.Expr(c.resetAllAttrs(newBody.duplicate)).asInstanceOf[c.Expr[T]].splice + + vprintln("GENERATED handler for last state:") + vprintln(handlerForLastState) + + val localVarTrees = asyncBlockBuilder.asyncStates.init.flatMap(_.allVarDefs).toList + + /* + def resume(): Unit = { + try { + (handlerExpr.splice orElse handlerForLastState.splice)(state) + } catch { + case NonFatal(t) => result.failure(t) } } - p.future + */ + val nonFatalModule = c.mirror.staticModule("scala.util.control.NonFatal") + val resumeFunTree: c.Tree = DefDef(Modifiers(), newTermName("resume"), List(), List(List()), Ident(definitions.UnitClass), + Try( + reify { + val combinedHandler = mkPartialFunction_orElse(handlerExpr)(handlerForLastState).splice + combinedHandler.apply(c.Expr[Int](Ident(newTermName("state"))).splice) + }.tree + , + List( + CaseDef( + Apply(Ident(nonFatalModule), List(Bind(newTermName("t"), Ident(nme.WILDCARD)))), + EmptyTree, + Block(List({ + val t = c.Expr[Throwable](Ident(newTermName("t"))) + futureSystemOps.completeProm[T](c.Expr[futureSystem.Prom[T]](Ident(newTermName("result"))), reify(scala.util.Failure(t.splice))).tree + }), c.literalUnit.tree))), EmptyTree)) + + val prom: Expr[futureSystem.Prom[T]] = reify { + val result = futureSystemOps.createProm[T].splice + var state = 0 + futureSystemOps.future[Unit] { + c.Expr[Unit](Block( + localVarTrees :+ resumeFunTree, + Apply(Ident(newTermName("resume")), List()))) + }(futureSystemOps.execContext).splice + result } + val result = futureSystemOps.promiseToFuture(prom) + // println(s"${c.macroApplication} \nexpands to:\n ${result.tree}") + result + + case tree => + c.abort(c.macroApplication.pos, s"expression not supported by async: ${tree}") } } } diff --git a/src/main/scala/scala/async/ExprBuilder.scala b/src/main/scala/scala/async/ExprBuilder.scala index c5c192d..4beaa34 100644 --- a/src/main/scala/scala/async/ExprBuilder.scala +++ b/src/main/scala/scala/async/ExprBuilder.scala @@ -5,15 +5,22 @@ package scala.async import scala.reflect.macros.Context import scala.collection.mutable.{ListBuffer, Builder} +import concurrent.Future /* * @author Philipp Haller */ -class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { +final class ExprBuilder[C <: Context, FS <: FutureSystem](val c: C, val futureSystem: FS) extends AsyncUtils { builder => + lazy val futureSystemOps = futureSystem.mkOps(c) + import c.universe._ import Flag._ + import defn._ + + val execContextType = c.weakTypeOf[futureSystem.ExecContext] + val execContext = futureSystemOps.execContext private val awaitMethod = awaitSym(c) @@ -23,7 +30,7 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { * case any if any == num => rhs * } */ - def mkHandler(num: Int, rhs: c.Expr[Unit]): c.Expr[PartialFunction[Int, Unit]] = { + def mkHandler(num: Int, rhs: c.Expr[Any]): c.Expr[PartialFunction[Int, Unit]] = { /* val numLiteral = c.Expr[Int](Literal(Constant(num))) @@ -44,7 +51,8 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { def mkIncrStateTree(): c.Tree = { Assign( Ident(newTermName("state")), - Apply(Select(Ident(newTermName("state")), newTermName("$plus")), List(Literal(Constant(1))))) + mkInt_+(c.Expr[Int](Ident(newTermName("state"))))(c.literal(1)).tree + ) } def mkStateTree(nextState: Int): c.Tree = @@ -69,7 +77,7 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { // pattern Bind(newTermName("any"), Typed(Ident(nme.WILDCARD), Ident(definitions.IntClass))), // guard - Apply(Select(Ident(newTermName("any")), newTermName("$eq$eq")), List(Literal(Constant(num)))), + mkAny_==(c.Expr(Ident(newTermName("any"))))(c.literal(num)).tree, rhs ) @@ -79,8 +87,7 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { val unitIdent = Ident(definitions.UnitClass) val caseCheck = - Apply(Select(Apply(Ident(definitions.List_apply), - cases.map(p => Literal(Constant(p._2)))), newTermName("contains")), List(Ident(newTermName("x$1")))) + defn.mkList_contains(defn.mkList_apply(cases.map(p => c.literal(p._2))))(c.Expr(Ident(newTermName("x$1")))) Block(List( // anonymous subclass of PartialFunction[Int, Unit] @@ -91,7 +98,7 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { Block(List(Apply(Select(Super(This(tpnme.EMPTY), tpnme.EMPTY), nme.CONSTRUCTOR), List())), Literal(Constant(())))), DefDef(Modifiers(), newTermName("isDefinedAt"), List(), List(List(ValDef(Modifiers(PARAM), newTermName("x$1"), intIdent, EmptyTree))), TypeTree(), - caseCheck), + caseCheck.tree), DefDef(Modifiers(), newTermName("apply"), List(), List(List(ValDef(Modifiers(PARAM), newTermName("x$1"), intIdent, EmptyTree))), TypeTree(), Match(Ident(newTermName("x$1")), cases.map(_._1)) // combine all cases into a single match @@ -168,7 +175,7 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { val assignTree = Assign( Ident(resultName.toString), - Select(Ident("tr"), newTermName("get")) + mkTry_get(c.Expr(Ident("tr"))).tree ) val handlerTree = Match( @@ -179,10 +186,7 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { ) ) ) - Apply( - Select(awaitable, newTermName("onComplete")), - List(handlerTree) - ) + futureSystemOps.onComplete(c.Expr(awaitable), c.Expr(handlerTree), execContext).tree } /* Make an `onComplete` invocation which increments the state upon resuming: @@ -198,23 +202,17 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { val tryGetTree = Assign( Ident(resultName.toString), - Select(Ident("tr"), newTermName("get")) + Select(Ident("tr"), Try_get) ) + val handlerTree = - Match( - EmptyTree, - List( - CaseDef(Bind(newTermName("tr"), Ident("_")), EmptyTree, - Block(tryGetTree, mkIncrStateTree(), Apply(Ident("resume"), List())) // rhs of case - ) - ) - ) - Apply( - Select(awaitable, newTermName("onComplete")), - List(handlerTree) - ) + Function(List(ValDef(Modifiers(PARAM), newTermName("tr"), TypeTree(tryType), EmptyTree)), Block(tryGetTree, mkIncrStateTree(), Apply(Ident("resume"), List()))) + + futureSystemOps.onComplete(c.Expr(awaitable), c.Expr(handlerTree), execContext).tree } + def tryType = appliedType(c.mirror.staticClass("scala.util.Try").toType, List(resultType)) + /* Make an `onComplete` invocation which sets the state to `nextState` upon resuming: * * awaitable.onComplete { @@ -228,21 +226,12 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { val tryGetTree = Assign( Ident(resultName.toString), - Select(Ident("tr"), newTermName("get")) + Select(Ident("tr"), Try_get) ) val handlerTree = - Match( - EmptyTree, - List( - CaseDef(Bind(newTermName("tr"), Ident("_")), EmptyTree, - Block(tryGetTree, mkStateTree(nextState), Apply(Ident("resume"), List())) // rhs of case - ) - ) - ) - Apply( - Select(awaitable, newTermName("onComplete")), - List(handlerTree) - ) + Function(List(ValDef(Modifiers(PARAM), newTermName("tr"), TypeTree(tryType), EmptyTree)), Block(tryGetTree, mkStateTree(nextState), Apply(Ident("resume"), List()))) + + futureSystemOps.onComplete(c.Expr(awaitable), c.Expr(handlerTree), execContext).tree } /* Make a partial function literal handling case #num: @@ -391,12 +380,12 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { override val varDefs = self.varDefs.toList } } - + /** * Build `AsyncState` ending with a match expression. - * + * * The cases of the match simply resume at the state of their corresponding right-hand side. - * + * * @param scrutTree tree of the scrutinee * @param cases list of case definitions * @param stateFirstCase state of the right-hand side of the first case @@ -414,7 +403,7 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { override val varDefs = self.varDefs.toList } } - + override def toString: String = { val statsBeforeAwait = stats.mkString("\n") s"ASYNC STATE:\n$statsBeforeAwait \nawaitable: $awaitable \nresult name: $resultName" @@ -423,7 +412,7 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { /** * An `AsyncBlockBuilder` builds a `ListBuffer[AsyncState]` based on the expressions of a `Block(stats, expr)` (see `Async.asyncImpl`). - * + * * @param stats a list of expressions * @param expr the last expression of the block * @param startState the start state @@ -441,20 +430,20 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { private var remainingBudget = budget - /* Fall back to CPS plug-in if tree contains an `await` call. */ + /* TODO Fall back to CPS plug-in if tree contains an `await` call. */ def checkForUnsupportedAwait(tree: c.Tree) = if (tree exists { case Apply(fun, _) if fun.symbol == awaitMethod => true case _ => false - }) throw new FallbackToCpsException - + }) c.abort(tree.pos, "await unsupported in this position") //throw new FallbackToCpsException + def builderForBranch(tree: c.Tree, state: Int, nextState: Int, budget: Int, nameMap: Map[c.Symbol, c.Name]): AsyncBlockBuilder = { val (branchStats, branchExpr) = tree match { case Block(s, e) => (s, e) - case _ => (List(tree), Literal(Constant(()))) + case _ => (List(tree), Literal(Constant(()))) } new AsyncBlockBuilder(branchStats, branchExpr, state, nextState, budget, nameMap) } - + // populate asyncStates for (stat <- stats) stat match { // the val name = await(..) pattern @@ -491,44 +480,45 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { asyncStates += // the two Int arguments are the start state of the then branch and the else branch, respectively stateBuilder.resultWithIf(cond, currState + 1, currState + thenBudget) - - List((thenp, currState + 1, thenBudget), (elsep, currState + thenBudget, elseBudget)) foreach { case (tree, state, branchBudget) => - val builder = builderForBranch(tree, state, currState + ifBudget, branchBudget, toRename) - asyncStates ++= builder.asyncStates - toRename ++= builder.toRename + + List((thenp, currState + 1, thenBudget), (elsep, currState + thenBudget, elseBudget)) foreach { + case (tree, state, branchBudget) => + val builder = builderForBranch(tree, state, currState + ifBudget, branchBudget, toRename) + asyncStates ++= builder.asyncStates + toRename ++= builder.toRename } - + // create new state builder for state `currState + ifBudget` currState = currState + ifBudget stateBuilder = new builder.AsyncStateBuilder(currState, toRename) - + case Match(scrutinee, cases) => vprintln("transforming match expr: " + stat) checkForUnsupportedAwait(scrutinee) - + val matchBudget: Int = remainingBudget / 2 remainingBudget -= matchBudget //TODO test if budget > 0 // state that we continue with after match: currState + matchBudget - + val perCaseBudget: Int = matchBudget / cases.size asyncStates += // the two Int arguments are the start state of the first case and the per-case state budget, respectively stateBuilder.resultWithMatch(scrutinee, cases, currState + 1, perCaseBudget) - + for ((cas, num) <- cases.zipWithIndex) { val (casStats, casExpr) = cas match { case CaseDef(_, _, Block(s, e)) => (s, e) - case CaseDef(_, _, rhs) => (List(rhs), Literal(Constant(()))) + case CaseDef(_, _, rhs) => (List(rhs), Literal(Constant(()))) } val builder = new AsyncBlockBuilder(casStats, casExpr, currState + (num * perCaseBudget) + 1, currState + matchBudget, perCaseBudget, toRename) asyncStates ++= builder.asyncStates toRename ++= builder.toRename } - + // create new state builder for state `currState + matchBudget` currState = currState + matchBudget stateBuilder = new builder.AsyncStateBuilder(currState, toRename) - + case _ => checkForUnsupportedAwait(stat) stateBuilder += stat @@ -542,7 +532,9 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { assert(asyncStates.size > 1) val cases = for (state <- asyncStates.toList) yield state.mkHandlerCaseForState() - c.Expr(mkHandlerTreeFor(cases zip asyncStates.init.map(_.state))).asInstanceOf[c.Expr[PartialFunction[Int, Unit]]] + reify { + c.Expr[PartialFunction[Int, Unit]](mkHandlerTreeFor(cases zip asyncStates.init.map(_.state))).splice: PartialFunction[Int, Unit] + } } /* Builds the handler expression for a sequence of async states. @@ -560,14 +552,49 @@ class ExprBuilder[C <: Context with Singleton](val c: C) extends AsyncUtils { // do not traverse first or last state val handlerTreeForNextState = asyncState.mkHandlerTreeForState() val currentHandlerTreeNaked = c.resetAllAttrs(handlerExpr.tree.duplicate) - handlerExpr = c.Expr( - Apply(Select(currentHandlerTreeNaked, newTermName("orElse")), - List(handlerTreeForNextState))).asInstanceOf[c.Expr[PartialFunction[Int, Unit]]] + handlerExpr = mkPartialFunction_orElse(c.Expr(currentHandlerTreeNaked))(c.Expr(handlerTreeForNextState)) } handlerExpr } } + } + + /** `termSym( (_: Foo).bar(null: A, null: B)` will return the symbol of `bar`, after overload resolution. */ + def methodSym(apply: c.Expr[Any]): Symbol = { + val tree2: Tree = c.typeCheck(apply.tree) // TODO why is this needed? + tree2.collect { + case s: SymTree if s.symbol.isMethod => s.symbol + }.headOption.getOrElse(sys.error(s"Unable to find a method symbol in ${apply.tree}")) + } + + object defn { + def mkList_apply[A](args: List[Expr[A]]): Expr[List[A]] = { + c.Expr(Apply(Ident(definitions.List_apply), args.map(_.tree))) + } + + def mkList_contains[A](self: Expr[List[A]])(elem: Expr[Any]) = reify(self.splice.contains(elem.splice)) + + def mkPartialFunction_orElse[A, B](self: Expr[PartialFunction[A, B]])(other: Expr[PartialFunction[A, B]]) = reify { + self.splice.orElse(other.splice) + } + + def mkFunction_apply[A, B](self: Expr[Function1[A, B]])(arg: Expr[A]) = reify { + self.splice.apply(arg.splice) + } + + def mkInt_+(self: Expr[Int])(other: Expr[Int]) = reify { + self.splice + other.splice + } + + def mkAny_==(self: Expr[Any])(other: Expr[Any]) = reify { + self.splice == other.splice + } + + def mkTry_get[A](self: Expr[util.Try[A]]) = reify { + self.splice.get + } + val Try_get = methodSym(reify((null.asInstanceOf[scala.util.Try[Any]]).get)) } } diff --git a/src/main/scala/scala/async/FutureSystem.scala b/src/main/scala/scala/async/FutureSystem.scala new file mode 100644 index 0000000..64c5a66 --- /dev/null +++ b/src/main/scala/scala/async/FutureSystem.scala @@ -0,0 +1,138 @@ +/** + * Copyright (C) 2012 Typesafe Inc. + */ +package scala.async + +import reflect.macros.Context + +/** + * An abstraction over a future system. + * + * Used by the macro implementations in [[scala.async.AsyncBase]] to + * customize the code generation. + * + * The API mirrors that of `scala.concurrent.Future`, see the instance + * [[scala.async.ScalaConcurrentFutureSystem]] for an example of how + * to implement this. + */ +trait FutureSystem { + /** A container to receive the final value of the computation */ + type Prom[A] + /** A (potentially in-progress) computation */ + type Fut[A] + /** An execution context, required to create or register an on completion callback on a Future. */ + type ExecContext + + trait Ops { + val context: reflect.macros.Context + + import context.universe._ + + /** Lookup the execution context, typically with an implicit search */ + def execContext: Expr[ExecContext] + + /** Create an empty promise */ + def createProm[A: WeakTypeTag]: Expr[Prom[A]] + + /** Extract a future from the given promise. */ + def promiseToFuture[A: WeakTypeTag](prom: Expr[Prom[A]]): Expr[Fut[A]] + + /** Construct a future to asynchrously compute the given expression */ + def future[A: WeakTypeTag](a: Expr[A])(execContext: Expr[ExecContext]): Expr[Fut[A]] + + /** Register an call back to run on completion of the given future */ + def onComplete[A, U](future: Expr[Fut[A]], fun: Expr[scala.util.Try[A] => U], + execContext: Expr[ExecContext]): Expr[Unit] + + /** Complete a promise with a value */ + def completeProm[A](prom: Expr[Prom[A]], value: Expr[scala.util.Try[A]]): Expr[Unit] + } + + def mkOps(c: Context): Ops {val context: c.type} +} + +object ScalaConcurrentFutureSystem extends FutureSystem { + + import scala.concurrent._ + + type Prom[A] = Promise[A] + type Fut[A] = Future[A] + type ExecContext = ExecutionContext + + def mkOps(c: Context): Ops {val context: c.type} = new Ops { + val context: c.type = c + + import context.universe._ + + def execContext: Expr[ExecContext] = c.Expr(c.inferImplicitValue(c.weakTypeOf[ExecutionContext]) match { + case EmptyTree => c.abort(c.macroApplication.pos, "Unable to resolve implicit ExecutionContext") + case context => context + }) + + def createProm[A: WeakTypeTag]: Expr[Prom[A]] = reify { + Promise[A]() + } + + def promiseToFuture[A: WeakTypeTag](prom: Expr[Prom[A]]) = reify { + prom.splice.future + } + + def future[A: WeakTypeTag](a: Expr[A])(execContext: Expr[ExecContext]) = reify { + Future(a.splice)(execContext.splice) + } + + def onComplete[A, U](future: Expr[Fut[A]], fun: Expr[scala.util.Try[A] => U], + execContext: Expr[ExecContext]): Expr[Unit] = { + reify { + future.splice.onComplete(fun.splice)(execContext.splice) + context.literalUnit.splice + } + } + + def completeProm[A](prom: Expr[Prom[A]], value: Expr[scala.util.Try[A]]): Expr[Unit] = reify { + prom.splice.complete(value.splice) + context.literalUnit.splice + } + } +} + +/** + * A trivial implentation of [[scala.async.FutureSystem]] that performs computations + * on the current thread. Useful for testing. + */ +object IdentityFutureSystem extends FutureSystem { + + class Prom[A](var a: A) + + type Fut[A] = A + type ExecContext = Unit + + def mkOps(c: Context): Ops {val context: c.type} = new Ops { + val context: c.type = c + + import context.universe._ + + def execContext: Expr[ExecContext] = c.literalUnit + + def createProm[A: WeakTypeTag]: Expr[Prom[A]] = reify { + new Prom(null.asInstanceOf[A]) + } + + def promiseToFuture[A: WeakTypeTag](prom: Expr[Prom[A]]) = reify { + prom.splice.a + } + + def future[A: WeakTypeTag](t: Expr[A])(execContext: Expr[ExecContext]) = t + + def onComplete[A, U](future: Expr[Fut[A]], fun: Expr[scala.util.Try[A] => U], + execContext: Expr[ExecContext]): Expr[Unit] = reify { + fun.splice.apply(util.Success(future.splice)) + context.literalUnit.splice + } + + def completeProm[A](prom: Expr[Prom[A]], value: Expr[scala.util.Try[A]]): Expr[Unit] = reify { + prom.splice.a = value.splice.get + context.literalUnit.splice + } + } +} -- cgit v1.2.3