我有以下语法:
public struct SYSTEM_INFO
{
...
public UIntPtr minimumApplicationAddress;
public UIntPtr maximumApplicationAddress;
...
}
public static void Main()
{
SYSTEM_INFO sys_info = new SYSTEM_INFO();
GetSystemInfo(out sys_info);
UIntPtr proc_min_address = sys_info.minimumApplicationAddress;
UIntPtr proc_max_address = sys_info.maximumApplicationAddress;
// saving the values as ulong ints so I won't have to do a lot of casts later
ulong proc_min_address_l = (ulong)proc_min_address;
ulong proc_max_address_l = (ulong)proc_max_address;
Console.WriteLine("Min Addr: {0}, Max Addr: {1}", proc_min_address_l, proc_max_address_l);
}
我的问题是以下2种语言有效:
myg : line+ EOF ;
line : ( for_loop | command params ) NEWLINE;
for_loop : FOR WORD INT DO NEWLINE stmt_body;
stmt_body: line+ END;
params : ( param | WHITESPACE)*;
param : WORD | INT;
command : WORD;
fragment LOWERCASE : [a-z] ;
fragment UPPERCASE : [A-Z] ;
fragment DIGIT : [0-9] ;
WORD : (LOWERCASE | UPPERCASE | DIGIT | [_."'/\\-])+ (DIGIT)* ;
INT : DIGIT+ ;
WHITESPACE : (' ' | '\t')+ -> skip;
NEWLINE : ('\r'? '\n' | '\r')+ -> skip;
FOR: 'for';
DO: 'do';
END: 'end';
这是打印带有“ for”字样的消息的有效命令。
message please wait for 90 seconds
这将是for n 2 do
循环的开始。
问题在于,当前的词法分析器与for循环不匹配,因为'for'在第一次出现时就被WORD规则匹配。
我可以通过将FOR规则放在WORD规则之前来解决此问题,但是消息中的“ for”将被FOR规则匹配
答案 0 :(得分:2)
这是典型的关键字与标识符的问题,我认为Stackoverflow上存在很多与此有关的问题。但是令我惊讶的是,我只能找到一个old answer of mine for ANTLR3。
即使提到的原理仍然相同,您也无法使用ANTLR4在解析器规则中更改返回的令牌类型。
要使方案正常工作,需要执行两个步骤。
WORD
规则之前定义关键字。这样,他们就能获得语法部分所需的自己的标记类型,而这些标记部分需要特定的关键字。第二步,修改您的规则:
param: WORD | INT | commandKeyword;
command: WORD | commandKeyword;
commandKeyword: FOR | DO | END; // Keywords allowed as names in commands.