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.1.tar.gz
(19.6 kB
view details)
Built Distribution
reparsec-0.3.1-py3-none-any.whl
(25.4 kB
view details)
File details
Details for the file reparsec-0.3.1.tar.gz
.
File metadata
- Download URL: reparsec-0.3.1.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 | 1b8c55a73104509cd51edd185cf858facaf469c90d55b586bed396cffc79a7b2 |
|
MD5 | 11f0734ebaac7dabcaef7ada1071b893 |
|
BLAKE2b-256 | 0fe340a4f6c8019dd2f0ce9f33835fa64a54096812781c844372bd175944aaf5 |
File details
Details for the file reparsec-0.3.1-py3-none-any.whl
.
File metadata
- Download URL: reparsec-0.3.1-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 | eba7d54cdea49cde7cb4fd80b7e4a32a9dc5b891c126851f58ed39dc9d3924c6 |
|
MD5 | fc313d1f43f6c737c51d18324d3c793a |
|
BLAKE2b-256 | e02d72b0629b745387f3c872fc33bb82fcd6ab6ee1ef2553232fbb4ad104f45a |