0

我正在尝试为简单的 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?

该文档以一个决定(如果……那么……否则)开始,然后是一个简单的陈述。

到目前为止,我的语法如下所示:

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]+

这将返回一个输出:

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

1、and数组中为什么会有多余的空字符串和then数组else?我应该怎么做才能删除它们?

  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]+

4

1 回答 1

2

我想出了答案。我需要提供第一个语句作为重复:

document = (decision / simple_statement)*

于 2020-12-29T20:36:41.123 回答