我正在尝试使用antlr4版本4.4和python2运行时。语法来自antlr4书,第6页,文件:Hello.g4:
grammar Hello;
r : 'hello' ID ;
ID : [a-z]+ ;
WS : [ trn]+ -> skip ;
我用命令
生成词法分析器和解析器antlr4 -Dlanguage=Python2 Hello.g4
然后生成文件 hellohelper .py、HelloParser.py和 hellollistener .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:UsersLGantlrtpantlr2-codecodeinstall>Test.py data.txt
Traceback (most recent call last):
File "C:UsersLGantlrtpantlr2-codecodeinstallTest.py", line 15, in <module>
main(sys.argv)
File "C:UsersLGantlrtpantlr2-codecodeinstallTest.py", line 11, in main
print tree.toStringTree(parser)
File "C:Python27libsite-packagesantlr4RuleContext.py", line 181, in toStringTree
return Trees.toStringTree(self, ruleNames=ruleNames, recog=recog)
File "C:Python27libsite-packagesantlr4treeTrees.py", line 48, in toStringTree
s = escapeWhitespace(cls.getNodeText(t, ruleNames), False)
File "C:Python27libsite-packagesantlr4treeTrees.py", line 68, in getNodeText
return ruleNames[t.getRuleContext().getRuleIndex()]
TypeError: 'HelloParser' object does not support indexing
我还没弄明白是什么问题
奇怪的是,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
看起来您取错了toStringStree
函数
看一下java文档
这解释了错误消息"object does not support indexing"。您选择的函数需要一个规则名称列表,而不是解析器。