public
Last active

  • Download Gist
ImportExample.scala
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
import scala.language.experimental.macros
import scala.reflect.macros.Context
 
object ImportExample {
def demo = macro demo_impl
 
def demo_impl(c: Context) = {
import c.universe._
 
def toQual(sym: Symbol): Tree = sym.owner.owner match {
case NoSymbol => Ident(sym.companionSymbol)
case owner => Select(toQual(sym.owner), sym.companionSymbol.name)
}
 
def selector(name: Name) = {
val termName = name.toTermName
ImportSelector(termName, -1, termName, -1)
}
 
def importPackageOrClass(sym: Symbol): Import = Import(
toQual(sym.owner),
List(
if (sym.isPackage || sym.isModule) ImportSelector(
nme.WILDCARD, -1, null, -1
) else if (sym.isClass) selector(sym.name) else ???
)
)
 
val imports = List(
typeOf[scala.util.parsing.combinator.RegexParsers].typeSymbol
).map(sym => importPackageOrClass(sym))
 
val anon = newTypeName(c.fresh())
 
val tree = Block(
imports :+ ClassDef(
Modifiers(Flag.FINAL),
anon,
Nil,
Template(
Ident(newTypeName("RegexParsers")) :: Nil,
emptyValDef,
DefDef(
Modifiers(),
nme.CONSTRUCTOR,
Nil,
Nil :: Nil,
TypeTree(),
Block(
Apply(
Select(Super(This(tpnme.EMPTY), tpnme.EMPTY), nme.CONSTRUCTOR),
Nil
) :: Nil,
c.literalUnit.tree
)
) :: Nil
)
),
Apply(Select(New(Ident(anon)), nme.CONSTRUCTOR), Nil)
)
 
println(tree)
 
c.Expr[scala.util.parsing.combinator.RegexParsers](tree)
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.