Reputation: 109
I'm trying to count the method declarations in my java code A.java using Antlr produced parser and lexer for Java obtained from Github. The code that I'm trying is as follows:
package antlrjavaparser;
import java.io.FileInputStream;
import java.io.InputStream;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
public class TestListener extends Java8BaseListener{
static int methodCount=0;
public static void main(String args[]) throws Exception {
InputStream in = new FileInputStream("src/main/java/A.java");
ANTLRInputStream input = new ANTLRInputStream(in);
if (in == null){
System.err.println("Unable to find test file.");
}
Java8Lexer lex = new Java8Lexer(input);
CommonTokenStream tokens = new CommonTokenStream(lex);
Java8Parser parser = new Java8Parser(tokens);
ParseTree tree = null;
tree = parser.compilationUnit();
ParseTreeWalker walker = new ParseTreeWalker();
Java8BaseListener listener = new Java8BaseListener();
walker.walk(listener, tree);
printTokens(lex);
System.out.println(methodCount);
}
private static void printTokens(Java8Lexer lex) {
// Print tokens
Token token = null;
while ((token = lex.nextToken()) != null) {
if (token.getType() == Token.EOF) {
break;
}
if (token.getChannel() == Token.HIDDEN_CHANNEL) {
continue;
}
System.out.println("Token: [" + token.getText() + "] Type:[" + token.getType() + "]");
}
lex.reset();
}
@Override
public void enterMethodDeclaration(Java8Parser.MethodDeclarationContext ctx) {
methodCount++;
}
}
methodCount
prints 0
every time. A.java is a very simple java class containing a few methods. I've tried overriding multiple methods from Java8BaseListener
to see if any of them is triggered at all but it looks like they're not. Am I using antlr wrong? Is there anything wrong with the way I'm using walker
? I just started working on this two days ago so I don't really know antlr too well. Any help would be appreciated.
Upvotes: 0
Views: 181
Reputation: 370162
Java8BaseListener listener = new Java8BaseListener();
Here you're instantiating the base listener, which does nothing. You should be instantiating your subclass of it. So:
Java8BaseListener listener = new TestListener();
Upvotes: 1