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.5.tar.gz
(20.4 kB
view details)
Built Distribution
reparsec-0.3.5-py3-none-any.whl
(25.5 kB
view details)
File details
Details for the file reparsec-0.3.5.tar.gz
.
File metadata
- Download URL: reparsec-0.3.5.tar.gz
- Upload date:
- Size: 20.4 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 | 9d08ae99c9a8db4f3673e0b153c7656634dd996f1b53d6360f9e6db155ec9070 |
|
MD5 | 244e5646c7183b2459f072ee7aeb4f53 |
|
BLAKE2b-256 | e593cbccd5e607eefddbeaeef71be8d0b0cb0cd2e9ca63804f121517010cbb81 |
File details
Details for the file reparsec-0.3.5-py3-none-any.whl
.
File metadata
- Download URL: reparsec-0.3.5-py3-none-any.whl
- Upload date:
- Size: 25.5 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 | ac798c4dc6be53ebf1cf3e7a455d3f6377955b551384cd8315bdf4db7ca5f0f9 |
|
MD5 | 69254e32d23174b8ec1e6a0d3a562f43 |
|
BLAKE2b-256 | 07ab4fb173b23a2f2b1082cb6e088f0d36c151e3bf1bcf6dfa32cf4298b8da87 |