Antlr4:输入不匹配

标签 antlr4

这是一个简单的语法测试,我认为很容易解析,但我立即得到“不匹配的输入”,并且我无法弄清楚 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)

最佳答案

在开头匹配的最长标记是 QTEXT,它匹配文本 # include(直到但不包括第一个 " 字符的文本),但是据报道,此时的有效标记是“program”和“#”。因此最好避免与几乎任何内容匹配的标记定义。

关于Antlr4:输入不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16364046/

相关文章:

java - 从 Java 程序分析 C++ 文件

antlr4 - 访问者中的已检查异常

c++ - 我如何在 Antlr4 的解析树中检测空格?

java - Antlr4 在自己的 Maven 模块中

具有冲突标记的 ANTLR 行为

java - 处理 ANTLR4 中的错误

java - ANTLR4 运行时 JAR

java - 如何让antlr语法识别带空格的字符串?

antlr - ANTLR 中的 'semantic predicate' 是什么?

parsing - ANTLR 语法也可以识别数字键和整数