解析antlr4中的C#预处理器
本文关键字:预处理 处理器 中的 antlr4 解析 | 更新日期: 2023-09-27 17:50:52
我正在尝试使用ANTLR4解析C#预处理器,而不是忽略它们。我使用这里提到的语法:https://github.com/antlr/grammars-v4/tree/master/csharp
这是我的补充(现在我只关注pp_conditional(:
pp_directive
: Pp_declaration
| pp_conditional
| Pp_line
| Pp_diagnostic
| Pp_region
| Pp_pragma
;
pp_conditional
: pp_if_section (pp_elif_section | pp_else_section | pp_conditional)* pp_endif
;
pp_if_section:
SHARP 'if' conditional_or_expression statement_list
;
pp_elif_section:
SHARP 'elif' conditional_or_expression statement_list
;
pp_else_section:
SHARP 'else' (statement_list | pp_if_section)
;
pp_endif:
SHARP 'endif'
;
我在这里添加了它的条目:
block
: OPEN_BRACE statement_list? CLOSE_BRACE
| pp_directive
;
我得到了错误:
line 19:0 mismatched input '#if TEST'n' expecting '}'
当我使用以下测试用例时:
if (!IsPostBack){
#if TEST
ltrBuild.Text = "**TEST**";
#else
ltrBuild.Text = "**LIVE**";
#endif
}
问题是block
由'{' statement_list? '}'
或pp_directive
组成。在这种特定情况下,它选择第一个,因为它看到的第一个令牌是{
(在if
条件之后(。现在,它预计可能会看到statement_list?
,然后是}
,但它发现的是#if TEST
,pp_directive
。
我们该怎么办?让你的pp_directive
成为一个声明。由于我们知道statement_list: statement+;
,我们搜索statement
并将pp_directive
添加到其中:
statement
: labeled_statement
| declaration_statement
| embedded_statement
| pp_directive
;
它应该运行良好。然而,我们也必须看看你的block: ... | pp_directive
是否应该被删除,它应该被删除。我会让它帮你找出原因,但这里有一个不明确的测试用例:
if (!IsPostBack)
#pragma X
else {
}