Scala macro for assigned value label in apply method

112 views Asked by At

From object Naming below (adapted from answer in Scala macro get enclosing line), which gathers the label associated to a value,

val x = Naming.apply("")
x: String = x

would like to modify the apply method so that it would deliver a new Naming instance where assignedName takes the assigned value label, namely,

val x = Naming()
assert( x.assignedName == "x")

In the code that follows, a naƮve change like this

def apply(s: String): String = Naming( macro impl )

cannot work. Any working approach to instantiate assignedName is much valued.

case class Naming(var assignedName: String = "") {
  val m = collection.mutable.Map[String,Int]()
}

object Naming {

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

  def apply(s: String): String = macro impl 

  def impl(c: Context)(s: c.Expr[String]): c.Expr[String] = {
    import c.universe._

    c.enclosingClass.collect {
      case ValDef(_, name, _, rhs) if rhs.pos == c.macroApplication.pos =>
        c.literal(name.decoded)
    }.headOption.getOrElse(
      c.literal("")
    )
  }

}

Update In apply method, reify'ing the Naming instance with assisgnedName updated might be a solution. If viable, how could this be implemented ?

0

There are 0 answers