-
Notifications
You must be signed in to change notification settings - Fork 5
/
enableMembersIf.scala
64 lines (51 loc) · 1.86 KB
/
enableMembersIf.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
package com.thoughtworks
import scala.annotation.StaticAnnotation
import scala.reflect.internal.annotations.compileTimeOnly
import scala.reflect.macros.Context
import scala.util.matching.Regex
object enableMembersIf {
private[enableMembersIf] object Macros {
def macroTransform(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
import c.universe._
def constructors(body: List[Tree]): List[Tree] = {
(for {
constructor @ DefDef(_, nme.CONSTRUCTOR, _, _, _, _) <- body.view
} yield constructor).take(1).toList
}
val Apply(Select(Apply(_, List(condition)), _), List(_ @_*)) =
c.macroApplication
if (
c.eval(c.Expr[Boolean](q"""
import _root_.com.thoughtworks.enableIf._
_root_.com.thoughtworks.enableIf.isEnabled(${reify(
c
).tree}, $condition)
"""))
) {
c.Expr(q"..${annottees.map(_.tree)}")
} else {
val head = annottees.head.tree match {
case ClassDef(mods, name, tparams, Template(parents, self, body)) =>
ClassDef(
mods,
name,
tparams,
Template(parents, self, constructors(body))
)
case ModuleDef(mods, name, Template(parents, self, body)) =>
ModuleDef(mods, name, Template(parents, self, constructors(body)))
}
c.Expr(q"$head; ..${annottees.tail}")
}
}
}
}
@compileTimeOnly("enableIf.scala requires macros paradise plugin")
final class enableMembersIf(condition: Context => Boolean)
extends StaticAnnotation {
throw new AssertionError("enableIf.scala requires macro paradise plugin")
def this(condition: Boolean) = this { _ => condition }
import scala.language.experimental.macros
def macroTransform(annottees: Any*): Any =
macro enableMembersIf.Macros.macroTransform
}