FastParse - 内存不足错误

FastParse - out of memory error

我正在尝试使用 FastParse library 为非常原始的模板系统创建解析器,如下所示:

Hello, your name is {{name}} and today is {{date}}.

到目前为止我有:

scala> import fastparse.all._
import fastparse.all._

scala> val FieldStart = "{{"
FieldStart: String = {{

scala> val FieldEnd = "}}"
FieldEnd: String = }}

scala> val Field = P(FieldStart ~ (!FieldEnd ~ AnyChar).rep.! ~ FieldEnd)
Field: fastparse.all.Parser[String] = Field

scala> val Static = P((!FieldStart ~ !FieldEnd ~ AnyChar).rep.!)
Static: fastparse.all.Parser[String] = Static

scala> val Template = P(Start ~ (Field | Static) ~ End)
Template: fastparse.all.Parser[String] = Template

scala> Template parse "{{foo}}"
res0: fastparse.core.Parsed[String,Char,String] = Success(foo,7)

scala> Template parse "foo"
res1: fastparse.core.Parsed[String,Char,String] = Success(foo,3)

scala> Template parse "{{foo"
res2: fastparse.core.Parsed[String,Char,String] = Failure(End:1:1 ..."{{foo")

但是当我尝试我认为应该是正确的最终形式时:

scala> val Template = P(Start ~ (Field | Static).rep ~ End)
Template: fastparse.all.Parser[Seq[String]] = Template

我得到:

scala> Template parse "{{foo}}"
java.lang.OutOfMemoryError: Java heap space
  at scala.collection.mutable.ResizableArray$class.ensureSize(ResizableArray.scala:103)
  at scala.collection.mutable.ArrayBuffer.ensureSize(ArrayBuffer.scala:48)
  at scala.collection.mutable.ArrayBuffer.$plus$eq(ArrayBuffer.scala:84)
  at scala.collection.mutable.ArrayBuffer.$plus$eq(ArrayBuffer.scala:48)
  at fastparse.core.Implicits$LowPriRepeater$GenericRepeater.accumulate(Implicits.scala:47)
  at fastparse.core.Implicits$LowPriRepeater$GenericRepeater.accumulate(Implicits.scala:44)
  at fastparse.parsers.Combinators$Repeat.rec(Combinators.scala:462)
  at fastparse.parsers.Combinators$Repeat.parseRec(Combinators.scala:489)
  at fastparse.parsers.Combinators$Sequence$Flat.rec(Combinators.scala:297)
  at fastparse.parsers.Combinators$Sequence$Flat.parseRec(Combinators.scala:319)
  at fastparse.parsers.Combinators$Rule.parseRec(Combinators.scala:160)
  at fastparse.core.Parser.parseInput(Parsing.scala:374)
  at fastparse.core.Parser.parse(Parsing.scala:358)
  ... 19 elided

我做错了什么?

这样试试:

val Field = P(FieldStart ~ (!FieldEnd ~ AnyChar).rep(min=1).! ~ FieldEnd)
val Static = P((!(FieldStart | FieldEnd) ~ AnyChar).rep(min=1).!)

val Template = P(Start ~ (Field | Static) ~ End)

你应该小心 .rep,它的字面意思是 或更多...
此外,在 Static 解析器中,否定前瞻应类似于 !(FieldStart | FieldEnd)
我想,因为你不想(开大括号或闭大括号)。

希望对您有所帮助! ;)