Skip to content

@travisbrown /ImportExample.scala
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.