Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 xMethod(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.

like image 359
scout Avatar asked Nov 15 '22 11:11

scout


1 Answers

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.

like image 116
Mirko Stocker Avatar answered Dec 19 '22 18:12

Mirko Stocker