如何使用 python2 运行时和 antlr4 打印解析树 [英] how print parse-tree using python2 runtime with antlr4

查看:44
本文介绍了如何使用 python2 运行时和 antlr4 打印解析树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 antlr4 4.4 版python2 运行时.语法来自 antlr4 书,第 6 页,文件:Hello.g4:

I'm trying to use antlr4 version 4.4 and the python2 runtime. The grammar is from the antlr4 book, page 6, file: Hello.g4:

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

我用命令生成词法分析器和解析器

and I generate lexer and parser with command

antlr4 -Dlanguage=Python2 Hello.g4

文件 HelloLexer.pyHelloParser.pyHelloListener.py 等,然后生成.我做了一个主程序 test.py 来测试生成的 python 解析器:

the files HelloLexer.py, HelloParser.py and HelloListener.py among other, are then generated. I make 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 seems works ok, except that I can't 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 yet what the problem is.

推荐答案

看起来你用错了 toStringStree 函数.

It looks like you took the wrong toStringStree function.

看看java 文档.

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

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

这篇关于如何使用 python2 运行时和 antlr4 打印解析树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆