How to use Shapeless in a Quasiquote?
This is my working solution using old-style macro annotations.
import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
import scala.annotation.StaticAnnotation
class fieldable extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro fieldableMacro.impl
}
object fieldableMacro {
def impl(c: Context)(annottees: c.Expr[Any]*): c.Tree = {
import c.universe._
annottees.map(_.tree) match {
case (param @ q"case class $className(..$fields)") :: Nil => {
val implicits = fields.collect {
case field @ q"$mods val $tname: $tpt" => q"""
implicit val $tname = Field.apply[$className,$tpt](
Witness(${tname.decodedName.toString}), _.$tname
)"""
}; q"$param; object ${className.toTermName} {..$implicits}"
}
}
}
}
It can be, for sure, improved using better quasiquotes, but my goal was to show something as cleaner as possible.
It can be used as:
@fieldable
case class MyCaseClass(foo: String, bar: Int)
This produces a MyCaseClass
companion object having required Fields
implicits:
implicit val foo = Field.apply[MyCaseClass, String](Witness("foo"), ((x$1) => x$1.foo));
implicit val bar = Field.apply[MyCaseClass, Int](Witness("bar"), ((x$2) => x$2.bar));
As it was already pointed out, without a complete working example, it's quite difficult to write an exhaustive answer.