当Scala宏生成时,依赖类型似乎“不起作用”

问题描述 投票:3回答:1

为handwavey标题道歉。我不完全确定如何简洁地说出这个问题,因为我以前从未遇到过这样的问题。

背景资料:

我有以下特征,其中U类型意味着持有Shapeless extensible record类型:

trait Flattened[T] {
  type U <: shapeless.HList
  def fields: U
}

我正在使用blackbox宏(出于此问题范围之外的原因)来创建特征的新实例:

object flatten {

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

  def apply[T](struct: T): Flattened[T] =
    macro impl[T]

  def impl[T : c.WeakTypeTag](c: Context)(struct: c.Tree): c.Tree = {
    import c.universe._

    // AST representing a Shapeless extensible record (actual
    // implementation uses values in `struct` to construct this
    // AST, but I've simplified it for this example).
    val fields: Tree = q"""("a" ->> 1) :: ("b" ->> "two") :: ("c" ->> true) :: HNil"""

    // Result type of the above AST
    val tpe: TypeTree = TypeTree(c.typecheck(q"$fields").tpe)

    q"""
    new Flattened[${weakTypeOf[T]}] {
      import shapeless._
      import syntax.singleton._
      import record._

      type U = $tpe
      val fields = $fields
    }
    """
  }
}

问题:

问题是,当我使用这个宏来创建Flattened的新实例时,fields的类型不再是可扩展的记录:

import shapeless._
import syntax.singleton._
import record._

val s = "some value... it doesn't matter for this example, since it isn't used. I'm just putting something here so the example compiles and runs in a REPL."
val t = flatten(s)

val fields = t.fields
// fields: t.U = 1 :: "two" :: true :: HNil

fields("a")  // compile error!

// The compile error is:
//     cmd5.sc:1: No field String("a") in record ammonite.$sess.cmd4.t.U
//     val res5 = fields("a")
//                      ^
//     Compilation Failed

边注:

奇怪的是,如果我手动做宏的工作,它的工作原理是:

// I can't actually instantiate a new `Flattened[_]` manually, since
// defining the type `U` would be convoluted (not even sure it can be
// done), so an object with the same field is the next best thing.
object Foo {
  import shapeless._
  import syntax.singleton._
  import record._

  val fields = ("a" ->> 1) :: ("b" ->> "two") :: ("c" ->> true) :: HNil
}

val a = Foo.fields("a")
// a: Int = 1

val b = Foo.fields("b")
// b: String = "two"

val c = Foo.fields("c")
// c: Boolean = true

为什么会出现这种差异,如何使宏版本的行为与手动版本相同?

scala shapeless scala-macros dependent-type scala-quasiquotes
1个回答
3
投票

可能是你的宏没有错。这是类型签名:

def apply[T](struct: T): Flattened[T] = macro impl[T]
def impl[T : c.WeakTypeTag](c: Context)(struct: c.Tree): c.Tree

你正在使用黑盒宏,根据the documentation,黑盒宏对他们的签名是真实的。也就是说,即使impl产生一个Flattened[T] { type U = ... },它是一个黑盒宏的事实意味着scalac总是将它包裹在(_: Flattened[T])中,忘记了U在细化中的定义。将其设为白盒宏:

// import scala.reflect.macros.blackbox.context // NO!
import scala.reflect.macros.whitebox.context
def impl[T: c.WeakTypeTag](c: Context)(struct: c.Tree): c.Tree
© www.soinside.com 2019 - 2024. All rights reserved.