1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
use std::ops::RangeBounds;
use crate::leaf::trim_leading_whitespace_mut;
use crate::parse::Parser;
use crate::state::ParserState;
use crate::utils::extract_bounds;
use smallvec::SmallVec;
impl<'a, Output> Parser<'a, Output>
where
Self: 'a,
Output: 'a,
{
#[inline]
pub fn then<Output2>(self, next: Parser<'a, Output2>) -> Parser<'a, (Output, Output2)>
where
Output2: 'a,
{
let with = move |state: &mut ParserState<'a>| {
let value1 = self.call(state)?;
let value2 = next.call(state)?;
Some((value1, value2))
};
Parser::new(with)
}
/// Alternation with checkpoint-based backtracking (no Vec push/pop).
#[inline]
pub fn or(self, other: Parser<'a, Output>) -> Parser<'a, Output> {
let or = move |state: &mut ParserState<'a>| {
let checkpoint = state.offset;
if let Some(value) = self.call(state) {
return Some(value);
}
state.furthest_offset = state.furthest_offset.max(state.offset);
state.offset = checkpoint;
if let Some(value) = other.call(state) {
return Some(value);
}
state.furthest_offset = state.furthest_offset.max(state.offset);
state.offset = checkpoint;
None
};
Parser::new(or)
}
#[inline]
pub fn opt(self) -> Parser<'a, Option<Output>> {
let opt = move |state: &mut ParserState<'a>| {
if let Some(value) = self.call(state) {
return Some(Some(value));
}
Some(None)
};
Parser::new(opt)
}
/// Consuming negative lookahead: parse `self`, then check that `next` does
/// NOT match at the resulting position. If `next` matches, the overall
/// parse fails. Unlike `negate()` (zero-width), `not()` consumes the input
/// matched by `self` on success.
#[inline]
pub fn not<Output2>(self, next: Parser<'a, Output2>) -> Parser<'a, Output>
where
Output2: 'a,
{
let not = move |state: &mut ParserState<'a>| {
let value = self.call(state)?;
let checkpoint = state.offset;
let saved_furthest = state.furthest_offset;
if next.call(state).is_none() {
state.offset = checkpoint;
state.furthest_offset = saved_furthest;
return Some(value);
}
state.offset = checkpoint;
state.furthest_offset = saved_furthest;
None
};
Parser::new(not)
}
/// Set difference: match `self` only if `excluded` would NOT match at the
/// same starting position. Used for EBNF/BNF exception (`-`) semantics.
#[inline]
pub fn minus<Output2>(self, excluded: Parser<'a, Output2>) -> Parser<'a, Output>
where
Output2: 'a,
{
let minus = move |state: &mut ParserState<'a>| {
let checkpoint = state.offset;
let saved_furthest = state.furthest_offset;
if excluded.call(state).is_some() {
state.offset = checkpoint;
state.furthest_offset = saved_furthest;
return None;
}
state.offset = checkpoint;
state.furthest_offset = saved_furthest;
self.call(state)
};
Parser::new(minus)
}
/// Zero-width negative assertion: succeeds (returning `()`) when the inner
/// parser *fails*, and fails when the inner parser *succeeds*. Does not
/// consume any input in either case.
#[inline]
pub fn negate(self) -> Parser<'a, ()> {
let negate = move |state: &mut ParserState<'a>| {
let checkpoint = state.offset;
let saved_furthest = state.furthest_offset;
if self.call(state).is_none() {
state.offset = checkpoint;
state.furthest_offset = saved_furthest;
return Some(());
}
state.offset = checkpoint;
state.furthest_offset = saved_furthest;
None
};
Parser::new(negate)
}
/// Zero-width positive assertion: succeeds with the inner parser's value
/// when it matches, but does NOT consume any input. The dual of `negate()`:
/// where `negate()` succeeds when the inner parser fails, `peek()` succeeds
/// when the inner parser succeeds — both without advancing the offset.
#[inline]
pub fn peek(self) -> Parser<'a, Output> {
let peek = move |state: &mut ParserState<'a>| {
let checkpoint = state.offset;
let saved_furthest = state.furthest_offset;
let value = self.call(state)?;
state.offset = checkpoint;
state.furthest_offset = saved_furthest;
Some(value)
};
Parser::new(peek)
}
#[inline]
pub fn map<Output2>(self, f: fn(Output) -> Output2) -> Parser<'a, Output2>
where
Output2: 'a,
{
let map = move |state: &mut ParserState<'a>| self.call(state).map(f);
Parser::new(map)
}
#[inline]
pub fn map_with_state<Output2>(
self,
f: fn(Output, usize, &mut ParserState<'a>) -> Output2,
) -> Parser<'a, Output2>
where
Output2: 'a,
{
let map_with_state = move |state: &mut ParserState<'a>| {
let offset = state.offset;
let result = self.call(state)?;
Some(f(result, offset, state))
};
Parser::new(map_with_state)
}
#[inline]
pub fn skip<Output2>(self, next: Parser<'a, Output2>) -> Parser<'a, Output>
where
Output2: 'a,
{
let skip = move |state: &mut ParserState<'a>| {
let value = self.call(state)?;
next.call(state)?;
Some(value)
};
Parser::new(skip)
}
#[inline]
pub fn next<Output2>(self, next: Parser<'a, Output2>) -> Parser<'a, Output2>
where
Output2: 'a,
{
let next = move |state: &mut ParserState<'a>| {
self.call(state)?;
next.call(state)
};
Parser::new(next)
}
#[inline]
pub fn many(self, bounds: impl RangeBounds<usize> + 'a) -> Parser<'a, Vec<Output>> {
let (lower_bound, upper_bound) = extract_bounds(bounds);
let many = move |state: &mut ParserState<'a>| {
let est = if lower_bound > 0 {
lower_bound.max(4)
} else {
4
};
let mut values = Vec::with_capacity(est);
while values.len() < upper_bound {
let prev_offset = state.offset;
if let Some(value) = self.call(state) {
values.push(value);
// Guard: break on zero-length match to prevent infinite loops.
// Mirrors the VM interpreter's iter_start_offset check.
if state.offset == prev_offset {
break;
}
} else {
// Restore offset — the inner parser may have advanced past a
// partial match before failing (e.g., `binding.skip(comma)` where
// binding matched but comma didn't). Without this, subsequent
// parsers (like `.then(expression)`) see a wrong offset.
state.offset = prev_offset;
break;
}
}
if values.len() >= lower_bound {
Some(values)
} else {
None
}
};
Parser::new(many)
}
/// Like `many()` but returns `SmallVec<A>` — inline storage avoids heap
/// allocation for small collections.
#[inline]
pub fn many_small<A>(
self,
bounds: impl RangeBounds<usize> + 'a,
) -> Parser<'a, SmallVec<A>>
where
A: smallvec::Array<Item = Output> + 'a,
{
let (lower_bound, upper_bound) = extract_bounds(bounds);
let many = move |state: &mut ParserState<'a>| {
let mut values = SmallVec::new();
while values.len() < upper_bound {
let prev_offset = state.offset;
if let Some(value) = self.call(state) {
values.push(value);
if state.offset == prev_offset {
break;
}
} else {
state.offset = prev_offset;
break;
}
}
if values.len() >= lower_bound {
Some(values)
} else {
None
}
};
Parser::new(many)
}
/// Like `sep_by()` but returns `SmallVec<A>` — inline storage avoids heap
/// allocation for small collections.
#[inline]
pub fn sep_by_small<Output2, A>(
self,
sep: Parser<'a, Output2>,
bounds: impl RangeBounds<usize> + 'a,
) -> Parser<'a, SmallVec<A>>
where
Output2: 'a,
A: smallvec::Array<Item = Output> + 'a,
{
let (lower_bound, upper_bound) = extract_bounds(bounds);
let sep_by = move |state: &mut ParserState<'a>| {
let mut values = SmallVec::new();
// Parse first element
if let Some(value) = self.call(state) {
values.push(value);
} else if lower_bound == 0 {
return Some(values);
} else {
return None;
}
while values.len() < upper_bound {
let cp = state.offset;
if sep.call(state).is_none() {
state.offset = cp;
break;
}
if let Some(value) = self.call(state) {
values.push(value);
} else {
state.offset = cp;
break;
}
}
if values.len() >= lower_bound {
Some(values)
} else {
None
}
};
Parser::new(sep_by)
}
#[inline]
pub fn wrap<Output2, Output3>(
self,
left: Parser<'a, Output2>,
right: Parser<'a, Output3>,
) -> Parser<'a, Output>
where
Output2: 'a,
Output3: 'a,
{
let wrap = move |state: &mut ParserState<'a>| {
#[cfg(feature = "diagnostics")]
let open_offset = state.offset;
left.call(state)?;
#[cfg(feature = "diagnostics")]
let open_end = state.offset;
let value = self.call(state)?;
if right.call(state).is_some() {
Some(value)
} else {
#[cfg(feature = "diagnostics")]
{
let delimiter = state.src[open_offset..open_end].to_string();
state.add_suggestion(|| crate::state::Suggestion {
kind: crate::state::SuggestionKind::UnclosedDelimiter {
delimiter: delimiter.clone(),
open_offset,
},
message: format!(
"close the delimiter with matching `{}`",
match delimiter.as_str() {
"{" => "}",
"[" => "]",
"(" => ")",
d => d,
}
),
});
state.add_secondary_span(
open_offset,
format!("unclosed `{}` opened here", delimiter),
);
}
None
}
};
Parser::new(wrap)
}
#[inline]
pub fn trim<Output2>(self, trimmer: Parser<'a, Output2>) -> Parser<'a, Output>
where
Output2: 'a,
{
let trim = move |state: &mut ParserState<'a>| {
trimmer.call(state)?;
let value = self.call(state)?;
trimmer.call(state)?;
Some(value)
};
Parser::new(trim)
}
#[inline]
pub fn trim_keep<Output2>(
self,
trimmer: Parser<'a, Output2>,
) -> Parser<'a, (Output2, Output, Output2)>
where
Output2: 'a,
{
let trim = move |state: &mut ParserState<'a>| {
let trim1 = trimmer.call(state)?;
let value = self.call(state)?;
let trim2 = trimmer.call(state)?;
Some((trim1, value, trim2))
};
Parser::new(trim)
}
/// Strictly interleaving: `elem (sep elem)*`. Never accepts a trailing
/// separator — trailing sep acceptance is a grammar concern.
#[inline]
pub fn sep_by<Output2>(
self,
sep: Parser<'a, Output2>,
bounds: impl RangeBounds<usize> + 'a,
) -> Parser<'a, Vec<Output>>
where
Output2: 'a,
{
let (lower_bound, upper_bound) = extract_bounds(bounds);
let sep_by = move |state: &mut ParserState<'a>| {
let est = if lower_bound > 0 {
lower_bound.max(4)
} else {
4
};
let mut values = Vec::with_capacity(est);
// Parse first element
if let Some(value) = self.call(state) {
values.push(value);
} else if lower_bound == 0 {
return Some(values);
} else {
return None;
}
// Parse (sep elem)* — checkpoint before separator so trailing
// separators are rejected by restoring state.
while values.len() < upper_bound {
let cp = state.offset;
if sep.call(state).is_none() {
state.offset = cp;
break;
}
if let Some(value) = self.call(state) {
values.push(value);
} else {
// Element after separator failed — backtrack past the
// separator to reject the trailing separator.
state.offset = cp;
break;
}
}
if values.len() >= lower_bound {
Some(values)
} else {
None
}
};
Parser::new(sep_by)
}
/// Fused sep_by + whitespace trimming. Instead of wrapping element and
/// separator in trim_whitespace (which double-trims between elements),
/// this does a single trim between each step:
/// trim_ws → parse_element → (trim_ws → parse_sep → trim_ws → parse_element)*
#[inline]
pub fn sep_by_ws<Output2>(
self,
sep: Parser<'a, Output2>,
bounds: impl RangeBounds<usize> + 'a,
) -> Parser<'a, Vec<Output>>
where
Output2: 'a,
{
let (lower_bound, upper_bound) = extract_bounds(bounds);
let sep_by_ws = move |state: &mut ParserState<'a>| {
let mut values = Vec::with_capacity(4);
// Pre-trim before first element
trim_leading_whitespace_mut(state);
// Parse first element
if let Some(value) = self.call(state) {
values.push(value);
} else if lower_bound == 0 {
return Some(values);
} else {
return None;
}
while values.len() < upper_bound {
let cp = state.offset;
// Trim before separator — bypass sep's own flag dispatch
// since we're handling whitespace
trim_leading_whitespace_mut(state);
if sep.parser_fn.call(state).is_none() {
state.offset = cp;
break;
}
// Trim before next element
trim_leading_whitespace_mut(state);
if let Some(value) = self.call(state) {
values.push(value);
} else {
state.offset = cp;
break;
}
}
if values.len() >= lower_bound {
// Post-trim after the last element
trim_leading_whitespace_mut(state);
Some(values)
} else {
None
}
};
Parser::new(sep_by_ws)
}
/// Error recovery combinator. On success, returns the result normally.
/// On failure, snapshots the current diagnostic into the collected
/// diagnostics list, then runs `sync` to skip past the bad content
/// and returns `sentinel`.
///
/// This enables `many()` / `sep_by()` loops to keep going — each failed
/// element produces a diagnostic but doesn't halt the overall parse.
#[cfg(feature = "diagnostics")]
pub fn recover(self, sync: Parser<'a, ()>, sentinel: Output) -> Parser<'a, Output>
where
Output: Clone,
{
use crate::state::{pop_last_diagnostic, push_diagnostic};
let recover = move |state: &mut ParserState<'a>| {
let checkpoint = state.offset;
if let Some(value) = self.call(state) {
return Some(value);
}
// Snapshot diagnostic, then try to sync forward
let diag = state.snapshot_diagnostic(checkpoint);
push_diagnostic(diag);
state.offset = checkpoint;
if sync.call(state).is_some() {
// Sync succeeded — return sentinel
Some(sentinel.clone())
} else {
// Sync failed — pop the diagnostic and give up
pop_last_diagnostic();
state.offset = checkpoint;
None
}
};
Parser::new(recover)
}
/// No-op version without diagnostics feature — just runs the inner parser.
#[cfg(not(feature = "diagnostics"))]
pub fn recover(self, _sync: Parser<'a, ()>, _sentinel: Output) -> Parser<'a, Output>
where
Output: Clone,
{
panic!("recover() requires the `diagnostics` feature")
}
/// Monadic bind (flatMap): parse with `self`, then use the result to choose
/// the next parser via `f`. The second parser runs from where `self` left off.
///
/// This enables context-sensitive parsing where the choice of continuation
/// depends on the value parsed so far.
#[inline]
pub fn chain<Output2, F>(self, f: F) -> Parser<'a, Output2>
where
Output2: 'a,
F: Fn(Output) -> Parser<'a, Output2> + 'a,
{
let chain = move |state: &mut ParserState<'a>| {
let value = self.call(state)?;
let next = f(value);
next.call(state)
};
Parser::new(chain)
}
#[inline]
pub fn look_ahead<Output2>(self, parser: Parser<'a, Output2>) -> Parser<'a, Output>
where
Output2: 'a,
{
let look_ahead = move |state: &mut ParserState<'a>| {
let value = self.call(state)?;
let offset_after_self = state.offset;
let lookahead_result = parser.call(state);
state.offset = offset_after_self;
lookahead_result?;
Some(value)
};
Parser::new(look_ahead)
}
/// Packrat memoization: cache parse results by input offset.
/// On cache hit, restores offset and returns cloned value in O(1).
/// Eliminates exponential re-parsing in ambiguous/cyclic grammars.
pub fn memoize(self) -> Parser<'a, Output>
where
Output: Clone,
{
use std::cell::RefCell;
use std::collections::HashMap;
// Cache: offset → None (failed) | Some((end_offset, value))
let cache: RefCell<HashMap<usize, Option<(usize, Output)>>> =
RefCell::new(HashMap::new());
let memo = move |state: &mut ParserState<'a>| {
let key = state.offset;
// Fast path: check cache without mutation
if let Some(entry) = cache.borrow().get(&key) {
return match entry {
Some((end_offset, value)) => {
state.offset = *end_offset;
Some(value.clone())
}
None => None,
};
}
// Cache miss: parse and store result
let result = self.call(state);
let entry = result.as_ref().map(|v| (state.offset, v.clone()));
cache.borrow_mut().insert(key, entry);
result
};
Parser::new(memo)
}
}
impl<'a, Output2> std::ops::BitOr<Parser<'a, Output2>> for Parser<'a, Output2>
where
Output2: 'a,
{
type Output = Parser<'a, Output2>;
#[inline]
fn bitor(self, other: Parser<'a, Output2>) -> Self::Output {
self.or(other)
}
}
impl<'a, Output, Output2> std::ops::Add<Parser<'a, Output2>> for Parser<'a, Output>
where
Output: 'a,
Output2: 'a,
{
type Output = Parser<'a, (Output, Output2)>;
#[inline]
fn add(self, other: Parser<'a, Output2>) -> Self::Output {
self.then(other)
}
}
#[path = "../span_trait.rs"]
mod span_trait;
pub use span_trait::*;