我想用 ANTLR4 解析 PostScript 代码。我完成了语法,但是一种特定的语言扩展(由其他人引入)很难被识别。
一个简短的例子:
1: % This is a line comment
2: % The next line just pushes the value 10 onto the stack
3: 10
4:
5: %?description This is the special line-comment in question
6: /procedure {
7: /var1 30 def %This just creates a variable
8: /var2 10 def %?description A description associated with var2 %?default 20
9: /var3 (a string value) def %?description I am even allowed to use % signs %?default (another value)
10: }
识别行注释,例如第 1、2 和 7 行,可以使用 Lexer-Rules 来完成
LINE_COMMENT: '%' .*? NEWLINE;
NEWLINE: '\r'? '\n';
它简单地匹配 % 之后直到行尾的所有内容。
我遇到的问题是那些特殊的行注释,它们以类似的内容开头%?description
or %?default
,因为这些也应该被识别,但与 LINE_COMMENT 相比,可以将多个这些放在一行中(例如第 8 行和第 9 行)。所以第 8 行包含两个特殊注释%?description A description associated with var2
and %?default 20
.
把它想象成这样(尽管这行不通):
SPECIAL_COMMENT: '%?' .*? (SPECIAL_COMMENT|NEWLINE);
现在是真正棘手的部分:应该允许您在后面添加任意文本%?description
包括%
同时仍然能够分割个人评论。
简而言之,问题可以简化为分割表格的一行
(%?<keyword> <content with % allowed in it>)+ NEWLINE
e.g.
%?description descr. with % in in %?default (my default value for 100%) %?rest more
into
1.) %?description descr. with % in in
2.) %?default (my default value for 100%)
3.) %?rest more
有什么想法,如何制定词法分析器或解析器规则来实现这一目标?