Skip to content

Instantly share code, notes, and snippets.

@non
Created February 13, 2014 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save non/8967469 to your computer and use it in GitHub Desktop.
Save non/8967469 to your computer and use it in GitHub Desktop.
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