如何解析 pegjs 中的嵌套注释?

The*_*au5 3 javascript grammar parsing peg pegjs

我想知道您如何在 pegjs 中解析注释(例如,la Haskell)。

目标:

{-
    This is a comment and should parse.
    Comments start with {- and end with -}.
    If you've noticed, I still included {- and -} in the comment.
    This means that comments should also nest
    {- even {- to -} arbitrary -} levels
    But they should be balanced
-}
Run Code Online (Sandbox Code Playgroud)

例如,以下不应解析:

{- I am an unbalanced -} comment -}
Run Code Online (Sandbox Code Playgroud)

但是你也应该有一个转义机制:

{- I can escape comment \{- characters like this \-} -}
Run Code Online (Sandbox Code Playgroud)

这有点像解析 s 表达式,但使用 s 表达式,很容易:

sExpression = "(" [^)]* ")"
Run Code Online (Sandbox Code Playgroud)

因为关闭括号只是一个字符,我不能用胡萝卜“不”它。顺便说一句,我想知道如何“不”比 pegjs 中的单个字符长的东西。

谢谢你的帮助。

小智 5

这不处理你的逃逸机制,但它应该让你开始(在这里是一个链接到现场观看:pegedit ;只需点击Build ParserParse在屏幕的顶部。

start = comment

comment = COMSTART (not_com/comment)* COMSTOP

not_com = (!COMSTOP !COMSTART.)

COMSTART = '{-'

COMSTOP = '-}'
Run Code Online (Sandbox Code Playgroud)

要回答您的一般问题:

顺便说一句,我想知道如何“不”比 pegjs 中的单个字符长的东西。

最简单的方法就是(!rulename .)在那里rulename是你的语法定义的其他规则。这! rulename部分只是确保接下来扫描的任何内容都不匹配rulename,但您仍然必须定义一些规则来匹配,这就是我包含..