2015-02-09 76 views
2

我在想如何解析pegjs中的评论(比如la Haskell)。如何解析pegjs中的嵌套注释?

目标:

{- 
    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 
-} 

例如,下列不应该解析:

{- I am an unbalanced -} comment -} 

但你也应该有一个逃生机制:

{- I can escape comment \{- characters like this \-} -} 

这八九不离十好像解析s表达式,但使用s表达式,很容易:

sExpression = "(" [^)]* ")" 

因为密切的parens只是一个字符,我可以“不”与胡萝卜。另外,我想知道如何能够“不”比pegjs中的单个字符更长的东西。

感谢您的帮助。

回答

3

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

start = comment 

comment = COMSTART (not_com/comment)* COMSTOP 

not_com = (!COMSTOP !COMSTART.) 

COMSTART = '{-' 

COMSTOP = '-}' 

要回答您的一般问题:

顺便说一句,我不知道如何能及“不是”东西是长于pegjs单个字符

简单的方法是(!rulename .)其中rulename是在您的语法中定义的另一个规则。 ! rulename部分只是确保接下来扫描的内容与rulename不匹配,但您仍然需要为匹配的规则定义某些内容,这就是为什么我包含.的原因。

+1

酷!谢谢。这有很大帮助。我看到了!但我认为这只是不起作用。我知道我明白我实际上必须包括一些东西来解析它。 – TheSeamau5 2015-02-15 03:30:55