2

这是一个我认为很容易解析的简单语法测试,但我马上就得到了“不匹配的输入”,我无法弄清楚 Antlr 正在寻找什么。

输入:

  # include "something" program TEST1 { BLAH BLAH }

我的语法:

  grammar ProgHeader;

  program: header* prog EOF ;
  header: '#' ( include | define ) ;
  include: 'include' string ;
  define: 'define' string string? ;
  string: '"' QTEXT '"' ;
  prog: 'program' QTEXT '{' BLOCK '}' ;
  QTEXT: ~[\r\n\"]+ ;
  BLOCK: ~[}]+ ; // don't care, example block
  WS: [ \t\r\n] -> skip ;

输出错误信息:

line 1:0 mismatched input '# include "something" program TEST1 { BLAH BLAH '
expecting {'program', '#'}

这真的让我很困惑,因为它说它正在寻找一个“#”并且在输入的开头就有一个。我也丢弃了解析树。它似乎卡在“程序”规则的顶部:

(program # include "something" program TEST1 { BLAH BLAH  } )

哈普?

如果重要的话,这里是驱动这个测试用例的完整程序(我认为这不重要,上面的信息就足够了,但在这里):

  package antlrtests;

  import antlrtests.grammars.*;
  import org.antlr.v4.runtime.*;
  import org.antlr.v4.runtime.tree.*;

  /**
   *
   * @author Brenden Towey
   */
  public class ProgHeaderTest {
     private String[] testVectors = {
        "# include \"something\" program TEST1 { BLAH BLAH } ",
     };
     public void runTests() {
        for( String test : testVectors )
           simpleTest( test );
     }
     private void simpleTest( String test ) {
        ANTLRInputStream ains = new ANTLRInputStream( test );
        ProgHeaderLexer wpl = new ProgHeaderLexer( ains );
        CommonTokenStream tokens = new CommonTokenStream( wpl );
        ProgHeaderParser wikiParser = new ProgHeaderParser( tokens );
        ParseTree parseTree = wikiParser.program();
        System.out.println( "'" + test + "': " + parseTree.toStringTree(
                wikiParser ) );
     }
  }

和完整的输出:

run:
line 1:0 mismatched input '# include "something" program TEST1 { BLAH BLAH ' expecting {'program', '#'}
'# include "something" program TEST1 { BLAH BLAH } ': (program # include "something" program TEST1 { BLAH BLAH  } )
BUILD SUCCESSFUL (total time: 0 seconds)
4

1 回答 1

3

最开始匹配的最长标记是 QTEXT,它匹配文本# include(直到第一个字符但不包括第一个"字符的文本),但据报道,该点的有效标记是“程序”和“#”。所以最好避免与几乎任何东西匹配的令牌定义。

于 2013-05-03T18:23:45.670 回答