使用 PEG.js 解析此语法的意外行为

Unexpected Behaviour with parsing this grammar with PEG.js

我是形式语法世界的新手。我尝试使用 ANTLR for JS but couldn't figure out how to run the parser. I'm trying to develop a grammar for a DSL on PEG.js and this is what I have (http://peg.arcanis.fr/3T2PKD/):

start 
  = expr

operator
  = "show" lparen st:string ws rparen { console.log(7)}
  / "show" lparen ex:expr rparen      { console.log(8)}

expr 
 = op: operator ws ex: expr  {console.log (1)}
 / st:string ws ex: expr     {console.log (2)}
 / st:string ws op:operator  {console.log (3)}
 / op:operator ws str:string {console.log (4)}
 / st:string ws              {console.log (5)}
 / op:operator ws            {console.log (6)}

lparen
  = ws "(" ws

rparen
  = ws ")" ws

integer "integer"
  = digits:[0-9]+ { return parseInt(digits.join(""), 10); }

string "string"
  = quotation_mark chars:char* quotation_mark { return chars.join(""); }

ws "whitespace" = [ \t\n\r]*

char
  = unescaped
  / escape
    sequence:(
        '"'
      / "\"
      / "/"
      / "b" { return "\b"; }
      / "f" { return "\f"; }
      / "n" { return "\n"; }
      / "r" { return "\r"; }
      / "t" { return "\t"; }
      / "u" digits:$(HEXDIG HEXDIG HEXDIG HEXDIG) {
          return String.fromCharCode(parseInt(digits, 16));
        }
    )
    { return sequence; }

escape         = "\"
quotation_mark = '"'
unescaped      = [\x20-\x21\x23-\x5B\x5D-\u10FFFF]

/* ----- Core ABNF Rules ----- */

/* See RFC 4234, Appendix B (http://tools.ietf.org/html/rfc4627). */
DIGIT  = [0-9]
HEXDIG = [0-9a-f]i

{
  ;
}

测试时:show ("abc") 控制台不应该显示 7 6个 ?

而是显示 7 7 7 6

这三天一直在绞尽脑汁。有人,在某个地方帮助我达到节俭!

解析器必须尝试规则 op: operator ws ex: exprop:operator ws str:string 才能最终成功使用 op:operator ws。它不知道这些不会起作用,直到它找不到 ).

之外的任何东西

因此,它通过 operator 规则一次,没有看到另一个表达式,因此它回溯。然后它看到 时间的 operator,它 仍然 不起作用,因为它后面没有字符串。所以最后,在第三次尝试时,它看到了运算符,然后最后一条规则成功了。

您对 console.log(7) 的调用是因为 operator 规则本身成功,即使 expr 规则没有成功。