1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
|
/**
* Copyright (C) 2012 Typesafe Inc. <http://www.typesafe.com>
*/
package scala.async
import language.experimental.macros
import scala.reflect.macros.Context
import scala.reflect.runtime.universe
import scala.concurrent.{ Future, Promise }
import scala.util.control.NonFatal
import scala.collection.mutable.ListBuffer
/*
* @author Philipp Haller
*/
object Async extends AsyncUtils {
def async[T](body: T): Future[T] = macro asyncImpl[T]
def await[T](awaitable: Future[T]): T = ???
def asyncImpl[T: c.AbsTypeTag](c: Context)(body: c.Expr[T]): c.Expr[Future[T]] = {
import c.universe._
def mkHandlers(rhs: c.Expr[Unit]): Seq[c.Expr[PartialFunction[Int, Unit]]] = {
//TODO: come up with much better way to do this
val handlers = ListBuffer[c.Expr[PartialFunction[Int, Unit]]]()
handlers += reify(new PartialFunction[Int, Unit] {
def isDefinedAt(x_synth: Int) = x_synth == 0
def apply(x_synth: Int) = x_synth match { case 0 => rhs.splice }
})
handlers += reify(new PartialFunction[Int, Unit] {
def isDefinedAt(x_synth: Int) = x_synth == 1
def apply(x_synth: Int) = x_synth match { case 1 => rhs.splice }
})
handlers += reify(new PartialFunction[Int, Unit] {
def isDefinedAt(x_synth: Int) = x_synth == 2
def apply(x_synth: Int) = x_synth match { case 2 => rhs.splice }
})
handlers += reify(new PartialFunction[Int, Unit] {
def isDefinedAt(x_synth: Int) = x_synth == 3
def apply(x_synth: Int) = x_synth match { case 3 => rhs.splice }
})
handlers
}
class AsyncStateBuilder {
/* Statements preceding an await call. */
private val stats = ListBuffer[c.Tree]()
/* Argument of an await call. */
var awaitable: c.Tree = null
/* Result name of an await call. */
var resultName: c.universe.TermName = null
/* Result type of an await call. */
var resultType: c.universe.Type = null
def += (stat: c.Tree): Unit =
stats += stat
/* Result needs to be created as a var at the beginning of the transformed method body, so that
it is visible in subsequent states of the state machine.
*/
def complete(awaitArg: c.Tree, awaitResultName: c.universe.TermName, awaitResultType: c.Tree): Unit = {
awaitable = c.resetAllAttrs(awaitArg.duplicate)
resultName = awaitResultName
resultType = awaitResultType.tpe
}
override def toString: String = {
val statsBeforeAwait = stats.mkString("\n")
s"ASYNC STATE:\n$statsBeforeAwait \nawaitable: $awaitable \nresult name: $resultName"
}
/* Make an `onComplete` invocation:
*
* awaitable.onComplete {
* case tr =>
* resultName = tr.get
* resume()
* }
*/
def mkOnCompleteTree: c.Tree = {
val assignTree =
Assign(
Ident(resultName.toString),
Select(Ident("tr"), c.universe.newTermName("get"))
)
val handlerTree =
Match(
EmptyTree,
List(
CaseDef(Bind(c.universe.newTermName("tr"), Ident("_")), EmptyTree,
Block(assignTree, Apply(Ident("resume"), List())) // rhs of case
)
)
)
Apply(
Select(awaitable, c.universe.newTermName("onComplete")),
List(handlerTree)
)
}
/* Make a partial function literal handling case #num:
*
* {
* case num =>
* stats
* awaitable.onComplete {
* case tr =>
* resultName = tr.get
* resume()
* }
* }
*/
def mkHandlerForState(num: Int): c.Expr[PartialFunction[Int, Unit]] = {
assert(awaitable != null)
val nakedStats = stats.map(stat => c.resetAllAttrs(stat.duplicate)).toList
val block = Block((nakedStats :+ mkOnCompleteTree): _*)
val blockExpr = c.Expr(block).asInstanceOf[c.Expr[Unit]]
val numLiteral = c.Expr(Literal(Constant(num))).asInstanceOf[c.Expr[Int]]
reify(new PartialFunction[Int, Unit] {
def isDefinedAt(`x$1`: Int) =
`x$1` == numLiteral.splice
def apply(`x$1`: Int) = `x$1` match {
case any: Int if any == numLiteral.splice =>
blockExpr.splice
}
})
}
def lastExprTree: c.Tree = {
assert(awaitable == null)
if (stats.size == 1)
c.resetAllAttrs(stats(0).duplicate)
else {
val nakedStats = stats.map(stat => c.resetAllAttrs(stat.duplicate)).toList
Block(nakedStats: _*)
}
}
//TODO: complete for other primitive types, how to handle value classes?
def varDefForResult: c.Tree = {
val rhs =
if (resultType <:< definitions.IntTpe) Literal(Constant(0))
else if (resultType <:< definitions.LongTpe) Literal(Constant(0L))
else if (resultType <:< definitions.BooleanTpe) Literal(Constant(false))
else Literal(Constant(null))
ValDef(Modifiers(Flag.MUTABLE), resultName, TypeTree(resultType), rhs)
}
}
body.tree match {
case Block(stats, expr) =>
val asyncStates = ListBuffer[AsyncStateBuilder]()
var stateBuilder = new AsyncStateBuilder // current state builder
val awaitMethod = awaitSym(c)
for (stat <- stats) {
stat match {
// the val name = await(..) pattern
case ValDef(mods, name, tpt, Apply(fun, args)) if fun.symbol == awaitMethod =>
stateBuilder.complete(args(0), name, tpt)
asyncStates += stateBuilder
stateBuilder = new AsyncStateBuilder
case _ =>
stateBuilder += stat
}
}
// complete last state builder (representing the expressions after the last await)
stateBuilder += expr
asyncStates += stateBuilder
vprintln("states of current method:")
asyncStates foreach vprintln
// also return index of last state
def buildHandlerExpr(): (c.Expr[PartialFunction[Int, Unit]], Int) = {
var handlerExpr = asyncStates(0).mkHandlerForState(1) // state 0 but { case 1 => ... }
var i = 1
while (asyncStates(i).awaitable != null) {
val handlerForNextState = asyncStates(i).mkHandlerForState(i+1)
val currentHandlerTreeNaked = c.resetAllAttrs(handlerExpr.tree.duplicate)
handlerExpr = reify {
c.Expr(currentHandlerTreeNaked).asInstanceOf[c.Expr[PartialFunction[Int, Unit]]].splice orElse handlerForNextState.splice
}
i += 1
}
// asyncStates(i) does not end with `await`
(handlerExpr, i)
}
val (handlerExpr, indexOfLastState) = buildHandlerExpr()
vprintln(s"GENERATED handler expr ($indexOfLastState):")
vprintln(handlerExpr)
val localVarDefs = ListBuffer[c.Tree]()
for (state <- asyncStates.init) // exclude last state (doesn't have await result)
localVarDefs += state.varDefForResult
// pad up to 5 var defs
if (localVarDefs.size < 5)
for (_ <- localVarDefs.size until 5) localVarDefs += EmptyTree
val handlerForLastState: c.Expr[PartialFunction[Int, Unit]] =
mkHandlers({
val tree = Apply(Select(Ident("result"), c.universe.newTermName("success")),
List(asyncStates(indexOfLastState).lastExprTree))
c.Expr(tree).asInstanceOf[c.Expr[Unit]]
})(indexOfLastState + 1)
vprintln("GENERATED handler for last state:")
vprintln(handlerForLastState)
reify {
val result = Promise[T]()
var state = 0
c.Expr(localVarDefs(0)).splice
c.Expr(localVarDefs(1)).splice
c.Expr(localVarDefs(2)).splice
c.Expr(localVarDefs(3)).splice
c.Expr(localVarDefs(4)).splice
def resume(): Unit = {
state += 1
var handler: PartialFunction[Int, Unit] =
handlerExpr.splice
try {
(handler orElse handlerForLastState.splice)(state)
} catch {
case NonFatal(t) => result.failure(t)
}
}
resume()
result.future
}
case _ =>
// issue error message
reify {
sys.error("expression not supported by async")
}
}
}
}
|