LEPL递归解析器

联合创作 · 2023-10-01 04:46

LEPL是一个用 Python 开发的向下递归解析器。It is based on parser combinator libraries popular in functional programming, but also exploits Python language features. Operators provide a friendly syntax, and the consistent use of generators supports full backtracking and resource management. Backtracking implies that a wide variety of grammars are supported; appropriate memoisation ensures that even left-recursive grammars terminate.
>>> from lepl import *

>>> class Term(Node): pass
>>> class Factor(Node): pass
>>> class Expression(Node): pass

>>> expr = Delayed()
>>> number = Digit()[1:,...] > 'number'
>>> spaces = Drop(Regexp(r'\s*'))

>>> with Separator(spaces):
>>> term = number | '(' & expr & ')' > Term
>>> muldiv = Any('*/') > 'operator'
>>> factor = term & (muldiv & term)[:] > Factor
>>> addsub = Any('+-') > 'operator'
>>> expr += factor & (addsub & factor)[:] > Expression
>>> line = expr & Eos()

>>> parser = line.parse_string
>>> parser('1 + 2 * (3 + 4 - 5)')[0]

Expression
+- Factor
| +- Term
| | `- number '1'
| `- ' '
+- operator '+'
+- ' '
`- Factor
+- Term
| `- number '2'
+- ' '
+- operator '*'
+- ' '
`- Term
+- '('
+- Expression
| +- Factor
| | +- Term
| | | `- number '3'
| | `- ' '
| +- operator '+'
| +- ' '
| +- Factor
| | +- Term
| | | `- number '4'
| | `- ' '
| +- operator '-'
| +- ' '
| `- Factor
| `- Term
| `- number '5'
`- ')
浏览 8
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报