我在使用PLY时遇到问题。我一直在阅读文档,并决定尝试这些例子。词法分析的例子运行得很好,但我无法进行解析。我也不明白如何将lex和yacc接口在一起以创建一个合适的编译器。解析器只包含lexer可能的标记,而且据我所知,没有其他内容。
我添加了一些东西,比如颜色(Colorama模块)和稍微不同的消息,但除此之外,这与示例相同:
#!/usr/bin/env python
### LEXICAL ANALYSIS ###
import ply.lex as lex
import colorama
colorama.init()
tokens = (
"NUMBER",
"PLUS",
"MINUS",
"MULTIPLY",
"DIVIDE",
"LBRACKET",
"RBRACKET"
)
t_PLUS = r"+"
t_MINUS = r"-"
t_MULTIPLY = r"*"
t_DIVIDE = r"/"
t_LBRACKET = r"("
t_RBRACKET = r")"
t_ignore = "tr "
def t_NUMBER(t):
r"d+"
t.value = int(t.value)
return t
def t_newline(t):
r"n+"
t.lexer.lineno += len(t.value)
def t_COMMENT(t):
r"#.*"
print "Comment:", t.value
def t_error(t):
print colorama.Fore.RED + "nnLEXICAL ERROR: line", t.lexer.lineno, "and position", t.lexer.lexpos, "invalid token:", t.value.split("n")[0] + colorama.Fore.RESET
t.lexer.skip(len(t.value))
def mylex(inp):
lexer = lex.lex()
lexer.input(inp)
for token in lexer:
print "Token:", token
这很好,但解析器却不行:
#!/usr/bin/env python
import ply.yacc as yacc
from langlex import tokens
def p_expression_plus(p):
"expression : expression PLUS term"
p[0] = p[1] + p[3]
def p_expression_minus(p):
"expression : expression MINUS term"
p[0] = p[1] - p[3]
def p_expression_term(p):
"expression : term"
p[0] = p[1]
def p_term_times(p):
"term : term MULTIPLY factor"
p[0] = p[1] * p[3]
def p_term_div(p):
"term : term DIVIDE factor"
p[0] = p[1] / p[3]
def p_term_factor(p):
"term : factor"
p[0] = p[1]
def p_factor_num(p):
"factor : NUMBER"
p[0] = p[1]
def p_factor_expr(p):
"factor : LBRACKET expression RBRACKET"
p[0] = p[2]
def p_error(p):
print "Syntax error!"
parser = yacc.yacc()
while True:
s = raw_input("calc > ")
if not(s):
continue
result = parser.parse(s)
print result
当我尝试运行它时,我得到以下错误:
calc > 5 + 10
Traceback (most recent call last):
File "C:UsersMaxDesktoplanglangyacc.py", line 49, in <module>
result = parser.parse(s)
File "C:Python27libsite-packagesplyyacc.py", line 265, in parse
return self.parseopt_notrack(input,lexer,debug,tracking,tokenfunc)
File "C:Python27libsite-packagesplyyacc.py", line 881, in parseopt_notrack
lexer = lex.lexer
AttributeError: 'module' object has no attribute 'lexer'
我是lex、yacc和编译器开发的初学者,不知道为什么会发生这种情况。如有任何帮助,我们将不胜感激。
您尚未在lexer文件中构建lexer。您在函数mylex()
中有它,但实际上并没有构建它。
将其从功能中拉出。
lexer = lex.lex()
def mylex(inp):
lexer.input(inp)
# etc.