在 Scala 3 宏中获取封闭模块
Get enclosing module in Scala 3 macros
如何获取宏调用的封闭模块。
package foo.bar
class MyClass:
val macroReturnValue = SomeMacro.macroCall("someExpression")
end MyClass
macroReturnValue
应该包含例如"foo.bar.MyClass"
尝试
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]
如何获取宏调用的封闭模块。
package foo.bar
class MyClass:
val macroReturnValue = SomeMacro.macroCall("someExpression")
end MyClass
macroReturnValue
应该包含例如"foo.bar.MyClass"
尝试
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]