Antlr4听众无法找到孩子

时间:2014-04-03 05:56:07

标签: antlr antlr4

我有这个语法:

grammar Test;

node:
    BEGIN BLOCK
    name=STRING
    noOfKvp=INT

    (
    key_value_pair |
    hasOptionalThing=OPTIONAL_THING
    )*

    END BLOCK
    ;

key_value_pair
    :   key=number value=number
    ;

number
    : INT | FLOAT
    ;

BEGIN : 'BEGIN';
END : 'END';
BLOCK : 'BLOCK';
OPTIONAL_THING : 'OPTIONAL_THING' ;
STRING : '"' .*? '"';

INT
    : MINUS? DIGIT+
    ;

FLOAT
    : MINUS? ('0'..'9')+ '.' ('0'..'9')* EXPONENT? | MINUS? '.' ('0'..'9')+ EXPONENT? | MINUS? ('0'..'9')+ EXPONENT
    ;

fragment MINUS
    : '-'
    ;

fragment EXPONENT
    : ('e'|'E') ('+'|'-')? ('0'..'9')+
    ;

DIGIT
    : '0'..'9'
    ;


WS : ( ' ' | '\t' | '\r' | '\n')+ -> skip;

此示例文件:

BEGIN BLOCK
    "Blockname"
    5
    1 5
    2 7.5
    3.3 10
    4 12.5
    5.2 15
END BLOCK

现在,当我解析它时,我似乎无法在听众中获得键值对:

public class MyListener extends TestBaseListener  {

    @Override
    public void exitNode(TestParser.NodeContext ctx) {
        super.exitNode(ctx);
        List<TestParser.Key_value_pairContext> keyValuePairs = ctx.key_value_pair();
        System.out.println(keyValuePairs.size());
    }          
}

输出为0.我不明白为什么......

编辑:这是我运行解析器的代码

public static void main(String[] args) throws IOException {
        ANTLRFileStream stream = new ANTLRFileStream("C:\\temp\\SimpleGrammarTest.txt");
        TestLexer lexer = new TestLexer(stream);
        TokenStream tokenStream = new CommonTokenStream(lexer);
        TestParser parser = new TestParser(tokenStream);
        parser.setBuildParseTree(false);
        parser.addParseListener(new MyListener());
        parser.node();
    }

1 个答案:

答案 0 :(得分:1)

我无法重现这一点。鉴于班级:

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

public class Main {
    public static void main(String[] args) throws Exception {

        TestLexer lexer = new TestLexer(new ANTLRFileStream("test.txt"));
        // `test.txt` contains your input, btw

        TestParser parser = new TestParser(new CommonTokenStream(lexer));
        ParseTree tree = parser.node();

        ParseTreeWalker walker = new ParseTreeWalker();
        walker.walk(new MyListener(), tree);
    }
}

并进行以下测试:

java -cp antlr-4.2.1-complete.jar org.antlr.v4.Tool Test.g4 
javac -cp .:antlr-4.2.1-complete.jar *.java
java -cp .:antlr-4.2.1-complete.jar Main

我看到5正在我的控制台上打印。