Reputation: 1259
I am trying to run strp by step instruction as per - http://meri-stuff.blogspot.com/2011/08/antlr-tutorial-hello-word.html
Original code as per the above webpage -
public CommonTree compile(String expression) {
try {
//lexer splits input into tokens
ANTLRStringStream input = new ANTLRStringStream(expression);
TokenStream tokens = new CommonTokenStream( new S001HelloWordLexer( input ) );
//parser generates abstract syntax tree
S001HelloWordParser parser = new S001HelloWordParser(tokens);
S001HelloWordParser.expression_return ret = parser.expression();
//acquire parse result
CommonTree ast = (CommonTree) ret.tree;
printTree(ast);
return ast;
} catch (RecognitionException e) {
throw new IllegalStateException("Recognition exception is never thrown, only declared.");
}
}
I have modified some part of the code below:
public CommonTree compile(String expression) {
try {
//lexer splits input into tokens
ANTLRStringStream input = new ANTLRStringStream(expression);
TokenStream tokens = new CommonTokenStream( (TokenSource) new S001HelloWordLexer( (CharStream) input ) );
//parser generates abstract syntax tree
S001HelloWordParser parser = new S001HelloWordParser((org.antlr.v4.runtime.TokenStream) tokens);
S001HelloWordParser.expression_return ret = parser.expression();
//acquire parse result
CommonTree ast = (CommonTree) ret.tree;
printTree(ast);
return ast;
} catch (RecognitionException e) {
throw new IllegalStateException("Recognition exception is never thrown, only declared.");
}
}
The issue is in my S001HelloWordParser file, there is no method as expression() nor is there a static class names 'expression_return', so I am not able to create the variable 'ret' on whom I could call the tree() method. Is there anything I am missing here?
How else can I generate the tree? Or any idea about the process using antlr 4.7 version?
Please help. Thanks!
Upvotes: 0
Views: 906
Reputation: 170308
I am trying to run strp by step instruction as per - http://meri-stuff.blogspot.com/2011/08/antlr-tutorial-hello-word.html
Don't. That tutorial is about ANTLR 3, you need to find an ANTLR 4 tutorial.
The issue is in my S001HelloWordParser file, there is no method as expression() nor is there a static class names 'expression_return'
That means your S001HelloWord
grammar does not contain a parser rule called expression
.
Start from the source: https://github.com/antlr/antlr4/blob/master/doc/getting-started.md
And here's a Q&A (with full code examples) about an expression parser for ANTLR4: If/else statements in ANTLR using listeners
Upvotes: 1