0
# Core Parser Construction
1
2
Fundamental parser creation and execution functionality. These are the building blocks for all parsing operations in Parsimmon.
3
4
## Capabilities
5
6
### Parsimmon Constructor
7
8
Creates a parser from a parsing function. This is the fundamental building block for all parsers.
9
10
```javascript { .api }
11
/**
12
* Creates a parser from a parsing function
13
* @param {Function} action - Function that takes (input, index) and returns parse result
14
* @returns {Parser} A new parser instance
15
*/
16
function Parsimmon(action);
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
// Custom parser that matches a specific word
23
const hello = Parsimmon(function(input, i) {
24
const target = "hello";
25
if (input.slice(i, i + target.length) === target) {
26
return Parsimmon.makeSuccess(i + target.length, target);
27
}
28
return Parsimmon.makeFailure(i, `'${target}'`);
29
});
30
```
31
32
### String Parser
33
34
Parses an exact string match. Case-sensitive.
35
36
```javascript { .api }
37
/**
38
* Creates a parser that matches an exact string
39
* @param {string} str - The string to match
40
* @returns {Parser} Parser that succeeds when input matches str
41
*/
42
Parsimmon.string(str);
43
```
44
45
**Usage Examples:**
46
47
```javascript
48
const hello = Parsimmon.string("hello");
49
hello.parse("hello"); // { status: true, value: "hello" }
50
hello.parse("Hello"); // { status: false, ... }
51
52
// Case insensitive matching using regexp
53
const caseInsensitiveHello = Parsimmon.regexp(/hello/i);
54
```
55
56
### Regular Expression Parser
57
58
Creates a parser from a regular expression pattern.
59
60
```javascript { .api }
61
/**
62
* Creates a parser that matches a regular expression
63
* @param {RegExp} re - Regular expression to match
64
* @param {number} [group=0] - Capture group to return (default: 0 for full match)
65
* @returns {Parser} Parser that succeeds when regex matches
66
*/
67
Parsimmon.regexp(re, group);
68
69
// Alias for regexp
70
Parsimmon.regex(re, group);
71
```
72
73
**Usage Examples:**
74
75
```javascript
76
// Match digits
77
const digits = Parsimmon.regexp(/[0-9]+/);
78
digits.parse("123"); // { status: true, value: "123" }
79
80
// Extract capture groups
81
const wordAndNumber = Parsimmon.regexp(/([a-z]+)([0-9]+)/, 1);
82
wordAndNumber.parse("abc123"); // { status: true, value: "abc" }
83
84
// Full match with all groups
85
const fullMatch = Parsimmon.regexp(/([a-z]+)([0-9]+)/);
86
fullMatch.parse("abc123"); // { status: true, value: "abc123" }
87
```
88
89
### Success Parser
90
91
Always succeeds with a given value, consuming no input.
92
93
```javascript { .api }
94
/**
95
* Creates a parser that always succeeds with the given value
96
* @param {any} value - Value to return on success
97
* @returns {Parser} Parser that always succeeds
98
*/
99
Parsimmon.succeed(value);
100
101
// Alias for succeed
102
Parsimmon.of(value);
103
```
104
105
**Usage Examples:**
106
107
```javascript
108
const alwaysTrue = Parsimmon.succeed(true);
109
alwaysTrue.parse("anything"); // { status: true, value: true }
110
111
// Useful for providing default values
112
const optionalName = Parsimmon.string("name").fallback("anonymous");
113
```
114
115
### Failure Parser
116
117
Always fails with a given error message.
118
119
```javascript { .api }
120
/**
121
* Creates a parser that always fails
122
* @param {string} message - Error message for the failure
123
* @returns {Parser} Parser that always fails
124
*/
125
Parsimmon.fail(message);
126
```
127
128
**Usage Examples:**
129
130
```javascript
131
const alwaysFails = Parsimmon.fail("This always fails");
132
alwaysFails.parse("anything"); // { status: false, expected: ["This always fails"] }
133
134
// Useful for conditional parsing
135
const validator = Parsimmon.regexp(/[0-9]+/).chain(function(numStr) {
136
const num = parseInt(numStr);
137
return num > 0 ? Parsimmon.succeed(num) : Parsimmon.fail("positive number");
138
});
139
```
140
141
### Custom Parser
142
143
Creates a parser using a custom parsing function with access to success/failure constructors.
144
145
```javascript { .api }
146
/**
147
* Creates a custom parser with access to success/failure constructors
148
* @param {Function} fn - Function receiving (succeed, fail) => (input, i) => result
149
* @returns {Parser} Custom parser
150
*/
151
Parsimmon.custom(fn);
152
```
153
154
**Usage Examples:**
155
156
```javascript
157
// Custom parser for balanced parentheses
158
const balanced = Parsimmon.custom(function(succeed, fail) {
159
return function(input, i) {
160
let depth = 0;
161
let j = i;
162
163
while (j < input.length) {
164
if (input[j] === "(") depth++;
165
else if (input[j] === ")") depth--;
166
else if (depth === 0) break;
167
j++;
168
}
169
170
if (depth === 0 && j > i) {
171
return succeed(j, input.slice(i, j));
172
}
173
return fail(i, "balanced parentheses");
174
};
175
});
176
```
177
178
### Parser Execution Methods
179
180
Methods for executing parsers on input strings.
181
182
```javascript { .api }
183
/**
184
* Parses input and returns detailed result object
185
* @param {string|Buffer} input - Input to parse
186
* @returns {ParseResult} Result with status, value, and error information
187
*/
188
parser.parse(input);
189
190
/**
191
* Parses input and returns value or throws error
192
* @param {string|Buffer} input - Input to parse
193
* @returns {any} Parsed value
194
* @throws {Error} Formatted parsing error
195
*/
196
parser.tryParse(input);
197
```
198
199
**Usage Examples:**
200
201
```javascript
202
const number = Parsimmon.regexp(/[0-9]+/).map(Number);
203
204
// Using parse() - returns result object
205
const result = number.parse("42");
206
if (result.status) {
207
console.log("Success:", result.value); // Success: 42
208
} else {
209
console.log("Error:", result.expected);
210
}
211
212
// Using tryParse() - throws on error
213
try {
214
const value = number.tryParse("42");
215
console.log("Success:", value); // Success: 42
216
} catch (err) {
217
console.log("Error:", err.message);
218
}
219
```
220
221
### Utility Functions
222
223
Helper functions for working with parse results.
224
225
```javascript { .api }
226
/**
227
* Check if an object is a parser
228
* @param {any} obj - Object to test
229
* @returns {boolean} True if obj is a parser
230
*/
231
Parsimmon.isParser(obj);
232
233
/**
234
* Create a success result object
235
* @param {number} index - Position after successful parse
236
* @param {any} value - Parsed value
237
* @returns {ParseResult} Success result
238
*/
239
Parsimmon.makeSuccess(index, value);
240
241
/**
242
* Create a failure result object
243
* @param {number} index - Position where parsing failed
244
* @param {string|string[]} expected - Expected input description
245
* @returns {ParseResult} Failure result
246
*/
247
Parsimmon.makeFailure(index, expected);
248
249
/**
250
* Format a parse error for display
251
* @param {string} input - Original input
252
* @param {ParseResult} error - Error result from parse()
253
* @returns {string} Formatted error message
254
*/
255
Parsimmon.formatError(input, error);
256
```
257
258
**Usage Examples:**
259
260
```javascript
261
// Check if something is a parser
262
const isParser = Parsimmon.isParser(Parsimmon.string("test")); // true
263
const notParser = Parsimmon.isParser("test"); // false
264
265
// Format errors nicely
266
const parser = Parsimmon.string("hello");
267
const result = parser.parse("hi there");
268
if (!result.status) {
269
const errorMsg = Parsimmon.formatError("hi there", result);
270
console.log(errorMsg); // Shows formatted error with position
271
}
272
```