Reputation: 2686
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)
Upvotes: 0
Views: 49
Reputation: 27595
The error was here:
Expr.summon[TR[o, i]]
everywhere else you used i
prefix for input and o
for output but here you swapped the values together: you looked for TR[String, Int]
and on failure was printing not found TR[Int, String]
- that's why it's useful to deduplicate the logic, if it was not found TR[String, Int]
the issue would be immediately obvious.
It could have been implemented much easier with:
import scala.quoted.*
object TransformerMacro:
inline def resolveTransformer[T] = ${ resolveTransformerImpl[T] }
def resolveTransformerImpl[T: Type](using Quotes) =
import quotes.reflect.*
// Help us extract member types without weird shenanigans
type Aux[I, O] = Person { type R = O; type M = I }
Type.of[T] match {
case '[Aux[i, o]] => // much simpler extraction
// reuse computed type for both summoning and printing
def handle[A: Type] = {
Expr.summon[A] match {
case Some(instance) =>
report.info(s"We might find the implicit now ${instance.asTerm.show}: ${TypeRepr.of[A].show}")
'{Some(${instance})}
case None =>
report.error(s"No Implicit Found for type: \n${TypeRepr.of[A].show}")
'{ None }
}
}
handle(using Type.of[TR[i, o]])
}
Upvotes: 1