Extracting type from a reified, type-checked `Tree` in Scala -
given following repl session:
scala> import scala.reflect.runtime.universe._ import scala.reflect.runtime.universe._ scala> import scala.tools.reflect.toolbox import scala.tools.reflect.toolbox scala> import scala.reflect.runtime.{currentmirror => cm} import scala.reflect.runtime.{currentmirror=>cm} scala> val r = reify { val = 234.45 } r: reflect.runtime.universe.expr[unit] = expr[unit]({ val = 234.45; () }) scala> val c = cm.mktoolbox().typecheck(r.tree) warning: there 1 feature warning; re-run -feature details c: qual$2.u.tree forsome { val qual$2: scala.tools.reflect.toolbox[reflect.runtime.universe.type] @scala.reflect.internal.annotations.uncheckedbounds } = { val a: double = 234.45; () } what's recommended way of pulling out type of variable a type-checked tree c?
you can using quasiquotes, i'm not sure it's easiest way do:
scala> val c = cm.mktoolbox().typecheck(r.tree) warning: there 1 feature warning; re-run -feature details c: qual$2.u.tree forsome { val qual$2: scala.tools.reflect.toolbox[reflect.runtime.universe.type] @scala.reflect.internal.annotations.uncheckedbounds } = { val a: double = 234.45; () } scala> val q"{val $name: $tpt = $rhs; ()}" = c name: reflect.runtime.universe.termname = tpt: reflect.runtime.universe.tree = double rhs: reflect.runtime.universe.tree = 234.45 scala> :t tpt.tpe reflect.runtime.universe.type scala> println(tpt.tpe) double
Comments
Post a Comment