Parser
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)
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.4.0.tar.gz
(19.5 kB
view details)
Built Distribution
reparsec-0.4.0-py3-none-any.whl
(24.9 kB
view details)
File details
Details for the file reparsec-0.4.0.tar.gz
.
File metadata
- Download URL: reparsec-0.4.0.tar.gz
- Upload date:
- Size: 19.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.1.14 CPython/3.10.1 Windows/10
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 638be3846e49d5a0524deff73b866f38f3becc5233cdba77c02f10fc775e3274 |
|
MD5 | fb1ce04312648d54e14b6393a4b8758c |
|
BLAKE2b-256 | 559e04f137ab8dbf3cd808bdfc1b46e74dcafb97a50c2fdde74c7418dd97657e |
File details
Details for the file reparsec-0.4.0-py3-none-any.whl
.
File metadata
- Download URL: reparsec-0.4.0-py3-none-any.whl
- Upload date:
- Size: 24.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.1.14 CPython/3.10.1 Windows/10
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2f1884b53095ab22376bb9b7932aa1ca6f690bcd4a68cbc5b3f62a4190b3d4af |
|
MD5 | bd43e5768e6bbad282442e1f688f1f33 |
|
BLAKE2b-256 | 2663c7594e3cc571c1a44620f5401cc63504976aadbf31813da631ccdd52c8ae |