我有一个简单的语法文件hello.g contains
grammar Hello_world;
utterance : greeting | exclamation;
greeting : interjection subject;
exclamation : 'Hooray!';
interjection : 'Hello';
subject : 'World!';
验证字符串'Hello World!'和'万岁!'
但是如何测试这个语法?在某处我读到我们需要编译解析器和其他人。我是ANTLR的新手,请帮忙。
我使用AntlrWorks1.5生成词法分析器和解析器; 之后使用以下代码运行测试:
import antlr3
from helloworldLexer import helloworldLexer
from helloworldParser import helloworldParser
while True:
expr = raw_input('>>> ')
if expr == '':
break
cStream = antlr3.StringStream(expr)
lexer = helloworldLexer(cStream)
tStream = antlr3.CommonTokenStream(lexer)
parser = helloworldParser(tStream)
result = parser.evaluate()
print result
当我运行上面的python文件时,得到以下错误:
>>> Hello World!
Traceback (most recent call last):
File "C:\Users\Lenovo\workspace\antlr\output\hello.py", line 12, in <module>
lexer = helloworldLexer(cStream)
File "C:\Users\Lenovo\workspace\antlr\output\helloworldLexer.py", line 26, in __init__
state = RecognizerSharedState()
NameError: global name 'RecognizerSharedState' is not defined