0

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 }
            }
        }
    }

Scastie

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)
4
  • What is the error you get? (Macros cannot be run in Scastie so I cannot run the example without investing some time into it). Commented Dec 16, 2024 at 15:56
  • @MateuszKubuszok At compile time Even if given/implicits are in scope it's not able to find and return None as I mention it gives report.error(s"No Implicit Found for type: \nTR[$itn, $otn]"). Commented Dec 16, 2024 at 17:33
  • 1
    This is not the error message: I want to know what is the type printed by report.error, what is the content of $itn/$otn. Commented Dec 16, 2024 at 20:46
  • @MateuszKubuszok this is the compilation error: and the type for itn and otn are String and Int respectively. No Implicit Found for type: TR[scala.Int, java.lang.String] val resolved = TransformerMacro.resolveTransformer[Person] Commented Dec 16, 2024 at 21:06

1 Answer 1

1

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]])
    }
Sign up to request clarification or add additional context in comments.

2 Comments

I have both the given instance in the scope TR[String, Int] and TR[Int, String] but it's the same not able to find the instance, that's not an issue I tried with both the combination.
Then you have not posted a complete example because this code compiles on my computer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.