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]