Search code examples
scalamacros

Cannot resolve symbol apply using macro in Scala 2.13


I am trying to upgrade my codebase from 2.11.8 to 2.13.15 And I have an error inside my HandOnSuite trait

trait HandsOnSuite extends AnyFunSpec with Matchers with ScalaFutures {
  def exercice(testName: String)(testFun: Unit)(implicit suite: HandsOnSuite): Unit = macro ExerciceMacro.apply
}

It can't find the apply method which is defined by a macro

package support

import scala.reflect.macros.blackbox
import scala.reflect.macros.blackbox.Context

class ExerciceMacro[C <: Context](val c: C) {
  import c.universe._

  def apply(testName: c.Expr[String])(testFun: c.Expr[Unit])(suite: c.Expr[HandsOnSuite]): c.Expr[Unit] = {
    val code = testFun.tree.pos.source.content.mkString
    val (start, end) = testFun.tree match {
      case Block(xs, expr) => (testFun.tree.pos.line, expr.pos.line)
      case _ => (testFun.tree.pos.line, testFun.tree.pos.line)
    }
    c.Expr(q"""$suite.testExercice($testName)($testFun)(new support.TestContext($code, $start, $end))""")
  }
}

object ExerciceMacro {
  def apply(c: blackbox.Context)(testName: c.Expr[String])(testFun: c.Expr[Unit])(suite: c.Expr[HandsOnSuite]): c.Expr[Unit] = {
    new ExerciceMacro[c.type](c).apply(testName)(testFun)(suite)
  }
}

Any tips to how can I upgrade this ? I can't find some documentation regarding macro

Using Intellij, I had invalidated my cache but it did not work


Solution

  • Try to replace this

    class ExerciceMacro[C <: Context](val c: C) {
      import c.universe._
    
      def apply(testName: c.Expr[String])(testFun: c.Expr[Unit])(suite: c.Expr[HandsOnSuite]): c.Expr[Unit] = ...
    }
    
    object ExerciceMacro {
      def apply(c: blackbox.Context)(testName: c.Expr[String])(testFun: c.Expr[Unit])(suite: c.Expr[HandsOnSuite]): c.Expr[Unit] = ...
    }
    

    with this:

    class ExerciceMacro(val c: blackbox.Context) {
      import c.universe._
    
      def apply(testName: c.Expr[String])(testFun: c.Expr[Unit])(suite: c.Expr[HandsOnSuite]): c.Expr[Unit] = ...
    }
    
    // no companion object