2012-10-05 13 views
5

Sto cercando di scrivere un semplice Grammer per PEG.js che corrisponda o meno così:Problemi con PEG.js fine dell'input

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 

Quindi, in pratica questi sono alcuni testi separati da un punto e virgola. La mia grammatica semplificata simile a questa:

start 
= flow:Flow 

Flow 
= instructions:Instruction* 

Instruction 
= Empty/Text 

TextCharacter 
= "\\;"/
. 

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

Empty 
= Semicolon 

Semicolon "semicolon" 
= ';' 

il problema è che se metto qualcosa di diverso da un punto e virgola ingresso, ottengo:

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

Come risolvere questo problema? Ho letto che PEG.js non è in grado di eguagliare la fine dell'input.

+4

FWIW, è possibile abbinare la fine dell'input con '! .' – ebohlman

risposta

8

Hai (almeno) 2 problemi:

tuo TextCharacter non dovrebbe corrispondere carattere (la .). Deve corrispondere ogni carattere eccetto una barra rovesciata e virgola, o dovrebbe corrispondere a un carattere di escape:

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

Il secondo problema è che la grammatica mandati l'input per terminare con un punto e virgola (ma lo fa il tuo contributo non finisce con un ;).

Che ne dite di qualcosa di simile a questo, invece:

start 
= instructions 

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

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

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

che analizzare l'input come segue:

[ 
    "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" 
     ] 
    ] 
] 

Si noti che il finale punto e virgola è opzionale ora.