使用宏来创建案例类

时间:2015-04-29 16:33:41

标签: scala scala-macros

给出以下宏(感谢此@TravisBrownhelp):

JetDim.scala

case class JetDim(dimension: Int) {
  require(dimension > 0)
}

object JetDim {
  def validate(dimension: Int): Int = macro JetDimMacro.apply
  def build(dimension: Int): JetDim = JetDim(validate(dimension))
}

JetDimMacro.scala

import reflect.macros.Context

object JetDimMacro {

    sealed trait PosIntCheckResult
    case class LteqZero(x: Int) extends PosIntCheckResult
    case object NotConstant extends PosIntCheckResult

    def apply(c: Context)(dimension: c.Expr[Int]): c.Expr[Int] = {

        import c.universe._

        getInt(c)(dimension) match {
            case Right(_)          => reify { dimension.splice }
            case Left(LteqZero(x)) => c.abort(c.enclosingPosition, s"$x must be > 0.")
            case Left(NotConstant) => reify { dimension.splice }
        }
    }

    def getInt(c: Context)(dimension: c.Expr[Int]): Either[PosIntCheckResult, Int] = {

        import c.universe._

        dimension.tree match {
            case Literal(Constant(x: Int)) => if (x > 0) Right(x) else Left(LteqZero(x))
            case _                         => Left(NotConstant)
        }
    }
}

它适用于REPL:

scala> import spire.math.JetDim
import spire.math.JetDim

scala> JetDim.validate(-55)
<console>:9: error: -55 must be > 0.
              JetDim.validate(-55)
                             ^

scala> JetDim.validate(100)
res1: Int = 100

但是,我想将此编译时检查(通过JetDimMacro)构建到案例类的apply方法中。

尝试1

case class JetDim(dimension: Int) {
  require(dimension > 0)
}

object JetDim {
  private def validate(dimension: Int): Int = macro JetDimMacro.apply
  def build(dimension: Int): JetDim = JetDim(validate(dimension))
}

但那失败了:

scala> import spire.math.JetDim
import spire.math.JetDim

scala> JetDim.build(-55)
java.lang.IllegalArgumentException: requirement failed
  at scala.Predef$.require(Predef.scala:207)
  at spire.math.JetDim.<init>(Jet.scala:21)
  at spire.math.JetDim$.build(Jet.scala:26)
  ... 43 elided

尝试2

class JetDim(dim: Int) {
  require(dim > 0)

  def dimension: Int = dim
}

object JetDim {
  private def validate(dimension: Int): Int = macro JetDimMacro.apply
  def apply(dimension: Int): JetDim = {
    validate(dimension)
    new JetDim(dimension)
  }
}

然而那也失败了:

scala> import spire.math.JetDim
import spire.math.JetDim

scala> JetDim(555)
res0: spire.math.JetDim = spire.math.JetDim@4b56f205

scala> JetDim(-555)
java.lang.IllegalArgumentException: requirement failed
  at scala.Predef$.require(Predef.scala:207)
  at spire.math.JetDim.<init>(Jet.scala:21)
  at spire.math.JetDim$.apply(Jet.scala:30)
  ... 43 elided

我想修改JetDimMacro#apply以返回JetDim而不是Int。但是,JetDim项目存在于core项目中,根据我的看法,该项目取决于macros项目(JetDimMacro所在的项目)。

如何使用validate配套对象中的JetDim方法在编译时检查正数?

1 个答案:

答案 0 :(得分:1)

问题在于,当我们在validate中调用apply时,我们不再处理常量(单例类型)。因此,validate获得一个非常数Int。

作为替代方案,您可以尝试使用隐式见证作为正整数,然后JetDim将其作为构造函数。例如,像:

package com.example

case class JetDim(n: PositiveInt)

case class PositiveInt(value: Int) {
  require(value > 0)
}

然后,我们添加了Int => PositiveInt的隐式(宏)转换,用于检查。

import scala.language.experimental.macros

import scala.reflect.macros.blackbox.Context

object PositiveInt {
  implicit def wrapConstantInt(n: Int): PositiveInt = macro verifyPositiveInt

  def verifyPositiveInt(c: Context)(n: c.Expr[Int]): c.Expr[PositiveInt] = {
    import c.universe._

    val tree = n.tree match {
      case Literal(Constant(x: Int)) if x > 0 =>
        q"_root_.com.example.PositiveInt($n)"
      case Literal(Constant(x: Int)) =>
        c.abort(c.enclosingPosition, s"$x <= 0")
      case x =>
        c.abort(c.enclosingPosition, s"cannot verify $x > 0")
    }
    c.Expr(tree)
  }
}

然后你可以使用JetDim(12),它将通过,或JetDim(-12),它将失败(宏将Int扩展为PositiveInt)。