Created
December 6, 2013 13:33
-
-
Save xeno-by/7823878 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.reflect.macros.WhiteboxContext | |
import scala.language.experimental.macros | |
import scala.reflect.api.Liftable | |
import scala.reflect.macros.Universe | |
import scala.reflect.api.Position | |
object Macros { | |
implicit def liftableCaseClass[T]: Liftable[T] = macro impl[T] | |
def impl[T: c.WeakTypeTag](c: WhiteboxContext) = { | |
import c.universe._ | |
val T = weakTypeOf[T] | |
if (!T.typeSymbol.asClass.isCaseClass) c.abort(c.enclosingPosition, "Not a case class") | |
else { | |
val params = T.members.collect { case x: MethodSymbol if x.isCaseAccessor => q"cc.$x" }.toList.reverse | |
q""" | |
import scala.reflect.api.Liftable | |
new Liftable[$T] { | |
def apply(universe: reflect.api.Universe, cc: $T): universe.Tree = { | |
val ttree = universe.TypeTree(universe.typeOf[$T]) | |
universe.Apply(universe.Select(universe.New(ttree), universe.nme.CONSTRUCTOR), List()) | |
} | |
} | |
""" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment