简体   繁体   English

PEGJS:嵌套的pegjs语法

[英]PEGJS : Nested pegjs grammar

start
  = intExp

intExp
  = andIntExp
  / orIntExp

andIntExp 
   = integer (andExp intExp)*

orIntExp 
   = integer (orExp intExp)*

andExp 
  = space* "and" space* { return "and";}

orExp 
  = space* "or" space*  { return "or";}

space 
  = [\n \t]

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

I want to parse input like 我想解析输入像

2 or 2 or 2 or 2 and 2 and 2 but 2 or 2 and 2 is invalid. 2 or 2 or 22 and 2 and 22 or 2 and 2无效。 In short I dont want and and or to occur together within the input. 简而言之,我不想and or一起出现在输入中。 Is there any way to do this with peg, without involving javascript and storing previously seen variable (For which I already have a solution) ? 有没有办法用peg做到这一点,而无需涉及javascript并存储以前看到的变量(我已经有解决方案了)?

Parsing expression grammars are deterministic. 解析表达语法是确定性的。 They try the first match and fail on first mismatch, also, they don't backtrack. 他们尝试第一场比赛,但在第一场比赛失败的情况下失败,而且,他们也没有退路。 You can just negate ambiguous expressions and your grammar will work as expected: 您可以否定模棱两可的表达式,语法将按预期工作:

Start
  = IntExpr

IntExpr
  = OrIntExpr
  / AndIntExpr

OrIntExpr
  = Integer _ !"and" ("or" _ OrIntExpr)?

AndIntExpr
  = Integer _ ("and" _ AndIntExpr)?

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

_ "space"
  = [\n \t]*

Our OurExpr refuses matching if receives and and jumps to the next option. 我们OurExpr死不相匹配,如果接收and并跳转到下一个选项。

The following rules have been tested: 已测试以下规则:

1 and 2 and 3 => PASS 1 and 2 and 3 => PASS

1 => PASS 1 => PASS

4 or 2 or 1 => PASS 4 or 2 or 1 => PASS

9 and 2 or 3 => FAIL 9 and 2 or 3 => FAIL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM