PEG.js - 如何解析c风格的评论?

时间:2014-10-24 21:30:50

标签: parsing comments peg

实现基于peg.js的解析器,我无法添加代码来处理c样式的注释/ *像这样* /。

我需要在不吃它的情况下找到结束标记。

这不起作用:

multi = '/*' .* '*/'

消息是:

line: 14
Expected "*/" or any character but end of input found.

我明白为什么这不起作用,但不幸的是我不知道如何使评论解析功能正常。

到目前为止,这是代码:

start = item*

item = comment / content_line

content_line = _ p:content _ {return ['CONTENT',p]}

content = 'some' / 'legal' / 'values'

comment = _ p:(single / multi) {return ['COMMENT',p]}

single = '//' p:([^\n]*) {return p.join('')}

multi = 'TODO'


_ = [ \t\r\n]* {return null}

和一些示例输入:

// line comment, no problems here

/*
  how to parse this ??
*/

values

// another comment

some legal

2 个答案:

答案 0 :(得分:14)

使用一个向前看的谓词,并确保在匹配字符之前字符流中没有"*/"

comment
 = "/*" (!"*/" .)* "*/"

(!"*/" .)部分可以理解如下:当前面没有'*/'时,匹配任何字符

这样就可以成功匹配这样的评论:/* ... **/

答案 1 :(得分:5)

完整代码:

分析器:

start = item*

item = comment / content_line

content_line = _ p:content _ {return ['CONTENT',p]}

content = 'all' / 'legal' / 'values' / 'Thanks!'

comment = _ p:(single / multi) {return ['COMMENT',p]}

single = '//' p:([^\n]*) {return p.join('')}

multi = "/*" inner:(!"*/" i:. {return i})* "*/" {return inner.join('')}

_ = [ \t\r\n]* {return null}

样品:

all  

// a comment

values

// another comment

legal

/*12
345 /* 
*/

Thanks!

结果:

[
    ["CONTENT","all"],
    ["COMMENT"," a comment"],
    ["CONTENT","values"],
    ["COMMENT"," another comment"],
    ["CONTENT","legal"],
    ["COMMENT","12\n345 /* \n"],
    ["CONTENT","Thanks!"]
]