跳转到主要内容

一个与RPython兼容的纯Python Lex/Yacc

项目描述

https://secure.travis-ci.org/alex/rply.png

欢迎使用RPLY!这是一个纯Python解析器生成器,也适用于RPython。它是David Beazley的出色PLY的直接移植,具有新的公共API和RPython支持。

您可以在线上找到文档。

基本API

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

然后您可以这样做

parser.parse(lexer.lex("1 + 3 - 2+12-32"))

您也可以替换自己的词法分析器。词法分析器是一个具有next()方法的对象,它返回序列中的下一个令牌,或者如果令牌流已耗尽,则返回None

为什么我们有这些盒子?

在RPython中,与其他静态类型语言一样,变量必须具有特定的类型,我们利用多态性将值保持在盒子中,以确保一切都是静态类型。您可以为您的项目编写所需的任何盒子。

如果您不打算从RPython使用解析器,只想获得一个酷炫的纯Python解析器,您可以直接忽略所有关于盒子的事情,并从每个生成方法中返回您喜欢的任何内容。

错误处理

默认情况下,当遇到解析错误时,会引发一个rply.ParsingError,它有一个getsourcepos()方法,返回一个rply.token.SourcePosition对象。

您还可以提供错误处理程序,目前它必须引发异常。它接收解析器错误的Token对象。

pg = ParserGenerator(...)

@pg.error
def error_handler(token):
    raise ValueError("Ran into a %s where it wasn't expected" % token.gettokentype())

Python兼容性

RPly已在Python 2.7、3.4+和PyPy下进行测试,并且已知可以正常工作。它也是从6c642ae7a0ea开始的PyPy检查点的有效RPython。

项目详情


下载文件

下载适用于您平台的文件。如果您不确定该选择哪个,请了解更多关于安装包的信息。

源代码分发

rply-0.7.8.tar.gz (15.8 kB 查看哈希值)

上传时间 源代码

构建分发

rply-0.7.8-py2.py3-none-any.whl (16.0 kB 查看哈希值)

上传时间 Python 2 Python 3

由以下支持