How to parse tree using python2 runtime with antlr4

I am trying to use antlr4 version 4.4 and python2 runtime . Grammar from antlr4 book, page 6, file: Hello.g4:

grammar Hello;           
r  : 'hello' ID ;
ID : [a-z]+ ;
WS : [ \t\r\n]+ -> skip ;

      

and i create lexer and parser with command

antlr4 -Dlanguage=Python2 Hello.g4

      

then the files HelloLexer.py, HelloParser.py and HelloListener.py are generated. I am doing a main program test.py to test the generated python parser:

from antlr4 import *
from HelloLexer import HelloLexer
from HelloParser import HelloParser

def main(argv):
    input = FileStream(argv[1])
    lexer = HelloLexer(input)
    stream = CommonTokenStream(lexer)
    parser = HelloParser(stream)
    tree = parser.r()
    print tree.toStringTree(parser)        <= the problem is here!

if __name__ == '__main__':
    import sys
    main(sys.argv)

      

Everything works fine except that I cannot print the parse tree.

C:\Users\LG\antlr\tpantlr2-code\code\install>Test.py data.txt
Traceback (most recent call last):
  File "C:\Users\LG\antlr\tpantlr2-code\code\install\Test.py", line 15, in <module>
    main(sys.argv)
  File "C:\Users\LG\antlr\tpantlr2-code\code\install\Test.py", line 11, in main
    print tree.toStringTree(parser)
  File "C:\Python27\lib\site-packages\antlr4\RuleContext.py", line 181, in toStringTree
    return Trees.toStringTree(self, ruleNames=ruleNames, recog=recog)
  File "C:\Python27\lib\site-packages\antlr4\tree\Trees.py", line 48, in toStringTree
    s = escapeWhitespace(cls.getNodeText(t, ruleNames), False)
  File "C:\Python27\lib\site-packages\antlr4\tree\Trees.py", line 68, in getNodeText
    return ruleNames[t.getRuleContext().getRuleIndex()]
TypeError: 'HelloParser' object does not support indexing

      

I haven't figured out what the problem is yet.

+3


source to share


2 answers


It looks like you accepted the wrong function toStringStree

.

Take a look at the java docs .



This explains the "object does not support indexing" error message. The selected function expects a list of rule names, not a parser.

+2


source


Oddly enough, toStringTree is a class method at runtime Python. You can call it like this to get a lisp style parse tree including string tokens:



from antlr4 import *
from antlr4.tree.Trees import Trees
# import your parser & lexer here

# setup your lexer, stream, parser and tree like normal

print(Trees.toStringTree(tree, None, parser))

# the None is an optional rule names list

      

+1


source







All Articles