gpt4 book ai didi

python-2.7 - 如何将 PLAY 的 lex 和 yacc 封装在两个单独的类中

转载 作者:行者123 更新时间:2023-12-04 12:29:24 26 4
gpt4 key购买 nike

我正在用 PLY 编写自己的解析器。我想分别封装lex和yacc

这是代码
对于 Lex 类:

class Lex:
tokens = (
'NAME', 'NUMBER',
)

literals = ['=', '+', '-', '*', '/', '(', ')']

# Tokens

t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'

...

解析器代码(使用 yacc):
class Parser:

# Parsing rules
tokens = Lex.tokens

def p_statement_assign(self, p):
'statement : NAME "=" expression'
self.names[p[1]] = p[3]

...

def run(self):
print self.tokens
lex.lex(module=Lex) # ----what should I do here?-----
parser = yacc.yacc(module=self)
parser.parse("1+2")

我得到以下错误:
必须使用 Lex 实例作为第一个参数调用未绑定(bind)方法 t_NUMBER()(改为获取 LexToken 实例)

我尝试使用 module=Lex对于 lex,就像 yacc.yacc(module=self) ,但它没有用,任何人都可以告诉解决方案。

最佳答案

这是我第一次尝试构建解释器。我真的不喜欢现代 Python 的 PLY。使用文档字符串来存放正则表达式感觉很奇怪。 PLY 样本似乎也已经过时了。但是,嘿,PLY 的第一个版本于 2001 年发布,16 年后它仍然存在,因此感谢作者/社区维护它。

话虽如此,这就是我如何进行一些封装工作:

class MyLexer(object):
tokens = (
'NUMBER',
'PLUS', 'MINUS', 'TIMES', 'DIVIDE',
'LPAREN', 'RPAREN',
)

t_PLUS = r'\+'
t_MINUS = r'-'
t_TIMES = r'\*'
t_DIVIDE = r'/'
t_LPAREN = r'\('
t_RPAREN = r'\)'

...

def __init__(self):
# Build the lexer
self.lexer = lex.lex(module=self)


class MyParser(object):

tokens = MyLexer.tokens

...

def p_expression_binop(self, t):
'''
expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIVIDE expression
'''
left_hand_side = t[1]
right_hand_side = t[3]
operator = t[2]
if operator == '+':
value = left_hand_side + right_hand_side
elif operator == '-':
value = left_hand_side - right_hand_side
elif operator == '*':
value = left_hand_side * right_hand_side
elif operator == '/':
value = left_hand_side / right_hand_side
else:
raise AssertionError('Unknown operator: {}'.format(operator))

t[0] = value

...

def __init__(self):
self.lexer = MyLexer()
self.parser = yacc.yacc(module=self)

关于python-2.7 - 如何将 PLAY 的 lex 和 yacc 封装在两个单独的类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38262552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com