Home > database >  Get enclosing module in Scala 3 macros
Get enclosing module in Scala 3 macros

Time:10-07

How do I get the enclosing module of a macro call.

package foo.bar
class MyClass:
  val macroReturnValue = SomeMacro.macroCall("someExpression")
end MyClass

macroReturnValue should contain e.g. "foo.bar.MyClass"

CodePudding user response:

Try

import scala.quoted.*

object SomeMacro:
  inline def macroCall(s: String): String = ${macroCallImpl('s)}

  def macroCallImpl(s: Expr[String])(using Quotes): Expr[String] =
    import quotes.reflect.*
    def enclosingClass(symb: Symbol): Symbol = 
      if symb.isClassDef then symb else enclosingClass(symb.owner)
    val name = enclosingClass(Symbol.spliceOwner).fullName
    Literal(StringConstant(name)).asExprOf[String]
  • Related