parsing - Scala PackratParsers doesn not backtrack as it should? -
parsing - Scala PackratParsers doesn not backtrack as it should? -
i have next code simple parser of logical expressions:
import scala.util.parsing.combinator.regexparsers import scala.util.parsing.combinator.packratparsers object parsers extends regexparsers packratparsers // entities definition sealed trait logicalunit case class variable(name: string) extends logicalunit case class not(arg: logicalunit) extends logicalunit case class and(arg1: logicalunit, arg2: logicalunit) extends logicalunit import parsers._ // in order of descending priority lazy val pattern: packratparser[logicalunit] = ((variable) | (not) | (and)) lazy val variable: packratparser[variable] = "[a-za-z]".r ^^ { n => variable(n) } lazy val not: packratparser[not] = ("!" ~> pattern) ^^ { x => not(x) } lazy val and: packratparser[and] = ((pattern <~ "&") ~ pattern) ^^ { case ~ b => and(a, b) } // execution println(parsers.parseall(pattern, "!a & !b"))
so, trying parse string !a & !b
, fails with
[1.4] failure: string matching regex `\z' expected `&' found !a & !b ^
it seems root parser tries parse whole string pattern -> not -> variable
, doesn't backtrack when discovers !a
not end yet, pattern -> and
isn't tried. thought using packratparsers
should solve that, didn't
can please tell me doing wrong?
i don't think there way create 1 of these parsers backtrack 1 time has accepted something. if alternative succeeds, no other alternative tried. behaviour intrinsic packrat parsing method parsing look grammars these combinators implement (as opposed context-free grammars order of alternatives not relevant , backtracking behaviour depends on parsing method). why alternatives may match longer input should given first.
regarding precedence of not versus and, standard approach encode precedence , associativity of operators in grammar rules context-free grammars. books on parsing describe how this. can see 1 version in next notes starting @ slide 24: http://www.sci.usq.edu.au/courses/csc3403/lect/syntax-1up.pdf.
scala parsing parser-combinators
Comments
Post a Comment