解析包含代码的字符串,返回一个Type

时间:2013-03-27 13:09:32

标签: scala reflection scala-2.10

我想解析String中包含的一段scala代码,并得到该表达式String => Type的结果reflect.runtime.universe.Type。我试过了:

scala> import scala.tools.nsc.interpreter.IMain
import scala.tools.nsc.interpreter.IMain

scala> new IMain().exprTyper.parse("scala.Option")
warning: there were 1 feature warning(s); re-run with -feature for details
res1: Option[List[_2.repl.global.Tree]] forSome { val _2: scala.tools.nsc.interpreter.IMain#exprTyper.type } = Some(List(scala.Option))

scala> .get.head
warning: there were 1 feature warning(s); re-run with -feature for details
res2: _2.repl.global.Tree forSome { val _2: scala.tools.nsc.interpreter.IMain#exprTyper.type } = scala.Option

scala> .tpe
res3: _2.type#repl.global.Type = null

scala> new IMain().runtimeTypeOfTerm("scala.Option")
warning: there were 1 feature warning(s); re-run with -feature for details
res5: _74.global.Type forSome { val _74: scala.tools.nsc.interpreter.IMain } = <notype>

scala> new IMain().typeOfTerm("scala.Option")
warning: there were 1 feature warning(s); re-run with -feature for details
res6: _75.global.Type forSome { val _75: scala.tools.nsc.interpreter.IMain } = <notype>

是否有可能,如果是的话,你是怎么做到的?感谢。

UPD:我已经表达了实际意图以及我现在在这个问题中的位置:Getting type information inside scala repl via IMain

1 个答案:

答案 0 :(得分:2)

所以,潜伏在SO之后(特别感谢this answer),我收敛到了以下结果:

scala> def toType(expr: String): Type = {
     | import scala.tools.reflect.ToolBox
     | import scala.reflect.runtime.{currentMirror => m}
     | val tb = m.mkToolBox()
     | val exp = tb.parse(expr.trim)
     | tb.typeCheck(exp).tpe
     | }
toType: (expr: String)reflect.runtime.universe.Type

scala> toType("Option")
res2: reflect.runtime.universe.Type = Option.type

scala> toType("List")
res3: reflect.runtime.universe.Type = scala.collection.immutable.List.type