-
Notifications
You must be signed in to change notification settings - Fork 29
/
BangNotation.scala
534 lines (495 loc) · 18.9 KB
/
BangNotation.scala
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
package com.thoughtworks.dsl
package compilerplugins
import com.thoughtworks.dsl.Dsl.{ResetAnnotation, nonTypeConstraintReset, shift}
import com.thoughtworks.dsl.compilerplugins.BangNotation.HasReturn
import scala.annotation.tailrec
import scala.tools.nsc.plugins.{Plugin, PluginComponent}
import scala.tools.nsc.transform.Transform
import scala.tools.nsc.typechecker.ContextMode
import scala.tools.nsc.{Global, Mode, Phase}
private object BangNotation {
sealed trait HasReturn
object HasReturn {
case object Yes extends HasReturn
case object No extends HasReturn
}
}
/** The Scala compiler plug-in to convert ordinary Scala control flows to continuation-passing style,
* which will then be interpreted by [[Dsl]].
*
* = Usage =
*
* `<pre>
* // In your build.sbt
* addCompilerPlugin("com.thoughtworks.dsl" %% "compilerplugins-bangnotation" % "latest.release")
* </pre>`
*
* @author 杨博 (Yang Bo)
*/
final class BangNotation(override val global: Global) extends Plugin {
import global._
import global.analyzer._
private val hasScalaJsPlugin =
global.settings.plugin.value.exists(_.matches("""^.*scalajs-compiler_.*\.jar$"""))
private var active = true
private def deactAnalyzerPlugins[A](run: => A): A = {
synchronized {
active = false
try {
run
} finally {
active = true
}
}
}
private type CpsAttachment = (Tree => Tree) => Tree
private trait Deactable extends AnalyzerPlugin {
override def isActive(): Boolean = {
active && phase.id < currentRun.picklerPhase.id
}
}
/** An [[AnalyzerPlugin]] that replaces trees annatated as [[ResetAnnotation]] to its cps transformed trees */
private trait TreeResetter extends AnalyzerPlugin with AnnotationSymbols {
override def canAdaptAnnotations(tree: Tree, typer: Typer, mode: Mode, pt: Type): Boolean = {
super.canAdaptAnnotations(tree, typer, mode, pt) || {
mode.inExprMode && tree.tpe.hasAnnotation(resetAnnotationSymbol) && tree.hasAttachment[CpsAttachment]
}
}
/** Avoid [[UnApply]] in `tree` to suppress compiler crash due to `unexpected UnApply xxx`.
*
* @see https://github.com/scala/bug/issues/8825
*/
private def scalaBug8825Workaround(tree: Tree): Tree = {
val transformer = new Transformer {
override def transform(tree: global.Tree): global.Tree = {
tree match {
case UnApply(
Apply(Select(prefix, termNames.unapply | termNames.unapplySeq), List(Ident(termNames.SELECTOR_DUMMY))),
args) =>
pq"$prefix(..${transformTrees(args)})"
case _ =>
super.transform(tree)
}
}
}
transformer.transform(tree)
}
override def adaptAnnotations(tree0: Tree, typer: Typer, mode: Mode, pt: Type): Tree = {
val tree = super.adaptAnnotations(tree0, typer, mode, pt)
tree.tpe.annotations.collectFirst {
case annotation if annotation.matches(resetAnnotationSymbol) =>
val Some(attachment) = tree.attachments.get[CpsAttachment]
val cpsTree = scalaBug8825Workaround(resetAttrs(attachment(identity)))
// reporter.info(tree.pos, s"Translating to continuation-passing style: $cpsTree", true)
deactAnalyzerPlugins {
typer.context.withMode(ContextMode.ReTyping) {
typer.typed(cpsTree, Mode.EXPRmode)
}
}
} match {
case Some(typedCpsTree) =>
// reporter.info(tree.pos, s"Translating to continuation-passing style: $typedCpsTree", true)
typedCpsTree.modifyType(_.filterAnnotations(!_.matches(resetAnnotationSymbol)))
case None =>
tree
}
}
}
private trait BangNotationTransformer extends AnalyzerPlugin with AnnotationSymbols {
private def cpsAttachment(tree: Tree)(continue: Tree => Tree): Tree = {
tree.attachments.get[CpsAttachment] match {
case Some(attachment) => attachment(continue)
case None => continue(tree)
}
}
private def cpsParameter(parameters: List[Tree])(continue: List[Tree] => Tree): Tree = {
parameters match {
case Nil =>
continue(Nil)
case head :: tail =>
cpsAttachment(head) { headValue =>
cpsParameter(tail) { tailValues =>
continue(headValue :: tailValues)
}
}
}
}
private def cpsParameterList(parameterLists: List[List[Tree]])(continue: List[List[Tree]] => Tree): Tree = {
parameterLists match {
case Nil =>
continue(Nil)
case headList :: tailList =>
cpsParameter(headList) { headValue =>
cpsParameterList(tailList) { tailValues =>
continue(headValue :: tailValues)
}
}
}
}
private def isCpsTree(tree: Tree) = {
def hasCpsAttachment(child: Any): Boolean = {
child match {
case list: List[_] => list.exists(hasCpsAttachment)
case TypeApply(fun, args) => hasCpsAttachment(fun)
case Apply(fun, args) => hasCpsAttachment(fun) || args.exists(hasCpsAttachment)
case CaseDef(pat, guard, body) => hasCpsAttachment(body)
case ValDef(mods, name, tpt, rhs) => hasCpsAttachment(rhs)
case childTree: Tree => childTree.hasAttachment[CpsAttachment]
case _ => false
}
}
tree.productIterator.exists(hasCpsAttachment)
}
private lazy val catchIdent: Tree = {
try {
Ident(rootMirror.staticModule("_root_.com.thoughtworks.dsl.keywords.Catch"))
} catch {
case e: ScalaReflectionException =>
abort("""The BangNotation compiler plug-in requires the runtime library `keywords-catch` to enable !-notation in `try` / `catch` / `finally` expressions:
libraryDependencies += "com.thoughtworks.dsl" %% "keywords-catch" % "latest.release"
""")
}
}
private val whileName = currentUnit.freshTermName("while")
private val whileDef = {
val domainName = currentUnit.freshTypeName("Domain")
val conditionName = currentUnit.freshTermName("condition")
val conditionValueName = currentUnit.freshTermName("conditionValue")
val bodyName = currentUnit.freshTermName("body")
val endWhileName = currentUnit.freshTermName("endWhile")
q"""
@${definitions.ScalaInlineClass} def $whileName[$domainName]($endWhileName: => $domainName)(
$bodyName: (=> $domainName) => $domainName,
$conditionName: (_root_.scala.Boolean => $domainName) => $domainName): $domainName = {
$conditionName { $conditionValueName: ${TypeTree()} =>
if ($conditionValueName) {
$bodyName {
$whileName[$domainName]($endWhileName)($bodyName, $conditionName)
}
} else {
$endWhileName
}
}
}
"""
}
private val doWhileName = currentUnit.freshTermName("doWhile")
private val doWhileDef = {
val domainName = currentUnit.freshTypeName("Domain")
val conditionName = currentUnit.freshTermName("condition")
val conditionValueName = currentUnit.freshTermName("conditionValue")
val bodyName = currentUnit.freshTermName("body")
val endDoWhileName = currentUnit.freshTermName("endDoWhile")
q"""
@${definitions.ScalaInlineClass} def $doWhileName[$domainName]($endDoWhileName: => $domainName)(
$bodyName: (=> $domainName) => $domainName,
$conditionName: (_root_.scala.Boolean => $domainName) => $domainName): $domainName = {
$bodyName {
$conditionName { $conditionValueName: ${TypeTree()} =>
if ($conditionValueName) {
$doWhileName[$domainName]($endDoWhileName)($bodyName, $conditionName)
} else {
$endDoWhileName
}
}
}
}
"""
}
private def notPure(head: Tree): List[Tree] = {
head match {
case (_: Ident) | (_: Literal) =>
Nil
case _ =>
head :: Nil
}
}
private def toFunction1(continue: Tree => Tree, parameterTypes: Type) = {
val parameterName = currentUnit.freshTermName("a")
val id = q"$parameterName"
continue(id) match {
case q"${f: Ident}.apply(${`id`})" =>
f
case transformed =>
q"""
{ ($parameterName: $parameterTypes) =>
${transformed}
}
"""
}
}
private def hasReturnTree(tree: Tree): Boolean = {
tree.attachments.get[HasReturn] match {
case Some(HasReturn.Yes) =>
true
case Some(HasReturn.No) =>
false
case _ =>
tree match {
case _: Return =>
true
case valDef: ValDef =>
hasReturnTree(valDef.rhs)
case _: MemberDef =>
false
case _ =>
tree.children.exists(hasReturnTree)
}
}
}
override def pluginsTyped(tpe0: Type, typer: Typer, tree: Tree, mode: Mode, pt: Type): Type = {
val tpe = super.pluginsTyped(tpe0, typer, tree, mode, pt)
def cps(continue: Tree => Tree): Tree = atPos(tree.pos) {
tree match {
case q"$prefix.$methodName[..$typeParameters](...$parameterLists)" =>
cpsAttachment(prefix) { prefixValue =>
cpsParameterList(parameterLists) { parameterListsValues =>
continue(atPos(tree.pos) {
q"$prefixValue.$methodName[..$typeParameters](...$parameterListsValues)"
})
}
}
case q"${method: Ident}[..$typeParameters](...$parameterLists)" =>
cpsParameterList(parameterLists) { parameterListsValues =>
continue(atPos(tree.pos) {
q"$method[..$typeParameters](...$parameterListsValues)"
})
}
case q"new $constructor[..$typeParameters](...$parameterLists)" =>
cpsParameterList(parameterLists) { parameterListsValues =>
continue(atPos(tree.pos) {
q"new $constructor[..$typeParameters](...$parameterListsValues)"
})
}
case Typed(expr, tpt) =>
cpsAttachment(expr) { exprValue =>
atPos(tree.pos) {
if (tpt.tpe.hasAnnotation(resetAnnotationSymbol)) {
continue(exprValue)
} else {
tpt match {
case tpt: TypeTree =>
// Create a new TypeTree with a null original, as a workaround of https://github.com/ThoughtWorksInc/Dsl.scala/issues/114
val noOriginal = TypeTree(tpt.tpe).setPos(tpt.pos)
continue(Typed(exprValue, noOriginal))
case _ =>
continue(Typed(exprValue, tpt))
}
}
}
}
case Block(stats, expr) =>
def loop(stats: List[Tree]): Tree = {
stats match {
case Nil =>
cpsAttachment(expr) {
case block: Block =>
continue(block)
case notBlock =>
continue(treeCopy.Block(tree, Nil, notBlock))
}
case (valDef @ ValDef(mods, name, tpt, rhs)) :: tail =>
// TODO: lazy val
cpsAttachment(rhs) { rhsValue =>
atPos(valDef.pos) {
q"${treeCopy.ValDef(valDef, mods, name, tpt, rhsValue)}; ${loop(tail)}"
}
}
case head :: tail =>
cpsAttachment(head) { headValue =>
q"..${notPure(headValue)}; ${loop(tail)}"
}
}
}
loop(stats)
case If(cond, thenp, elsep) =>
val endIfName = currentUnit.freshTermName("endIf")
q"""
${
val endIfBody = toFunction1(continue, tpe)
if (hasReturnTree(endIfBody)) {
q"""
val $endIfName = $endIfBody
""".updateAttachment(HasReturn.Yes)
} else {
q"""
@${definitions.ScalaInlineClass} def $endIfName = $endIfBody
""".updateAttachment(HasReturn.No)
}
}
${cpsAttachment(cond) { condValue =>
atPos(tree.pos) {
q"""
if ($condValue) ${cpsAttachment(thenp) { result =>
q"$endIfName.apply($result)"
}} else ${cpsAttachment(elsep) { result =>
q"$endIfName.apply($result)"
}}
"""
}
}}
"""
case Match(selector, cases) =>
val endMatchName = currentUnit.freshTermName("endMatch")
q"""
${
val endMatchBody = toFunction1(continue, tpe)
if (hasReturnTree(endMatchBody)) {
q"""
val $endMatchName = $endMatchBody
""".updateAttachment(HasReturn.Yes)
} else {
q"""
@${definitions.ScalaInlineClass} def $endMatchName = $endMatchBody
""".updateAttachment(HasReturn.No)
}
}
${cpsAttachment(selector) { selectorValue =>
atPos(tree.pos) {
Match(
selectorValue,
cases.map {
case caseDef @ CaseDef(pat, guard, body) =>
treeCopy.CaseDef(caseDef, pat, guard, cpsAttachment(body) { bodyValue =>
q"$endMatchName.apply($bodyValue)"
})
}
)
}
}}
"""
case _: CaseDef =>
// This CaseDef tree contains some bang notations, and will be translated by enclosing Try or Match tree, not here
EmptyTree
case Try(block, catches, finalizer) =>
val finalizerName = currentUnit.freshTermName("finalizer")
val resultName = currentUnit.freshTermName("result")
q"""
$catchIdent.tryCatch { ($resultName: $tpe) => ${{
cpsAttachment(finalizer) { finalizerValue =>
q"""
..${notPure(finalizerValue)}
${continue(q"$resultName")}
"""
}
}}}.apply(
{ $finalizerName: ${TypeTree()} => ${cpsAttachment(block) { blockValue =>
q"$finalizerName.apply($blockValue)"
}}},
{
case ..${catches.map { caseDef =>
atPos(caseDef.pos) {
treeCopy.CaseDef(
caseDef,
caseDef.pat,
caseDef.guard,
q"""{ $finalizerName: ${TypeTree()} => ${{
cpsAttachment(caseDef.body) { bodyValue =>
q"$finalizerName.apply($bodyValue)"
}
}}}"""
)
}
}}}
)
"""
case Assign(lhs, rhs) =>
cpsAttachment(rhs) { rhsValue =>
continue(treeCopy.Assign(tree, lhs, rhsValue))
}
case q"while($condition) $body" =>
// TODO: Trampoline
val continueName = currentUnit.freshTermName("continue")
val conditionHandlerName = currentUnit.freshTermName("conditionHandler")
q"""
$whileDef
$whileName({
${continue(q"()")}
})({ $continueName: ${TypeTree()} => ${cpsAttachment(body) { bodyValue =>
q"""
..${notPure(bodyValue)}
$continueName
"""
}}},
{ $conditionHandlerName: ${TypeTree()} => ${cpsAttachment(condition) { conditionValue =>
q"$conditionHandlerName.apply($conditionValue)"
}}})
"""
case q"do $body while($condition)" =>
// TODO: Trampoline
val continueName = currentUnit.freshTermName("continue")
val conditionHandlerName = currentUnit.freshTermName("conditionHandler")
q"""
$doWhileDef
$doWhileName({
${continue(q"()")}
})({ $continueName: ${TypeTree()} => ${cpsAttachment(body) { bodyValue =>
q"""
..${notPure(bodyValue)}
$continueName
"""
}}},
{ $conditionHandlerName: ${TypeTree()} => ${cpsAttachment(condition) { conditionValue =>
q"$conditionHandlerName.apply($conditionValue)"
}}})
"""
case Throw(expr) =>
cpsAttachment(expr) { exprValue =>
continue(treeCopy.Throw(tree, exprValue))
}
case Return(expr) =>
cpsAttachment(expr) { exprValue =>
continue(treeCopy.Return(tree, exprValue))
}
case tree =>
reporter.info(tree.pos, "CPS-transformation is skipped for this tree", force = false)
continue(tree)
}
}
if (mode.inExprMode) {
val symbol = tree.symbol
tree match {
case q"$shiftOps.$shiftMethod" if symbol != null && symbol.hasAnnotation(shiftSymbol) =>
def attachment: CpsAttachment = { continue: (Tree => Tree) =>
// FIXME: tpe is a by-name type. I don't know why.
cpsAttachment(shiftOps) { shiftOpsValue =>
atPos(tree.pos) {
q"""
$shiftOpsValue.cpsApply(${toFunction1(continue, tpe)})
"""
}
}
}
tree.updateAttachment[CpsAttachment](attachment)
case _ =>
if (isCpsTree(tree)) {
tree.updateAttachment[CpsAttachment](cps)
}
}
}
tpe
}
}
private trait AnnotationSymbols {
private[BangNotation] lazy val resetAnnotationSymbol = symbolOf[ResetAnnotation]
private[BangNotation] lazy val shiftSymbol = symbolOf[shift]
}
val name: String = "BangNotation"
override def init(options: List[String], error: String => Unit): Boolean = {
super.init(options, error) && {
try {
global.analyzer.addAnalyzerPlugin(new Deactable with TreeResetter with BangNotationTransformer)
true
} catch {
case e: ScalaReflectionException =>
error("""The BangNotation compiler plug-in requires the runtime library:
libraryDependencies += "com.thoughtworks.dsl" %% "dsl" % "latest.release"
""")
false
}
}
}
val description: String =
"A compiler plugin that converts native imperative syntax to monadic expressions or continuation-passing style expressions"
val components = Nil
}