Python-多个主要rply语法规则

时间:2019-04-07 22:15:17

标签: python parsing ply

以下是我从here提取的python-rply代码:

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

在此基本的python-rply代码中,您可以添加和减去数字。假设我想在此代码中添加一个新元素,例如变量。根据我的观察,在定义@pg.production("main : expr")函数之前,我将不得不在main部分添加一个新的 main 语法规则。我的问题是如何添加新的 main 语法规则?我是否可以像这样添加另一个装饰器:

@pg.production("main : expr")
@pg.production("main : <MY_NEW_ELEMENT_STUFF>")

如果是这样,有没有更有效的方法(如果在其中添加更多元素,则会变得局促)?

注意:我使用的是rply,而不是ply,但是它们非常相似。

0 个答案:

没有答案