lmars
lmars

Reputation: 302

How to get a `Symbol` of a member that is available via an implicit conversion?

I'm writing a macro which generate some code like this:

q"_root_.ru.lmars.macropack.TagsAndTags2.$tagName(..$tagParams)"

but I want to generate this code only if $tagName is defined and have some "marker" (like annotation or some special return type). How to get a Symbol of $tagName for this?

It's easy if $tagName is defined inside TagsAndTags2 object:

object TagsAndTags2
{
    def dialog(caption: String): String = ???
}

you can write something like this to get Symbol of dialog:

val tagParentAccess = q"_root_.ru.lmars.macropack.TagsAndTags2"
val tagParent = c.typecheck(tagParentAccess, silent = true)
val tagSymbol = tagParent.tpe.member(tagName)

But how to do the same if $tagName is available via an implicit conversion?

implicit final class UserTags(x: TagsAndTags2.type)
{
    def dialog(caption: String): String = ???
}

Upvotes: 0

Views: 147

Answers (1)

lxohi
lxohi

Reputation: 350

Here is a quick & dirty example (I've tried it in Scala 2.11):

temp/Foo.scala:

package temp

import scala.language.experimental.macros

object Foo {
  def printSymbol(name: String): Unit = macro FooMacro.printSymbol
}

object FooTarget

private class FooMacro(val c: scala.reflect.macros.blackbox.Context) {

  import c.universe._

  def printSymbol(name: Tree): Tree = {
    name match {
      case Literal(Constant(lv)) =>
        val a = q"_root_.temp.FooTarget.${TermName(lv.toString)}"
        val ca = c.typecheck(a)
        println("checked apply symbol", ca.symbol)
    }

    q"()"
  }

}

temp/Bar.scala:

package temp

object Implicits {

  implicit class BarObjContainer(f: FooTarget.type) {

    object bar

  }

}

object UseMacro {

  import Implicits._

  val v = Foo.printSymbol("bar")

}

Is ca.symbol what you want?

=== UPDATE ===

Here is the quick & dirty demo for function with param:

temp/Foo.scala:

package temp

import scala.language.experimental.macros

object Foo {
  def printSymbol(name: String): Unit = macro FooMacro.printSymbol
}

object FooTarget

private class FooMacro(val c: scala.reflect.macros.blackbox.Context) {

  import c.universe._

  def printSymbol(name: Tree): Tree = {
    name match {
      case Literal(Constant(lv)) =>
        val nameStr = lv.toString
        val f = q"_root_.temp.FooTarget.${TermName(nameStr)}(_)"
        c.typecheck(f) match {
          case Function(_, Apply(s@Select(_, TermName(`nameStr`)), _)) =>
            println(s.symbol)
        }
    }

    q"()"
  }

}

temp/Bar.scala:

package temp

object Implicits {

  implicit class BarObjContainer(f: FooTarget.type) {

    def bar(baz: String): Unit = ()

  }

}

object UseMacro {

  import Implicits._

  val v = Foo.printSymbol("bar")

}

s is the method symbol for "bar".

Upvotes: 1

Related Questions