Last active
December 19, 2015 11:29
-
-
Save travisbrown/5948460 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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