如何从 Scala 3 宏中的外部范围获取变量初始化的主体?

How to get the body of variable initialisation from outer scope in Scala 3 macros?

假设我有这段代码用于提取初始化变量的代码:

def extractBodyImpl[T: Type](expr: Expr[T])(using Quotes) =
    import quotes.reflect._
    expr.asTerm.underlyingArgument match
        case ident @ Ident(_) =>
            ident.symbol.tree match
                case ValDef(_,_,rhs) => println(rhs)
                case DefDef(_,_,_,rhs) => println(rhs)
    '{ () }

inline def extractBody[T](inline expr: T) = ${ extractBodyImpl('expr) }

当调用在同一范围内声明的变量时,它会按预期工作:

@main def hello() =
  val x = 1
  extractBody(x)

打印 Some(Literal(Constant(1))).

然而,对于来自外部作用域的变量,它打印 None:

val x = 1
@main def hello() =
  extractBody(x)

在第二种情况下如何让它工作?

您不能在宏中执行此操作。接收参数的函数可能已从任何地方调用。静态分析将如何访问仅在运行时可用的信息?唯一可靠的解决方案是强制用户在定义值后立即展开此 extractBody 宏,并将结果传递到结合了值及其来源的包装器中。