Peg.JS:简单的 if..then..else 实现

Peg.JS: Simple if..then..else implementation

我正在尝试为简单的 if..then..else 语句和简单的语句实现语法。

它应该能够解析如下语句:

if things are going fine
then
    things are supposed to be this way
    just go with it
else
    nothing new
How are you?

文档以一个决定(if.. then.. else)开头,然后是一个简单的陈述。

到目前为止我的语法是这样的:

document = decision / simple_statement / !.

decision = i:if t:then e:(else)? document { return { if: { cond: i }, then: t, else: e } }

if = 'if' s:statement nl { return s }
then = 'then' nl actions:indented_statements+ { return actions }
else = 'else' nl actions:indented_statements+ { return actions }
indented_statements = ss:(tab statement nl)+ { return ss.reduce(function(st, el) { return st.concat(el) }, []) }
statement = text:$(char+) { return text.trim() }

simple_statement = s:statement nl document { return { action: s } }

char = [^\n\r]
ws = [ \t]*
tab = [\t]+ { return '' }
nl = [\r\n]+

这returns一个输出:

{
   "if": {
      "cond": "things are going fine"
   },
   "then": [
      [
         "",
         "things are supposed to be this way",
         [
            "
"
         ],
         "",
         "just go with it",
         [
            "
"
         ]
      ]
   ],
   "else": [
      [
         "",
         "nothing new",
         [
            "
"
         ]
      ]
   ]
}

1.为什么 thenelse 数组中多了空字符串和数组?我应该怎么做才能删除它们?

  1. 为什么我的语法不读决定后的简单语句?我应该怎么做才能让它读取并解析整个文档?

编辑:我想我明白了为什么要获取这些数组。我更改了语法以删除 indented_statements.

中的重复项
document = decision / simple_statement / !.

decision = i:if t:then e:(else)? document { return { if: i, then: t, else: e } }

if = 'if' s:statement nl { return s }
then = 'then' nl actions:indented_statements+ { return actions }
else = 'else' nl actions:indented_statements+ { return actions }
indented_statements = tab s:statement nl { return s }
statement = text:$(char+) { return text.trim() }

simple_statement = s:statement nl document { return { action: s } }

char = [^\n\r]
ws = [ \t]*
tab = [\t]+ { return '' }
nl = [\r\n]+

我找到了答案。我需要重复提供第一个语句:

document = (decision / simple_statement)*