How can I untangle quotes and levels in Scala 3 macros?

31 Views Asked by At

I'm trying to untangle something... I'm struggling getting things I need at the right staging level. I'm trying to reflect on a class, who's name is given at runtime (not known at compile-time other than guaranteed given class is in the ClassPath).

Needed usgage:

val cname = "com.foo.MyClass"
examineClass(cname)

// Important:  This will NOT work-> examineClass("com.foo.MyClass")
// The real program will get the className from an external source.

Implementation:

  inline def examineClass(className: String): ResultRecor = ${ examineClassImpl('className) }

  def examineClassImpl(className: Expr[String])(using q: Quotes): Expr[RType[?]] =
    import quotes.reflect.*
    // Compile-time scope: At this point className.value is null--not set until runtime stage in '{}
    '{
      val cn = $className  // Runtime-scope: At this point $className a desired value, i.e. className.value.get is non-null
      ${ reflectOnClass(q)(q.reflect.TypeRepr.typeConstructorOf(Class.forName(cn))) }
    }

My problem: I get level 0/1 staging errors for cn in Class.forName(cn). That big reflectionOnClass function needs to be at compile-time to use Quotes.

How can I somehow get cn "passed-in" to that function?

0

There are 0 best solutions below