Is there anyway to go from a Symbol or Type to a Tree when defining a Scala macro?

Specifically the scenario is wanting to look up a literal on a companion object.

In scala code this looks something like this:

class Fred(a: String)

object Fred {
  val FredDescription = "hello"
}

In the macro I have access to a WeakTypeTag of Fred and can use that to get access to the companion and its type signature:

context.universe.weakTypeOf[A].typeSymbol.companionSymbol.typeSignature

But I can't see any way of accessing the literals or tree to match out the literals for the companion object.

Is this possible? Is there a trick to getting a Tree for some arbitrary Type or Symbol?

有帮助吗?

解决方案

There may be some cases where this is possible, e.g. when the type is defined in the same file where you invoke the macro, but in general case I would expect not.

This is because the type or symbol you are inspecting may come from already compiled classfiles. In such situation, the tree you are looking for simply does not exist.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top