7

Given the following:

src/main/scala/net/Equals5.scala

package net

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

case class Equals5(value: Int) {
    require(value == 5)
}

object Equals5 {
    implicit def wrapInt(n: Int): Equals5 = macro verifyIntEquals5

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

    val tree = n.tree match {
      case Literal(Constant(x: Int)) if x == 5 =>
        q"_root_.net.Equals5($n)"
      case Literal(Constant(x: Int)) =>
        c.abort(c.enclosingPosition, s"$x != 0")
      case _ => 
        q"_root_.net.Equals5($n)"
    }
    c.Expr(tree)
  }
}

build.sbt

val paradiseVersion = "2.1.0-M5"

scalaVersion := "2.11.7"

libraryDependencies += "org.scala-lang" % "scala-reflect" % "2.11.7"

libraryDependencies += "org.scalatest" % "scalatest_2.10" % "3.0.0-M7"

project/build.properties

sbt.version=0.13.0

I can compile successfully, but trying to run the following test:

src/test/scala/net/Equals5Test.scala

package net

import org.scalatest.Matchers

import org.scalatest._
import org.scalatest.prop.Checkers._

class Equals5Test extends FlatSpec with Matchers {

    "Trying to create an `Equals5` case class with an invalid Int" should "fail to compile" in {
        "Equals5(-555)" shouldNot compile
    }
}

gives a compile-time error:

.../Equals5Test.scala:11: can't expand macros compiled 
      by previous versions of Scala
[error]         "Equals5(-555)" shouldNot compile
[error]                                   ^

Looking at this answer, I expected that using scala 2.11 with sbt 0.13.0 would've fixed this issue.

Please let me know how to resolve this compile-time error.

Community
  • 1
  • 1
Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384
  • Why are you using `"org.scalatest" % "scalatest_2.10"` instead of `"org.scalatest" %% "scalatest"` ? do you have any reason ? – ymonad Aug 25 '15 at 03:54
  • I have similar problem as well. Wonder if you have sorted this out? In my case, I have bumped the scalatest version (one hurdle solved), but I still got the problem at the serialisation level. – zochhuana Mar 09 '16 at 16:45
  • you should use scala 2.10.4 or 2.10.x FYI, http://stackoverflow.com/questions/27888182/cant-expand-macros-compiled-by-previous-versions-of-scala-scala-2-11-4-sbt-0 – gaozhidf Mar 29 '17 at 15:28

1 Answers1

12

You are specifically requesting ScalaTest version which is compiled for Scala 2.10, so its macros like compile won't be expanded correctly (and it's quite likely not to be compatible with Scala 2.11 in other ways as well). (Also current SBT version is 0.13.9, so you may want to update to it as well.)

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487