如何使用python2运行时与antlr4打印解析树

时间:2014-08-05 10:22:59

标签: python-2.7 antlr4

我正在尝试使用antlr4 version 4.4python2 runtime。语法来自antlr4书,第6页,文件: Hello.g4

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

我用命令

生成词法分析器和解析器
antlr4 -Dlanguage=Python2 Hello.g4

然后生成 HelloLexer.py HelloParser.py HelloListener.py 等文件。我创建一个主程序test.py来测试生成的python解析器:

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)

除了我无法打印解析树外,一切似乎都运行正常。

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

我还没弄清楚问题是什么。

2 个答案:

答案 0 :(得分:3)

奇怪的是,toStringTree是Python运行时中的一个类方法。您可以像这样调用它来获取包含字符串化标记的lisp样式解析树:

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 :(得分:2)

看起来您使用了错误的toStringStree功能。

查看java docs

这解释了错误消息“对象不支持索引”。您选择的函数需要一个规则名称列表而不是解析器。