A parsing library for Parsing Expression Grammars (PEG), with a native engine written in Rust and a Transformer that turns parse trees into your own objects.
- A grammar is plain text, loaded at runtime. No code generation and no build step.
- The engine compiles a grammar to bytecode for a parsing machine and builds a compact, lossless tree with exact source positions.
- Errors say where a parse failed and what was expected there, a grammar can name its mistakes and go on past them, and limits bound the time and memory of every parse.
import fpeg
grammar = fpeg.Grammar(r"""
start: pair ** ","
pair: key=NAME "=" value=NUMBER
NAME: [a-z]+
NUMBER: [0-9]+
%ignore " "+
""")
tree = grammar.parse("x = 1, y = 22")
print(tree.pretty())start
pair
key=x
value=1
pair
key=y
value=22
A Transformer turns the tree into values, with one method for each rule:
class ToDict(fpeg.Transformer):
def start(self, *pairs):
return dict(pairs)
def pair(self, key, value):
return str(key), int(value)
print(ToDict().transform(tree)){'x': 1, 'y': 22}
For Python 3.11 or newer:
pip install fpegFor Rust 1.98 or newer, the library is the crate fpeg:
cargo add fpegThe fpeg command checks grammars, parses inputs and profiles a parse. Each release comes with it built for Linux, macOS and Windows, and Cargo builds it from source:
cargo install fpeg-cliThe benchmarks page has the numbers of the newest recorded runs, and the benchmarks folder the scripts that take them.
- Getting started: install fpeg, write a first grammar and turn its tree into values, in five minutes.
- Examples: a calculator, a configuration file, CSV, JSON and a filter language, each a grammar and a
Transformer. - Tutorials and guides on operator precedence, syntax trees, indentation, modules, errors and performance.
- The reference of the grammar language, the Python API and the command line.
Editor support is planned for the next release: a language server, a formatter and highlighting for grammar files. The page of planned features lists what comes after.
Licensed under either of the MIT licence or the Apache License, Version 2.0, at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in fpeg by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.