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.4.tar.gz
(20.2 kB
view details)
Built Distribution
reparsec-0.3.4-py3-none-any.whl
(25.5 kB
view details)
File details
Details for the file reparsec-0.3.4.tar.gz
.
File metadata
- Download URL: reparsec-0.3.4.tar.gz
- Upload date:
- Size: 20.2 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 | a78de2d652956798817748e012dff65ca87701b9a05491c4840439fefa62c8fd |
|
MD5 | be9bae27ec570f9b99963dbea7aa5c3c |
|
BLAKE2b-256 | 9cd6bbe4f81ee2158c0b007a3cd0caac350ff7b716038c7058faaacab66e0815 |
File details
Details for the file reparsec-0.3.4-py3-none-any.whl
.
File metadata
- Download URL: reparsec-0.3.4-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 | 5488663f20109c7548ea10c176415e1508ad15bff10dc8a306d3b189d3d88e4f |
|
MD5 | ad88f1ba1b483b104bf5cfd26461deaa |
|
BLAKE2b-256 | fcdbb60fec62b68bd9edd0e4078874483297c04dd3745e5cdd1507d81368e898 |