Scala解析器组合,大文件问题

Rob*_*ert 13 scala parser-combinators

我写了一个解析器如下:

class LogParser extends JavaTokenParsers {

  def invertedIndex: Parser[Array[Array[(Int, Int)]]] = {
    num ~> num ~> num ~> rep(postingsList) ^^ {
      _.toArray
    }
  }

  def postingsList: Parser[Array[(Int, Int)]] = {
    num ~> rep(entry) ^^ {
      _.toArray
    }
  }

  def entry = {
    num ~ "," ~ num ^^ {
      case docID ~ "," ~ count => (docID.toInt, count.toInt)
    }
  }

  def num = wholeNumber ^^ (_.toInt)

}
Run Code Online (Sandbox Code Playgroud)

如果我使用FileReader从(270MB)文件解析如下:

val index = parseAll(invertedIndex, new FileReader("path/to/file")).get
Run Code Online (Sandbox Code Playgroud)

我得到了Exception in thread "main" java.lang.StackOverflowError(我也尝试过包装BufferedReader)但我可以通过首先将文件读入一个字符串来修复它,如下所示:

val input = io.Source.fromFile("path/to/file")
val str = input.mkString
input.close()
val index = parseAll(invertedIndex, str).get
Run Code Online (Sandbox Code Playgroud)

为什么会这样?有没有办法避免首先将它作为字符串读取,这似乎是浪费?

Iva*_*ith 1

还有另一个库[1],它很像支持 Trampolining 的 scala 解析器组合器,这是阻止 stackoverflow 错误所需的。

[1] https://github.com/djspiewak/gll-combinators