Created
February 13, 2014 00:35
-
-
Save non/8967469 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
package demo | |
case class Wrapper[A](arr: Array[A]) | |
object Wrapper { | |
def literal[A](as: A*): Wrapper[A] = wrapperMacro | |
} | |
object Example { | |
def array[A](as: A*) = macro arrayMacro[A] | |
def arrayMacro[A: c.WeakTypeTag](c: Context)(as: c.Expr[A]*): c.Expr[Array[A]] = { | |
import c.mirror._ | |
import c.universe._ | |
val n = as.length | |
val tpe = implicitly[c.WeakTypeTag[A]].tpe | |
val valdef = q"val arr = new Array[$tpe]($n)" | |
val updates = as.toList.zipWithIndex.map { case (a, i) => | |
q"arr($i) = ${a.tree}" | |
} | |
c.Expr[Array[A]](Block(valdef :: updates, q"arr")) | |
} | |
def wrapperMacro[A: c.WeakTypeTag](c: Context)(as: c.Expr[A]*): c.Expr[demo.Wrapper[A]] = { | |
import c.mirror._ | |
import c.universe._ | |
val arr = arrayMacro(c)(as: _*) | |
c.Expr[demo.Wrapper[A]](q"demo.Wrapper($arr)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment