Search code examples
javascriptparsingparser-generatorpegjs

parsing boolean expression chain with pegjs


I'm trying to parse this string with peg.js:

filter a > 2 or b < 3 or b > 10 or c = 12

The relevant extract of the grammar looks like:

bool "bool"
  = left:expr space+ logicOp:logicOp space+ right:bool { return new options.BooleanExpr(left, logicOp, right); }
  / expr:expr { return expr; }


bools "bools"
  = left:bool morebools:(space+ logicOp space+ bool)+ { return options.makeBooleanChain(left, morebools); }
  / bool:bool { return bool; }


filter "filter"
  = "filter"i space+ _bool:bools { return new options.FilterCmd(_bool); }

The problem is that the boolean chain won't be recognised for more than 2 expression (expr1 or expr2) and I don't know how to parse more "or exprN" parts. I introduced a "bools" rule, but this doesn't work either. Any idea of how I can resolve this and parse arbitrarily long boolean expressions?


Solution

  • Going back to the online example as suggested by @HBP, I managed to create a working rule:

    bool "bool"
      = left:expr space+ logicOp:logicOp space+ right:bool { return new options.BooleanExpr(left, logicOp, right); }
      / expr
    

    This alone does the job...