So I got it mostly working, here is an example:
def eqImpl[A: c.WeakTypeTag](c: Context)(e1: c.Expr[A], e2: c.Expr[A]): c.Expr[Boolean] = {
import c.universe._
val tpe = c.weakTypeOf[A].typeSymbol.asClass
tpe.typeSignature // SI-7046 workaround
val subclasses = tpe.knownDirectSubclasses
val cases =
subclasses.map{ case clazz : ClassSymbol =>
require (clazz.isCaseClass)
val name = clazz.companionSymbol.name
val fields = clazz.typeSignature.declarations.collect {
case m: MethodSymbol if m.isCaseAccessor => m.name}
//pattern for the fields of the left and right side side
val lFields = fields.map{ m => pq"""${m+"L":TermName}"""}
val rFields = fields.map{ m => pq"""${m+"R":TermName}"""} side
//right hand side of the case statment
val eqFields =
fields.map{ m => q"""${m+"R":TermName} == ${m+"L":TermName}"""}.reduce[Tree]{
case (acc,n) => q"$acc && $n"}
cq"($name(..$lFields),$name(..$rFields)) => $eqFields "
}
val matchStmt = q"""Tuple2[$tpe,$tpe]($e1,$e2) match {
case ..$cases
case _ => false }"""
c.Expr[Boolean](matchStmt)
}
}
This code creates a match statement, that matches a tuple. If both sides of the tuple are instances of the same case class, the fields are compared. True is returned, if all fields are equal. I know that is not a particularly realistic example, but I hope it helps. For the example from the question this would generate:
Tuple2[Foobar,Foobar](e1,e2) match {
case (Foo(xL,fL),Foo(xR,fR) => xL == xR && fL == fR
case (Bar(sL,fL),Bar(sR,fR) => sL == sR && fL == fR
case _ => false
}