0
# Parsec
1
2
A universal Python parser combinator library inspired by Haskell's Parsec library. It enables developers to build complex parsers by combining simple parsing primitives using monadic operations and functional composition. The library provides a rich set of parsing combinators, advanced error handling with detailed location information, and supports both imperative and declarative parser construction patterns.
3
4
## Package Information
5
6
- **Package Name**: parsec
7
- **Language**: Python
8
- **Installation**: `pip install parsec`
9
10
## Core Imports
11
12
```python
13
from parsec import *
14
```
15
16
Common selective imports:
17
18
```python
19
from parsec import Parser, string, many, letter, digit, regex, generate
20
```
21
22
## Basic Usage
23
24
```python
25
from parsec import *
26
27
# Simple string parser
28
hello_parser = string("hello")
29
result = hello_parser.parse("hello world") # Returns "hello"
30
31
# Combining parsers with operators
32
# Parse "hello" followed by space(s) and "world"
33
greeting_parser = string("hello") >> spaces >> string("world")
34
result = greeting_parser.parse("hello world") # Returns "world"
35
36
# Using many combinator to parse repeated elements
37
letters_parser = many(letter())
38
result = letters_parser.parse("abc123") # Returns ['a', 'b', 'c']
39
40
# Parser generator approach for complex parsing
41
@generate
42
def number_list():
43
nums = yield many(digit())
44
yield string(",")
45
return int("".join(nums))
46
47
result = number_list.parse("123,") # Returns 123
48
```
49
50
## Architecture
51
52
Parsec follows functional programming principles with monadic parser combinators:
53
54
- **Parser**: Core class wrapping parsing functions that operate on text and return Value objects
55
- **Value**: Result container with success/failure status, consumed position, and parsed value
56
- **ParseError**: Detailed error reporting with source location information
57
- **Combinators**: Higher-order functions that combine simple parsers into complex ones
58
- **Generator decorators**: Python-native syntax for building complex parsers using yield
59
60
This design enables compositional parsing where complex grammar rules are built by combining simple, reusable parser components.
61
62
## Capabilities
63
64
### Core Parsing Primitives
65
66
The fundamental classes and types that form the foundation of all parsing operations, including the main Parser class, result handling with Value objects, and comprehensive error reporting.
67
68
```python { .api }
69
class Parser:
70
def __init__(self, fn): ...
71
def parse(self, text): ...
72
def parse_partial(self, text): ...
73
def parse_strict(self, text): ...
74
75
class Value:
76
@staticmethod
77
def success(index, actual): ...
78
@staticmethod
79
def failure(index, expected): ...
80
81
class ParseError(RuntimeError):
82
def __init__(self, expected, text, index): ...
83
```
84
85
[Core Primitives](./core-primitives.md)
86
87
### Parser Combinators
88
89
Higher-order functions for combining and repeating parsers, including repetition operators (many, times, count) and composition utilities that enable building complex parsers from simple building blocks.
90
91
```python { .api }
92
def times(p, mint, maxt=None): ...
93
def count(p, n): ...
94
def many(p): ...
95
def many1(p): ...
96
```
97
98
[Combinators](./combinators.md)
99
100
### Character and String Parsing
101
102
Specialized parsers for character-level and string-level text processing, including literal string matching, regular expression support, character class matching, and whitespace handling.
103
104
```python { .api }
105
def string(s): ...
106
def regex(exp, flags=0): ...
107
def one_of(s): ...
108
def none_of(s): ...
109
def letter(): ...
110
def digit(): ...
111
def space(): ...
112
def spaces(): ...
113
def eof(): ...
114
```
115
116
[Character Parsing](./character-parsing.md)
117
118
### Parser Operators
119
120
Monadic and compositional operators for sequencing, choice, transformation, and control flow between parsers. These operators enable both infix notation and functional composition patterns.
121
122
```python { .api }
123
# Parser class methods for operators
124
def bind(self, fn): ... # >>=
125
def compose(self, other): ... # >>
126
def choice(self, other): ... # |
127
def try_choice(self, other): ... # ^
128
def joint(self, other): ... # +
129
def parsecmap(self, fn): ...
130
```
131
132
[Parser Operators](./parser-operators.md)
133
134
### Parser Generation
135
136
Powerful declarative syntax using Python generators to build complex parsers with natural control flow, variable binding, and conditional logic while maintaining the functional parser combinator foundation.
137
138
```python { .api }
139
def generate(fn): ...
140
141
# Usage pattern:
142
@generate
143
def my_parser():
144
result1 = yield parser1
145
result2 = yield parser2
146
return combine(result1, result2)
147
```
148
149
[Parser Generation](./parser-generation.md)
150
151
## Types
152
153
```python { .api }
154
class ParseError(RuntimeError):
155
"""Parser error with location information."""
156
expected: str
157
text: str
158
index: int
159
160
def loc(self) -> str: ...
161
@staticmethod
162
def loc_info(text: str, index: int) -> tuple[int, int]: ...
163
164
class Value:
165
"""Parser result container."""
166
status: bool
167
index: int
168
value: any
169
expected: str
170
171
def aggregate(self, other) -> Value: ...
172
173
class Parser:
174
"""Core parser combinator class."""
175
def __call__(self, text: str, index: int) -> Value: ...
176
```