So, I'm trying to use Antlr4 for Python to generate Abstract Syntax Trees from my code. I'm pretty much following exactly every step described here: https://github.com/antlr/antlr4/blob/master/doc/python-target.md
Since I'm trying to parse Python code, I downloaded the Python grammar from here:https://github.com/antlr/grammars-v4/blob/master/python/python3-py/Python3.g4
which I renamed as MyGrammar
. From that step onwards, I did exactly the same things described in the link. I did antlr4 -Dlanguage=Python3 MyGrammar.g4
from the Terminal, and then I created the following Python script:
from antlr4 import *
from MyGrammarLexer import MyGrammarLexer
from MyGrammarParser import MyGrammarParser
def main(argv):
input_stream = FileStream(argv[1])
lexer = MyGrammarLexer(input_stream)
stream = CommonTokenStream(lexer)
parser = MyGrammarParser(stream)
tree = parser.startRule()
if __name__ == '__main__':
main(sys.argv)
However, for some reason I'm getting 'MyGrammarParser' object has no attribute 'startRule'
.
I know this question has been asked previously here (AttributeError: 'MuParser' object has no attribute 'startRule'), but people are recommending to use the parse
command instead. The problem is that I'm getting the same problem (it is not recognized as an attribute). Any ideas?