作为初学者,当我从The Definitive ANTLR 4 Reference学习ANTLR4时书中,我尝试运行第 7 章练习的修改版本:
/**
* to parse properties file
* this example demonstrates using embedded actions in code
*/
grammar PropFile;
@header {
import java.util.Properties;
}
@members {
Properties props = new Properties();
}
file
:
{
System.out.println("Loading file...");
}
prop+
{
System.out.println("finished:\n"+props);
}
;
prop
: ID '=' STRING NEWLINE
{
props.setProperty($ID.getText(),$STRING.getText());//add one property
}
;
ID : [a-zA-Z]+ ;
STRING :(~[\r\n])+; //if use STRING : '"' .*? '"' everything is fine
NEWLINE : '\r'?'\n' ;
由于 Java 属性只是键值对,所以我使用 STRING
来匹配除 NEWLINE
之外的所有内容(我不希望它只支持双引号中的字符串) )。当运行下面的句子时,我得到:
D:\Antlr\Ex\PropFile\Prop1>grun PropFile prop -tokens
driver=mysql
^Z
[@0,0:11='driver=mysql',<3>,1:0]
[@1,12:13='\r\n',<4>,1:12]
[@2,14:13='<EOF>',<-1>,2:14]
line 1:0 mismatched input 'driver=mysql' expecting ID
当我使用 STRING : '"' .*? '"'
时,它可以工作。
我想知道我错在哪里,以便以后避免类似的错误。
请给我一些建议,谢谢!
最佳答案
由于 ID 和 STRING 都可以匹配以“driver”开头的输入文本,因此词法分析器将选择最长的可能匹配,即使 ID 规则排在第一位。
所以,你有多种选择。最直接的方法是通过要求字符串以等号开头来消除 ID 和 STRING 之间的歧义(这就是您的替代方案的工作方式)。
file : prop+ EOF ;
prop : ID STRING NEWLINE ;
ID : [a-zA-Z]+ ;
STRING : '=' (~[\r\n])+;
NEWLINE : '\r'?'\n' ;
然后,您可以使用操作从字符串标记的文本中删除等号。
或者,您可以使用谓词来消除规则的歧义。
file : prop+ EOF ;
prop : ID '=' STRING NEWLINE ;
ID : [a-zA-Z]+ ;
STRING : { isValue() }? (~[\r\n])+;
NEWLINE : '\r'?'\n' ;
其中 isValue 方法向后查找字符流以验证它是否遵循等号。像这样的东西:
@members {
public boolean isValue() {
int offset = _tokenStartCharIndex;
for (int idx = offset-1; idx >=0; idx--) {
String s = _input.getText(Interval.of(idx, idx));
if (Character.isWhitespace(s.charAt(0))) {
continue;
} else if (s.charAt(0) == '=') {
return true;
} else {
break;
}
}
return false;
}
}
关于java - Ant : beginner 's mismatched input expecting ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23318705/