宏扩展后编译错误“找不到值...”

时间:2018-03-06 16:29:48

标签: scala scala-macros scala-reflect

我是scala-macros的新手。我正在为InfluxDB客户端编写一个自动JSON编写器/阅读器。

读者看起来像:

trait InfluxReader[T] {
  def read(js: JsArray): T
} 

InfluxFormatter:

object InfluxFormatter {
  /**
    * Generate InfluxReader for type ${A}
    */
  def reader[A]: InfluxReader[A] = macro InfluxFormatterImpl.reader_impl[A]
}

InfluxFormatterImpl:

private[macros] object InfluxFormatterImpl {
  /***
    * Generate AST for current type at compile time.
    * @tparam T - Type parameter for whom will be generated AST
    */
  def reader_impl[T: c.WeakTypeTag](c: blackbox.Context): c.universe.Tree = {
    import c.universe._

    val tpe = c.weakTypeOf[T]

    val methods = tpe.decls.toList collect {
      case m: MethodSymbol if m.isCaseAccessor =>
        m.name.decodedName.toString -> m.returnType.dealias
    }

    if (methods.lengthCompare(1) < 0) {
      c.abort(c.enclosingPosition, "Type parameter must be a case class with more then 1 fields")
    }

    val bool = typeOf[Boolean].dealias
    val int = typeOf[Int].dealias
    val long = typeOf[Long].dealias
    val double = typeOf[Double].dealias
    val string = typeOf[String].dealias

    val params = methods
      .map(_._1)
      .sorted
      .map(v => TermName(v))
      .map(v => q"$v = $v")

    val jsParams = methods
      .sortBy(_._1) // influx return results in alphabetical order
      .map { case (k, v) => TermName(k) -> v }
      .map {
        case (name, `bool`) => q"JsBoolean($name)"
        case (name, `string`) => q"JsString($name)"
        case (name, `int`) => q"JsNumber($name)"
        case (name, `long`) => q"JsNumber($name)"
        case (name, `double`) => q"JsNumber($name)"
        case (_, other) => c.abort(c.enclosingPosition, s"Unknown type $other")
      }

    val failureMsg = s"Can't deserialize $tpe object"

    val result = q"""
        new InfluxReader[$tpe] {
          def read(js: JsArray): $tpe = js.elements.tail match {
            case Vector(..$jsParams) => new $tpe(..$params)
            case _ => throw DeserializationException($failureMsg)
          }
       }"""

    result
  }
}

测试规范:

import com.github.fsanaulla.core.model._
import com.github.fsanaulla.core.utils._
import com.github.fsanaulla.macros.InfluxFormatter
import org.scalatest.{FlatSpec, Matchers}
import spray.json._

class MacroReaderSpec extends FlatSpec with Matchers {

  "Macros" should "generate reader" in {
    case class Test(name: String, age: Int)

    val rd: InfluxReader[Test] = InfluxFormatter.reader[Test]

    rd.read(JsArray(JsNumber(234324), JsNumber(4), JsString("Fz"))) shouldEqual Test("Fz", 4)
  }
}

编译MacroReaderSpec失败并出现编译错误:

Error:(14, 36) not found: value age
val rd = InfluxFormatter.reader[Test]
Error:(14, 36) not found: value name
val rd = InfluxFormatter.reader[Test]

使用编译器选项"-Ymacro-debug-lite",它看起来像:

Warning:scalac: {
  final class $anon extends InfluxReader[Test] {
    def <init>() = {
      super.<init>();
      ()
    };
    def read(js: JsArray): Test = js.elements.tail match {
      case Vector(JsNumber(age), JsString(name)) => new Test(age = age, name = name)
      case _ => throw DeserializationException("Can\'t deserialize Test object")
    }
  };
  new $anon()
}

错误出现在模式部分的这行代码中:

case Vector(JsNumber(age), JsString(name)) => new Test(age = age, name = name)

为什么找不到它?我认为它无法将其识别为模式匹配的表达式,也无法调用提取器。如果是,如何改变它?也许它以某种方式将其称为分数? 我正在使用scala 2.12.4。 Sbt 1.1.0。 可以找到源代码here

谢谢大家。

1 个答案:

答案 0 :(得分:1)

已通过使用pq拟引号重写代码来解决此问题。同样,所有标识符都必须包装到TermName(_)中。可以找到有效的示例here