Reputation: 4808
Say I have lhs
, tpe
, rhs
extracted from this:
q"$mods val $lhs: $tpe = $rhs"
Now, tpe
is an Ident
. How do I get the Tree
(or Type
) object corresponding to this ident?
Upvotes: 1
Views: 146
Reputation: 39587
The Ident is a tree representing a name, and the type is assigned by typechecking.
scala> import reflect.runtime._,universe._,tools.reflect._
import reflect.runtime._
import universe._
import tools.reflect._
scala> val t = q"val i: Int = 42"
t: reflect.runtime.universe.ValDef = val i: Int = 42
scala> val q"val $x: $what = $rhs" = t
x: reflect.runtime.universe.TermName = i
what: reflect.runtime.universe.Tree = Int
rhs: reflect.runtime.universe.Tree = 42
scala> showRaw(what)
res1: String = Ident(TypeName("Int"))
scala> val tb = currentMirror.mkToolBox()
tb: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] = scala.tools.reflect.ToolBoxFactory$ToolBoxImpl@27d5a580
scala> val v = tb.typecheck(t)
v: tb.u.Tree = val i: Int = 42
scala> v.children.head.tpe
res2: tb.u.Type = Int
Upvotes: 2