使用非交互式scala.tools.nsc.Global将文件解析为AST

时间:2015-12-03 12:43:02

标签: scala scala-compiler

scala.tools.nsc.interactive.Global中,有parseTree方法。我想使用scala.tools.nsc.Global从文件中获取AST。看parseTree定义,我写了

val settings = new Settings
settings.embeddedDefaults(getClass.getClassLoader)
settings.usejavacp.value = true
val reporter = new StoreReporter
val compiler: Compiler = new Global(settings, reporter)

val run = new compiler.Run
val tree = compiler.newUnitParser(new compiler.CompilationUnit(source)).parse()

但这会产生

[info]   java.lang.AssertionError: assertion failed: <no phase>: <?>
[info]   at scala.reflect.internal.Symbols$TypeHistory.<init>(Symbols.scala:3667)
[info]   at scala.reflect.internal.Symbols$Symbol.info_$eq(Symbols.scala:1509)
[info]   at scala.reflect.internal.Symbols$TypeSymbol.info_$eq(Symbols.scala:3099)
[info]   at scala.reflect.internal.Symbols$Symbol.setInfo(Symbols.scala:1515)
[info]   at scala.reflect.internal.Mirrors$Roots$RootClass.<init>(Mirrors.scala:307)
[info]   at scala.reflect.internal.Mirrors$Roots.RootClass$lzycompute(Mirrors.scala:321)
[info]   at scala.reflect.internal.Mirrors$Roots.RootClass(Mirrors.scala:321)
[info]   at scala.reflect.internal.Mirrors$Roots$EmptyPackageClass.<init>(Mirrors.scala:330)
[info]   at scala.reflect.internal.Mirrors$Roots.EmptyPackageClass$lzycompute(Mirrors.scala:336)
[info]   at scala.reflect.internal.Mirrors$Roots.EmptyPackageClass(Mirrors.scala:336)
[info]   ...

如何正确初始化编译器? Scala版本2.11.7。

1 个答案:

答案 0 :(得分:1)

李浩义对scala-users的回答:

val run = new compiler.Run()
compiler.phase = run.parserPhase
run.cancel()

val tree = compiler.newUnitParser(new compiler.CompilationUnit(source)).parse()