问题描述
我正在尝试为简单的 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。为什么 then
和 else
数组中有多余的空字符串和数组?我应该怎么做才能删除它们?
- 为什么我的语法在决定后没有读取简单的语句?我应该怎么做才能让它读取和解析整个文档?
EDIT:我想我知道我为什么要获取数组了。我更改了语法以删除 indented_statements
中的重复。
document = decision / simple_statement / !.
decision = i:if t:then e:(else)? document { return { if: i,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)*