Parser combinators library with error recovery
Project description
reparsec
Small parsec-like parser combinators library with semi-automatic error recovery.
Installation
pip install reparsec
Usage
Simple arithmetic expression parser and calculator:
from typing import Callable
from reparsec import Delay
from reparsec.scannerless import literal, regexp
from reparsec.sequence import eof
def op_action(op: str) -> Callable[[int, int], int]:
return {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
}[op]
spaces = regexp(r"\s*")
number = regexp(r"\d+").fmap(int) << spaces
mul_op = regexp(r"[*]").fmap(op_action) << spaces
add_op = regexp(r"[-+]").fmap(op_action) << spaces
l_paren = literal("(") << spaces
r_paren = literal(")") << spaces
expr = Delay[str, int]()
value = number | expr.between(l_paren, r_paren)
expr.define(value.chainl1(mul_op).chainl1(add_op))
parser = expr << eof()
print(parser.parse("1 + 2 * (3 + 4)").unwrap())
Output:
15
Out-of-the-box error recovery:
result = parser.parse("1 + 2 * * (3 + 4", recover=True)
try:
result.unwrap()
except ParseError as e:
print(e)
print(result.unwrap(recover=True))
Output:
at 8: expected '(' (skipped 2 tokens), at 16: expected ')' (inserted ')')
15
More examples:
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
reparsec-0.3.3.tar.gz
(19.6 kB
view details)
Built Distribution
reparsec-0.3.3-py3-none-any.whl
(25.4 kB
view details)
File details
Details for the file reparsec-0.3.3.tar.gz
.
File metadata
- Download URL: reparsec-0.3.3.tar.gz
- Upload date:
- Size: 19.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.1 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.6
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9c63a39bf0bfce7716fc1aa0f67f8d9b9445a20d9a329294519d78c5aa1bfccd |
|
MD5 | c43e780af59c126bc23658827948a899 |
|
BLAKE2b-256 | f7325e1b6a26d2dcfd9f4f158d91e3d5450b34d7e798a969ee50920c4e4e6080 |
File details
Details for the file reparsec-0.3.3-py3-none-any.whl
.
File metadata
- Download URL: reparsec-0.3.3-py3-none-any.whl
- Upload date:
- Size: 25.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.1 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.6
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | b10e091a4098ca64fd5ed5e60eee15bbf27efd8a6b3c8fae509001cb3097849a |
|
MD5 | 4c1ce1f428e43e8ecc91cbce9b8d3bdc |
|
BLAKE2b-256 | 8e860c15771e5d80188eccc26d8459beeabcfd870977faee6d372d745ab2c891 |