简体   繁体   English

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

[英]Peg.JS: Simple if..then..else implementation

I am trying to implement a grammar for a simple if..then..else statement along with simple statements.我正在尝试为简单的 if..then..else 语句和简单语句实现语法。

It should be able to parse a statement like:它应该能够解析如下语句:

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

The document starts with a decision (if.. then.. else) and is followed by a simple statement.该文档以一个决定(如果..那么..其他)开始,然后是一个简单的陈述。

My grammar so far looks like this:到目前为止,我的语法如下所示:

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

This returns an output:这将返回 output:

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

1. Why are there extra empty strings and arrays in the then and else array? 1、为什么 thenelse数组中多了空字符串和arrays? What should I do to remove them? 我应该怎么做才能删除它们?

  1. Why doesn't my grammar read the simple statement(s) after the decision?为什么我的语法在决定后没有阅读简单的陈述? What should I do to make it read and parse the entire document?我应该怎么做才能让它读取和解析整个文档?

EDIT : I think I figured out why I was getting the arrays.编辑:我想我知道为什么我得到 arrays。 I changed the grammar to remove repetitions inside indented_statements .我更改了语法以删除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]+

I figured out the answer.我想出了答案。 I needed to provide the first statement as repeating:我需要提供第一个语句作为重复:

document = (decision / simple_statement)*

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

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