Python Rply为多个不同的函数分配多个不同的规则

2024-04-29 13:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个python rply代码,如下所示(取自here):

from rply import ParserGenerator, LexerGenerator
from rply.token import BaseBox

lg = LexerGenerator()
# Add takes a rule name, and a regular expression that defines the rule.
lg.add("PLUS", r"\+")
lg.add("MINUS", r"-")
lg.add("NUMBER", r"\d+")

lg.ignore(r"\s+")

# This is a list of the token names. precedence is an optional list of
# tuples which specifies order of operation for avoiding ambiguity.
# precedence must be one of "left", "right", "nonassoc".
# cache_id is an optional string which specifies an ID to use for
# caching. It should *always* be safe to use caching,
# RPly will automatically detect when your grammar is
# changed and refresh the cache for you.
pg = ParserGenerator(["NUMBER", "PLUS", "MINUS"],
        precedence=[("left", ['PLUS', 'MINUS'])], cache_id="myparser")

@pg.production("main : expr")
def main(p):
    # p is a list, of each of the pieces on the right hand side of the
    # grammar rule
    return p[0]

@pg.production("expr : expr PLUS expr")
@pg.production("expr : expr MINUS expr")
def expr_op(p):
    lhs = p[0].getint()
    rhs = p[2].getint()
    if p[1].gettokentype() == "PLUS":
        return BoxInt(lhs + rhs)
    elif p[1].gettokentype() == "MINUS":
        return BoxInt(lhs - rhs)
    else:
        raise AssertionError("This is impossible, abort the time machine!")

@pg.production("expr : NUMBER")
def expr_num(p):
    return BoxInt(int(p[0].getstr()))

lexer = lg.build()
parser = pg.build()

class BoxInt(BaseBox):
    def __init__(self, value):
        self.value = value

    def getint(self):
        return self.value

这是一个简单的代码,因此当您键入以下内容时:

^{pr2}$

它将执行,并将4作为输出和答案。这是一个有效的代码,但仍需要改进。代码中调用@pg.production进行加法和减法的那部分代码效率不高;我的意思是,如果再添加几个运算符,它将变得非常狭窄。有没有一个好的方法来制作一个类似于这样的零件的非狭窄版本:

@pg.production("expr : expr PLUS expr")
def plus(p):
    lhs = p[0].getint()
    rhs = p[2].getint()
    if p[1].gettokentype() == "PLUS":
        return BoxInt(lhs + rhs)
    else:
        raise AssertionError("This is impossible, abort the time machine!")

@pg.production("expr : expr MINUS expr")
def minus(p):
    lhs = p[0].getint()
    rhs = p[2].getint()

    if p[1].gettokentype() == "MINUS":
        return BoxInt(lhs - rhs)
    else:
        raise AssertionError("This is impossible, abort the time machine!")

注意:我使用的是rply,不是{a3},但它们非常相似。


Tags: ofthereturnisdefplusproductionpg
1条回答
网友
1楼 · 发布于 2024-04-29 13:19:51

如果你把函数分开,这样每个产品都有自己的函数,这确实是最好的做法,那么检查操作符的令牌类型是完全没有意义的。您知道它是什么,因为解析器的逻辑意味着只有与生产匹配的函数才会被调用。在

因此您可以编写相当紧凑的代码:

@pg.production("expr : expr PLUS expr")
def plus(p):
    return BoxInt(p[0].getint() +  p[2].getint())

@pg.production("expr : expr MINUS expr")
def minus(p):
    return BoxInt(p[0].getint() -  p[2].getint())

相关问题 更多 >