Skip to content

Instantly share code, notes, and snippets.

@non
Created Feb 13, 2014
Embed
What would you like to do?
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