I am trying to implement the following grammer using FastParse API.
- Expr can contain only Foo,Bar,Baz sub expressions
- Expr must contain atleast 1 sub expression Foo/Bar/Bar. It cannot be empty
- Foo/Bar/Baz can appear in any order inside Expr.
- Foo/Bar/Baz cannot repeat so you can use them only once
So a valid expression is Expr(Baz(10),Foo(10),Bar(10))
and invalid expression is Expr()
or Expr(Bar(10),Bar(10))
So far I have written this code which can enforce and parse 1, 2, 3, rules. but rule no 4 is proving to be tricky.
import fastparse.noApi._
import fastparse.WhitespaceApi
object FastParsePOC {
val White = WhitespaceApi.Wrapper{
import fastparse.all._
NoTrace(" ".rep)
}
def print(input: Parsed[(String, String, Seq[(String, String)])]) : Unit = {
input match {
case Parsed.Success(value, index) =>
println(s"${value._1} ${value._2}")
value._3.foreach{case (name, index) => println(s"$name $index")}
case f @ Parsed.Failure(error, line, col) => println(s"Error: $error $line $col ${f.extra.traced.trace}")
}
}
def main(args: Array[String]) : Unit = {
import White._
val base = P("(" ~ (!")" ~ AnyChar).rep(1).! ~ ")")
val foo = P("Foo".! ~ base)
val bar = P("Bar".! ~ base)
val baz = P("Baz".! ~ base)
val foobarbaz = (foo | bar | baz)
val parser = P("Expr" ~ "(" ~ foobarbaz ~ ",".? ~ (foobarbaz).rep(sep=",") ~ ")")
val input3 = "Expr(Baz(20),Bar(10),Foo(30))"
val parsed = parser.parse(input3)
print(parsed)
}
}
You may check the "exactly-once" constraint with a
filter
call: