0

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

您好,您的名字是 {{name}},今天是 {{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$3(Combinators.scala:462)
  at fastparse.parsers.Combinators$Repeat.parseRec(Combinators.scala:489)
  at fastparse.parsers.Combinators$Sequence$Flat.rec$1(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

我究竟做错了什么?

4

1 回答 1

1

试试这样:

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)
我认为,因为你不想要(开括号或闭括号)。

希望能帮助到你!;)

于 2017-05-31T14:31:15.277 回答