我想解析的语法如下:
# This is a comment
# This is a block. It starts with \begin{} and ends with \end{}
\begin{document}
# Within the document block other kinds of blocks can exist, and within them yet other kinds.
# Comments can exist anywhere in the code.
This is another block within the block. It is a paragraph, no formal \begin{} and \end{} are needed.
The parser infers its type as a ParagraphBlock. The block ends with the newline.
\end{document}
我正在学习如何使用 PEG,这是我迄今为止为当前语法开发的内容:
Start
= (Newline / Comment / DocumentBlock)*
Comment
= '#' value: (!Newline .)* Newline? {
return {
type: "comment",
value: value.map(y => y[1]).join('').trim()
}
}
Newline
= [\n\r\t]
DocumentBlock
= "\\begin\{document\}"
(!"\\end\{document\}" DocumentChildren)*
"\\end\{document\}"
DocumentChildren
= NewlineBlock / ParagraphBlock
NewlineBlock
= value: Newline*
{
return {
type: "newline",
value: value.length
}
}
ParagraphBlock
= (!Newline .)* Newline
我遇到了一些无限循环的问题。当前代码产生此错误:
Line 19, column 5: Possible infinite loop when parsing (repetition used with an expression that may not consume any input).
上述简单语法的正确实现是什么?