Generating scala AST for recursive method
I am generating the scala AST using the following code:
val setting = new Settings(error)
val reporter = new ConsoleReporter(setting, in, out) {
override def displayPrompt = ()
}
val compiler = new Global(setting, reporter) with ASTExtractor{
override def onlyPresentation = true
}
//setting.PhasesSetting("parser", "parserPhase")
val run = new compiler.Run
val sourceFiles:List[String] = List("Test.scala")
run.compile(sourceFiles.toList)
I guess this is the standard code used to run the compiler in the code and generate the AST to work with. The above code worked fine for any valid scala code in Test.scala till now. When I use a recursive function in Test.scala, like
def xMethod(x:Int):Int = if(x == 0) -1 else xMeth开发者_如何学运维od(x-1)
It gives me a java.lang.NullPointerException. The top few lines of the stack trace look like this
at scala.tools.nsc.typechecker.Typers$Typer.checkNoDoubleDefsAndAddSynthetics$1(Typers.scala:2170)
at scala.tools.nsc.typechecker.Typers$Typer.typedStats(Typers.scala:2196)
at scala.tools.nsc.typechecker.Typers$Typer.typedBlock(Typers.scala:1951)
at scala.tools.nsc.typechecker.Typers$Typer.typed1(Typers.scala:3815)
at scala.tools.nsc.typechecker.Typers$Typer.typed(Typers.scala:4124)
at scala.tools.nsc.typechecker.Typers$Typer.typed(Typers.scala:4177)
at scala.tools.nsc.transform.TailCalls$TailCallElimination.transform(TailCalls.scala:199)
The code works fine for a method like
def aMethod(c:Int):Int = { bMethod(c) }
def bMethod(x:Int):Int = aMethod(x)
Please let me know if recursive functions need any other setting.
I can't tell you what you're doing wrong, but I use compiler.typedTree
to get an AST in my project. Maybe this works for you as well.
See http://scala.ifs.hsr.ch/browser/src/scala/tools/refactoring/util/CompilerProvider.scala for more context.
精彩评论