Scala 宏 - 使用“c.prefix”推断隐式值

Scala macro - Infer implicit value using `c.prefix`

c.inferImplicitValue 推断调用站点范围内的隐式值。是否可以使用 c.prefix 范围推断隐式?

这不是有效代码,但表达了我的需要:

c.prefix.inferImplicitValue

我目前正在为此目的使用一个简单的实现[1],但它有一些限制,比如不从 def 推断隐式值和检测 duplicated/ambiguous 隐式值。

[1] https://github.com/getquill/quill/blob/9a28d4e6c901d3fa07e7d5838e2f4c1f3c16732b/quill-core/src/main/scala/io/getquill/util/InferImplicitValueWithFallback.scala#L12

只需生成一个带有适当(本地)导入的块,然后调用 implicitly 就可以了:

q"""{import ${c.prefix}._; _root_.scala.Predef.implicitly[$T] }

其中 TType 的实例,表示要查找的隐式值的类型。

要检查隐式查找是否真的成功,您可以用 silent=true 调用 Context.typeCheck 并检查结果树是否为空。

作为说明,这里是一个实现 infer 方法的示例,如果在目标对象的成员中未找到隐式,则返回 None,否则将结果包装在 Some.

import scala.reflect.macros.Context
import scala.language.experimental.macros

def inferImplicitInPrefixContext[T:c.WeakTypeTag](c: Context): c.Tree = {
  import c.universe._
  val T = weakTypeOf[T]
  c.typeCheck(
    q"""{
      import ${c.prefix}._
      _root_.scala.Predef.implicitly[$T]
    }""",
    silent = true
  )
}

def infer_impl[T:c.WeakTypeTag](c: Context): c.Expr[Option[T]] = {
  import c.universe._
  c.Expr[Option[T]](
    inferImplicitInPrefixContext[T](c) match {
      case EmptyTree => q"_root_.scala.None"
      case tree => q"_root_.scala.Some($tree)"
    }
  )
}

trait InferOp {
  def infer[T]: Option[T] = macro infer_impl[T]
}

我们来测试一下:

object Foo extends InferOp {
  implicit val s = "hello"
}

Foo.infer[String] // res0: Some[String] = Some(hello)

Foo.infer[Int] // res1: None.type = None

implicit val lng: Long = 123L

Foo.infer[Long] // res2: Some[Long] = Some(123)