I am trying to write a macro in Scala 3, which will resolve the types defined in the case class and then find for the given/implict method for those type.
below is the code for macro.
import scala.quoted.*
object TransformerMacro:
inline def resolveTransformer[T] = ${ resolveTransformerImpl[T] }
def resolveTransformerImpl[T: Type](using Quotes) =
import quotes.reflect.*
val tpe = TypeRepr.of[T]
val typeMembersAll = tpe.typeSymbol.declaredTypes.map {
case typ if typ.isType =>
val typeName = typ.name
val typeBound = tpe.memberType(typ)
typeName -> typeBound
}
val outType = typeMembersAll.head._2
val inType = typeMembersAll.last._2
(outType, inType) match {
case (TypeBounds(_, oT), TypeBounds(_, iT)) =>
(oT.asType, iT.asType) match {
case ('[o], '[i]) =>
val itn = Type.show[i]
val otn = Type.show[o]
Expr.summon[TR[o, i]] match {
case Some(instance) =>
report.info(s"We might find the implicit now $itn, $otn $instance")
'{Some(${instance})}
case None =>
report.error(s"No Implicit Found for type: \nReModel[$itn, $otn]")
'{ None }
}
}
}
Example:
case class Person(name: String, age: Int, email: Option[String]):
type R = String
type M = Int
trait TR[A, B]:
def f(a: A) : B
object TR:
given strToInt: TR[Int, String] with
override def f(from: Int): String = from.toString
For the case class Person the macro will resolve the type of R and M, and will try to find the Implicit of type TR in the scope.
But the macro is also going into the None case and giving below error
report.error(s"No Implicit Found for type: \nTR[$itn, $otn]")
driver code for the macro
def main(args: Array[String]): Unit =
val resolved = TransformerMacro.resolveTransformer[Person]
println(resolved)
report.error(s"No Implicit Found for type: \nTR[$itn, $otn]").