5

私は次のようなものに一致するPEG.js用の簡単な文法を書き込もうとしています。

some text;
arbitrary other text that can also have µnicode; different expression;
let's escape the \; semicolon, and \not recognized escapes are not a problem;
possibly last expression not ending with semicolon

つまり、基本的にこれらはセミコロンで区切られたいくつかのテキストです。私の簡略化された文法は次のようになります。

start
= flow:Flow

Flow
= instructions:Instruction*

Instruction
= Empty / Text

TextCharacter
= "\\;" /
.

Text
= text:TextCharacter+ ';' {return text.join('')}

Empty
= Semicolon

Semicolon "semicolon"
= ';'

問題は、入力にセミコロン以外のものを入力すると、次のようになることです。

SyntaxError: Expected ";", "\\;" or any character but end of input found.

これを解決する方法は?PEG.jsが入力の終わりと一致しないことを読みました。

4

1 に答える 1

10

(少なくとも)2つの問題があります:

どの文字( )ともTextCharacter一致しないようにする必要があります。バックスラッシュとセミコロンを除くすべての文字と一致するか、エスケープ文字と一致する必要があります。.

TextCharacter
 = [^\\;]
 / "\\" .

2番目の問題は、文法で入力がセミコロンで終わるように要求されていることです(ただし、入力は;)で終わっていません。

代わりにこのようなものはどうですか?

start
 = instructions

instructions
 = instruction (";" instruction)* ";"?

instruction
 = chars:char+ {return chars.join("").trim();}

char
 = [^\\;]
 / "\\" c:. {return ""+c;}

これにより、入力が次のように解析されます。

[
   "some text",
   [
      [
         ";",
         "arbitrary other text that can also have µnicode"
      ],
      [
         ";",
         "different expression"
      ],
      [
         ";",
         "let's escape the ; semicolon, and not recognized escapes are not a problem"
      ],
      [
         ";",
         "possibly last expression not ending with semicolon"
      ]
   ]
]

末尾のセミコロンはオプションになっていることに注意してください。

于 2012-10-05T12:02:37.707 に答える