peg-parser 記法改良

汚いコードを書き直しつつ、記法を改良。より柔軟に文法を記述できるようになりますた。しかしバックエンドは相変らずRuiさんのpeg.scmなのであった。

CSVのパーサを生成するサンプルも拝借。

Record   ← Field (Comma Field)*
Field    ← Quoted / UnQuoted
Spaces   ← [\t ]*
Comma    ← Spaces ',' Spaces
DQuote   ← '"'
Quoted   ← DQuote ('""' / [^\"])* DQuote
UnQuoted ← !(Comma / newline) . UnQuoted / ε

こんなPEGを、次のように書ける。

(parse-string-with
   ((Record <- (:fld Field)
	    (:rest-fld ((Comma (:fld Field) :return fld) *))
	    :return (cons fld rest-fld))
    (Field <- (:charlist Quoted) :return (list->string charlist)
	   / (:charlist UnQuoted) :return (list->string charlist))
    (Spaces <- #[ \t] *)
    (Comma <- Spaces #\, Spaces)
    (DQuote <- #\")
    (Quoted <- DQuote
	    (:body ((#\" #\" :return #\" / #[^\"]) *))
	    DQuote
	    :return body)
    (UnQuoted <- ! (Comma / newline) (:ch anychar) (:unq UnQuoted)
	      :return (cons ch unq)
	      / :return ())
    )
   "\"a\"\"bc\" , b  , c")

ネストした括弧を使用できるようにしたこと、マッチした文字列を束縛する変数名をシンボルからキーワードで書くようにしたことが大きな変更点。