作用域中的隐式参数不应该用作宏生成代码的隐式参数吗?

时间:2019-04-26 19:17:06

标签: scala scala-macros

我正在尝试使生成类型类实例的现有宏适用于参数化类型,其中类型参数已经具有类型类的实例。我很惊讶在这种情况下它无法解决现有的(类型实参的)类型类,但这似乎正在发生。

我已尝试将其简化为一个显示该行为的小示例。这是宏的定义:

package test

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

trait Read[A] {
  def read(in: String): A
}

object Read {
  def CaseClassReadImpl[A: c.WeakTypeTag](c: Context): c.Expr[Read[A]] = {
    import c.universe._
    val aType = weakTypeOf[A]

    val params = aType.decls.collect {
      case m: MethodSymbol if m.isCaseAccessor => m
    }.toList

    val paramList = params.map(param => q"Read.read[${param.typeSignature}](in)")

    val src = q"""
      new Read[$aType] {
        def read(in: String) = ${aType.typeSymbol.companion}.apply(..$paramList)
      }
    """

    c.Expr[Read[A]](src)
  }

  def readFor[A]: Read[A] = macro CaseClassReadImpl[A]

  def read[A](in: String)(implicit A: Read[A]): A = A.read(in)
}

这是执行它的代码:

package test

object MacroTest {
  case class Foo[A](bar: A)

  implicit def fooRead[A](implicit A: Read[A]): Read[Foo[A]] =
    Read.readFor[Foo[A]]
}

我期望这能够成功,因为认为生成的对Read.read调用的隐式参数将解析为fooRead函数的隐式参数。相反,使用以下命令定义fooRead时失败:

Error:(7, 17) could not find implicit value for parameter A: test.Read[A]
    Read.readFor[Foo[A]]

为什么不对A使用隐式参数fooRead?在词汇范围内。

我意识到我应该将该代码库转换为使用无形库或某种类似的库,但是现在我只是在尝试使其工作尽可能少。


更新

我发现问题出在两个不同的A之间。上面的错误使它看起来像所需的隐式类型与我在作用域中的隐式类型相同,但是经过一番摆弄并显式地传递了隐式后,我设法得到了此错误信息(更为有用): / p>

Error: type mismatch;
 found   : A(in class Foo)
 required: A(in method fooRead)
  implicit def fooRead[A](implicit read: Read[A]): Read[Foo[A]] = Read.readFor[Foo[A]]

我仍然无法找到一种方法使Scala理解我希望A保持一致:传递给fooRead函数的那个​​。

1 个答案:

答案 0 :(得分:0)

尝试替换

param => q"Read.read[${param.typeSignature}](in)"

param => q"Read.read[${param.typeSignatureIn(aType)}](in)"

https://github.com/scala/scala/blob/2.13.x/src/reflect/scala/reflect/api/Symbols.scala#L335-L345

/** @see [[infoIn]] */
def typeSignatureIn(site: Type): Type

/** The type signature of this symbol seen as a member of given type `site`.
 *
 *  @group Basics
 */
def infoIn(site: Type): Type

/** @see [[info]] */
def typeSignature: Type

/** The type signature of this symbol.
 *
 *  This method always returns signatures in the most generic way possible, even if the underlying symbol is obtained from an
 *  instantiation of a generic type. For example, signature
 *  of the method `def map[B](f: (A) ⇒ B): List[B]`, which refers to the type parameter `A` of the declaring class `List[A]`,
 *  will always feature `A`, regardless of whether `map` is loaded from the `List[_]` or from `List[Int]`. To get a signature
 *  with type parameters appropriately instantiated, one should use `infoIn`.
 *
 *  @group Basics
 */
def info: Type