在python中使用antlr

use*_*522 6 antlr python-2.7

我试图在python中使用lexer.py和parser.py,但它在此代码中有错误:

import antlr3
import antlr3.tree
import traceback
from test22Lexer import test22Lexer
from test22Parser import test22Parser
char_stream = antlr3.ANTLRStringStream("input.txt")
lexer = test22Lexer(char_stream)
tokens = antlr3.CommonTokenStream(lexer)
parser = test22Parser(tokens)
parser.block()
Run Code Online (Sandbox Code Playgroud)

而错误是:

  class block_return(ParserRuleReturnScope):
  NameError: name 'ParserRuleReturnScope' is not defined
Run Code Online (Sandbox Code Playgroud)

我需要帮助:D

解析器:

class block_return(ParserRuleReturnScope):
def __init__(self):
    super(test22Parser.block_return, self).__init__()

    self.tree = None
Run Code Online (Sandbox Code Playgroud)

Nil*_*Nil 0

老实说,我对 ANTLR 一无所知,但你应该对 Python 的错误消息更有信心:

NameError: name 'ParserRuleReturnScope' is not defined
Run Code Online (Sandbox Code Playgroud)

它清楚地表明它尚未定义,因此您忘记包含它。正如您在Python ANTLR page中看到的,他们建议将其与通配符一起包含,例如:

from antlr3 import *
Run Code Online (Sandbox Code Playgroud)

这将使它工作,因为如果我没有记错的话,ParserRuleReturnScope它是在antlr3包中定义的。如果您不想导入 中的所有内容antlr,您可以按原样导入它,并在包中为所有 objec 添加前缀,例如:altlr3.ParserRuleReturnScope

正如我所写,我对 ANTLR 一无所知,抱歉,如果它不起作用,我试图提供帮助:)