【发布时间】:2012-08-07 03:00:08
【问题描述】:
我正在尝试使用 ANTLR 编写上下文相关的词法分析器规则,但无法让它完成我需要的工作。该规则需要根据在规则开头找到的字符匹配 2 个备选方案中的 1 个。下面是问题的简化版本。
本例语法:
lexer grammar X;
options
{
language = C;
}
RULE :
SimpleIdent {ctx->someFunction($SimpleIdent);}
(
{ctx->test != true}?
//Nothing
| {ctx->test == true}?
SLSpace+ OtherText
)
;
fragment SimpleIdent : ('a'..'z' | 'A'..'Z' | '_')+;
fragment SLSpace : ' ';
fragment OtherText : (~'\n')* '\n';
如果 ctx->test 为假,我希望词法分析器退出此规则,忽略 SimpleIdent 之后的任何字符。不幸的是,ANTLR 将在 SimpleIdent before 测试谓词之后测试该字符,因此如果那里有空格,它将始终采用第二种选择。这在 C 代码中清楚地显示:
// X.g:10:3: ({...}?|{...}? ( SLSpace )+ OtherText )
{
int alt2=2;
switch ( LA(1) )
{
case '\t':
case ' ':
{
alt2=2;
}
break;
default:
alt2=1;
}
switch (alt2)
{
case 1:
// X.g:11:5: {...}?
{
if ( !((ctx->test != true)) )
{
//Exception
}
}
break;
case 2:
// X.g:13:5: {...}? ( SLSpace )+ OtherText
{
if ( !((ctx->test == true)) )
{
//Exception
}
如何强制 ANTLR 在运行时在词法分析器中采用特定路径?
【问题讨论】: