2014-04-27 39 views
1

作为一个初学者,当我从The Definitive ANTLR 4 Reference书学习ANTLR4,我试图从第7章运行我练习的修改后的版本:ANTLR的:初学者的不匹配输入期待ID

/** 
* 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 : '"' .*? '"'相反,它的工作原理。

我想知道我错在哪里,以便将来避免类似的错误。

请给我一些建议,谢谢!

+0

因为ID也会匹配字符串值,如果我想允许字符串作为值,但不是在双引号,如何做到这一点? – wangdq

回答

1

由于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; 
} 
} 
+0

感谢您的详细回答。我误解了如果ID先来,那么当遇到歧义时,它会选择ID作为选择。另外一些人建议不要使用与STRING相匹配的规则:(〜[\ r \ n]) +;在我的情况下,java属性文件只包含String-String(未引用),所以我会按照你的方法。 – wangdq

相关问题