I'm trying to find all overridden methods in java files using antlr4 with python runtime. I have taken the grammar from https://github.com/antlr/grammars-v4/tree/master/java. I'm able to find the methods using the below code successfully.
istream = FileStream(repo_path, encoding='utf-8')
lexer = JavaLexer(istream)
stream = CommonTokenStream(lexer)
parser = JavaParser(stream)
tree = parser.compilationUnit()
walker = ParseTreeWalker()
walker.walk(PatternListener(), tree)
Inside Listener,
def enterMethodDeclaration(self, ctx):
method_name = ctx.IDENTIFIER().getText()
method_defition = ctx.methodBody().getText()
Now I want to track only overridden methods, not all the methods. so, I made below changes.
In JavaLexer.g4,
OVERRIDEN '@Override';
In JavaParser.g4,
methodDeclaration
: OVERRIDEN typeTypeOrVoid IDENTIFIER formalParameters ('[' ']')*
(THROWS qualifiedNameList)?
methodBody
;
to restrict methodDeclaration to only overriden method, and I have re-generated all lexer and parser again. But this time I'm getting many mismatch issues while parsing, like below.
line 71:15 extraneous input 'void' expecting {<EOF>, 'abstract', 'boolean', 'byte', 'char', 'class', 'double', 'enum', 'final', 'float', 'int', 'interface', 'long', 'native', 'private', 'protected', 'public', 'short', 'static', 'strictfp', 'synchronized', 'transient', 'volatile', '@Override', '{', '}', ';', '<', '@', IDENTIFIER}
line 74:23 mismatched input '(' expecting ';'
Can anyone please highlight the mistake which I'm doing here, is there any other way to implement this?. Any suggestions or discussions are appreciated. Thank you in advance:).