parse_that 0.3.0

Zero-copy parser combinator library for Rust
Documentation
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
use regex::Regex;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};

use crate::parse::Parser;
use crate::state::{ParserState, Span};

use aho_corasick::{AhoCorasickBuilder, Anchored, Input, MatchKind, StartKind};

/// Global regex cache — avoids recompiling the same pattern on repeated parser construction.
pub fn cached_regex(pattern: &str) -> Arc<Regex> {
    static CACHE: OnceLock<Mutex<HashMap<String, Arc<Regex>>>> = OnceLock::new();
    let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
    let mut map = cache.lock().unwrap();
    if let Some(re) = map.get(pattern) {
        return Arc::clone(re);
    }
    let re = Arc::new(
        Regex::new(pattern).unwrap_or_else(|_| panic!("Failed to compile regex: {}", pattern)),
    );
    map.insert(pattern.to_owned(), Arc::clone(&re));
    re
}

#[inline(always)]
pub fn trim_leading_whitespace(state: &ParserState<'_>) -> usize {
    let bytes = state.src_bytes;
    let mut i = state.offset;
    let end = bytes.len();

    // Fast path: first byte is not whitespace (most common case)
    if i >= end || !matches!(unsafe { *bytes.get_unchecked(i) }, b' ' | b'\t' | b'\n' | b'\r') {
        return 0;
    }

    i += 1; // we know the first byte is whitespace

    // SIMD: process 16 bytes at a time for longer spans
    {
        use std::simd::prelude::*;
        while i + 16 <= end {
            let chunk = u8x16::from_slice(&bytes[i..i + 16]);
            let mask = chunk.simd_eq(u8x16::splat(b' '))
                | chunk.simd_eq(u8x16::splat(b'\t'))
                | chunk.simd_eq(u8x16::splat(b'\n'))
                | chunk.simd_eq(u8x16::splat(b'\r'));
            if mask.all() {
                i += 16;
                continue;
            }
            let first_non_ws = (!mask).to_bitmask().trailing_zeros() as usize;
            return i + first_non_ws - state.offset;
        }
    }

    // Scalar tail
    while i < end {
        match unsafe { *bytes.get_unchecked(i) } {
            b' ' | b'\t' | b'\n' | b'\r' => i += 1,
            _ => break,
        }
    }
    i - state.offset
}

/// Convenience: skip leading whitespace, advancing the state offset.
#[inline(always)]
pub fn trim_leading_whitespace_mut(state: &mut ParserState<'_>) {
    let n = trim_leading_whitespace(state);
    state.offset += n;
}

#[inline]
pub fn epsilon<'a>() -> Parser<'a, ()> {
    let epsilon = move |_: &mut ParserState<'a>| Some(());
    Parser::new(epsilon)
}

#[inline(always)]
pub fn string_impl<'a>(
    s_bytes: &[u8],
    end: &usize,
    state: &mut ParserState<'a>,
) -> Option<Span<'a>> {
    if *end == 0 {
        return Some(Span::new(state.offset, state.offset, state.src));
    }

    let Some(slc) = &state.src_bytes.get(state.offset..) else {
        return None;
    };
    if slc.len() >= *end && slc[0] == s_bytes[0] && slc[1..*end].starts_with(&s_bytes[1..]) {
        let start = state.offset;
        state.offset += end;

        Some(Span::new(start, state.offset, state.src))
    } else {
        None
    }
}

#[inline(always)]
#[allow(clippy::manual_map)]
pub fn string<'a>(s: &'a str) -> Parser<'a, &'a str> {
    let s_bytes = s.as_bytes();
    let end = s_bytes.len();
    #[cfg(feature = "diagnostics")]
    let label: &'static str = Box::leak(format!("\"{}\"", s).into_boxed_str());
    let string = move |state: &mut ParserState<'a>| match string_impl(s_bytes, &end, state) {
        Some(span) => Some(span.as_str()),
        None => {
            #[cfg(feature = "diagnostics")]
            state.add_expected(label);
            None
        }
    };
    Parser::new(string)
}

#[inline(always)]
#[allow(clippy::manual_map)]
pub fn string_span<'a>(s: &'a str) -> Parser<'a, Span<'a>> {
    let s_bytes = s.as_bytes();
    let end = s_bytes.len();
    #[cfg(feature = "diagnostics")]
    let label: &'static str = Box::leak(format!("\"{}\"", s).into_boxed_str());
    let string = move |state: &mut ParserState<'a>| match string_impl(s_bytes, &end, state) {
        Some(span) => Some(span),
        None => {
            #[cfg(feature = "diagnostics")]
            state.add_expected(label);
            None
        }
    };
    Parser::new(string)
}

#[inline(always)]
fn regex_impl<'a>(re: &Regex, state: &mut ParserState<'a>) -> Option<Span<'a>> {
    if state.is_at_end() {
        return None;
    }
    let slc = state.src.get(state.offset..)?;
    match re.find_at(slc, 0) {
        Some(m) => {
            if m.start() != 0 {
                return None;
            }
            let start = state.offset;
            state.offset += m.end();
            Some(Span::new(start, state.offset, state.src))
        }
        None => None,
    }
}

#[inline(always)]
#[allow(clippy::manual_map)]
pub fn regex<'a>(r: &'a str) -> Parser<'a, &'a str> {
    let re = cached_regex(r);
    #[cfg(feature = "diagnostics")]
    let label: &'static str = Box::leak(format!("/{}/", r).into_boxed_str());
    let regex = move |state: &mut ParserState<'a>| match regex_impl(&re, state) {
        Some(span) => Some(span.as_str()),
        None => {
            #[cfg(feature = "diagnostics")]
            state.add_expected(label);
            None
        }
    };
    Parser::new(regex)
}

#[inline(always)]
#[allow(clippy::manual_map)]
pub fn regex_span<'a>(r: &'a str) -> Parser<'a, Span<'a>> {
    let re = cached_regex(r);
    #[cfg(feature = "diagnostics")]
    let label: &'static str = Box::leak(format!("/{}/", r).into_boxed_str());
    let regex = move |state: &mut ParserState<'a>| match regex_impl(&re, state) {
        Some(span) => Some(span),
        None => {
            #[cfg(feature = "diagnostics")]
            state.add_expected(label);
            None
        }
    };
    Parser::new(regex)
}

#[inline]
pub fn take_while_span<'a, F>(f: F) -> Parser<'a, Span<'a>>
where
    F: Fn(char) -> bool + 'a,
{
    let take_while = move |state: &mut ParserState<'a>| {
        let slc = state.src.get(state.offset..)?;
        let mut len = slc
            .char_indices()
            .take_while(|(_, c)| f(*c))
            .map(|(i, _)| i)
            .last();

        match len {
            Some(ref mut l) => {
                *l += 1;
                while *l < slc.len() && !slc.is_char_boundary(*l) {
                    *l += 1;
                }
                let start = state.offset;
                state.offset += *l;
                Some(Span::new(start, state.offset, state.src))
            }
            None => {
                #[cfg(feature = "diagnostics")]
                state.add_expected("matching character");
                None
            }
        }
    };

    Parser::new(take_while)
}

/// Fast byte-level take_while — for ASCII predicates only.
#[inline]
pub fn take_while_byte_span<'a>(f: fn(u8) -> bool) -> Parser<'a, Span<'a>> {
    let take_while = move |state: &mut ParserState<'a>| {
        let bytes = state.src_bytes;
        let start = state.offset;
        let end = bytes.len();
        let mut i = start;
        while i < end && f(unsafe { *bytes.get_unchecked(i) }) {
            i += 1;
        }
        if i == start {
            #[cfg(feature = "diagnostics")]
            state.add_expected("matching byte");
            return None;
        }
        state.offset = i;
        Some(Span::new(start, i, state.src))
    };
    Parser::new(take_while)
}

/// Match one or more bytes until any byte in `excluded` is found.
/// Uses a 256-byte LUT for branch-free scanning—10-15x faster than regex for
/// negated character classes like `/[^;{}!,]+/`.
#[inline]
pub fn take_until_any_span<'a>(excluded: &'static [u8]) -> Parser<'a, Span<'a>> {
    enum TakeUntilScan {
        One(u8),
        Two(u8, u8),
        Three(u8, u8, u8),
        Lut(Box<[bool; 256]>),
    }

    let mut lut = [false; 256];
    let mut unique = [0u8; 3];
    let mut unique_count = 0usize;
    let mut overflow = false;
    for &b in excluded {
        let idx = b as usize;
        if lut[idx] {
            continue;
        }
        lut[idx] = true;
        if unique_count < 3 {
            unique[unique_count] = b;
            unique_count += 1;
        } else {
            overflow = true;
        }
    }
    let scan = if overflow {
        TakeUntilScan::Lut(Box::new(lut))
    } else {
        match unique_count {
            1 => TakeUntilScan::One(unique[0]),
            2 => TakeUntilScan::Two(unique[0], unique[1]),
            3 => TakeUntilScan::Three(unique[0], unique[1], unique[2]),
            _ => TakeUntilScan::Lut(Box::new(lut)),
        }
    };
    #[cfg(feature = "diagnostics")]
    let label: &'static str = {
        let chars: String = excluded.iter().map(|&b| b as char).collect();
        Box::leak(format!("any byte not in [{}]", chars).into_boxed_str())
    };
    let take_until = move |state: &mut ParserState<'a>| {
        let bytes = state.src_bytes;
        let start = state.offset;
        if start >= bytes.len() {
            #[cfg(feature = "diagnostics")]
            state.add_expected(label);
            return None;
        }
        let scan_len = match &scan {
            TakeUntilScan::One(b1) => {
                memchr::memchr(*b1, &bytes[start..]).unwrap_or(bytes.len() - start)
            }
            TakeUntilScan::Two(b1, b2) => {
                memchr::memchr2(*b1, *b2, &bytes[start..]).unwrap_or(bytes.len() - start)
            }
            TakeUntilScan::Three(b1, b2, b3) => {
                memchr::memchr3(*b1, *b2, *b3, &bytes[start..]).unwrap_or(bytes.len() - start)
            }
            TakeUntilScan::Lut(lut) => {
                let mut i = start;
                let end = bytes.len();
                while i < end && !lut[unsafe { *bytes.get_unchecked(i) } as usize] {
                    i += 1;
                }
                i - start
            }
        };
        if scan_len == 0 {
            #[cfg(feature = "diagnostics")]
            state.add_expected(label);
            return None;
        }
        let end = start + scan_len;
        state.offset = end;
        Some(Span::new(start, end, state.src))
    };
    Parser::new(take_until)
}

#[inline]
pub fn next_span<'a>(amount: usize) -> Parser<'a, Span<'a>> {
    let next = move |state: &mut ParserState<'a>| {
        let start = state.offset;
        let new_offset = start + amount;
        if new_offset > state.src.len() {
            return None;
        }
        state.offset = new_offset;
        Some(Span::new(start, new_offset, state.src))
    };
    Parser::new(next)
}

pub fn any_span<'a>(patterns: &[&'a str]) -> Parser<'a, Span<'a>> {
    let ac = AhoCorasickBuilder::new()
        .match_kind(MatchKind::LeftmostFirst)
        .start_kind(StartKind::Anchored)
        .build(patterns)
        .expect("failed to build aho-corasick automaton");
    #[cfg(feature = "diagnostics")]
    let label: &'static str = Box::leak(format!("one of {:?}", patterns).into_boxed_str());

    let any = move |state: &mut ParserState<'a>| {
        let slc = state.src.get(state.offset..)?;
        let input = Input::new(slc).anchored(Anchored::Yes);
        match ac.find(input) {
            Some(m) => {
                let start = state.offset;
                state.offset += m.end();
                Some(Span::new(start, state.offset, state.src))
            }
            None => {
                #[cfg(feature = "diagnostics")]
                state.add_expected(label);
                None
            }
        }
    };

    Parser::new(any)
}

// ── one_of: flat N-way alternation ────────────────────────────

/// Flat N-way alternation — tries each parser in order with checkpoint backtracking.
pub fn one_of<'a, O: 'a>(parsers: Vec<Parser<'a, O>>) -> Parser<'a, O> {
    Parser::new(move |state: &mut ParserState<'a>| {
        for parser in &parsers {
            let checkpoint = state.offset;
            if let Some(value) = parser.call(state) {
                return Some(value);
            }
            state.furthest_offset = state.furthest_offset.max(state.offset);
            state.offset = checkpoint;
        }
        None
    })
}

// ── dispatch_byte: first-byte lookup table ────────────────────

/// First-byte dispatch — O(1) branch selection by peeking the next byte.
pub fn dispatch_byte<'a, O: 'a>(table: Vec<(u8, Parser<'a, O>)>) -> Parser<'a, O> {
    // Build lookup table: byte → index into table
    let mut lut: [Option<u16>; 256] = [None; 256];
    for (i, (byte, _)) in table.iter().enumerate() {
        lut[*byte as usize] = Some(i as u16);
    }
    #[cfg(feature = "diagnostics")]
    let label: &'static str = {
        let chars: Vec<char> = table.iter().map(|(b, _)| *b as char).collect();
        Box::leak(format!("one of {:?}", chars).into_boxed_str())
    };
    Parser::new(move |state: &mut ParserState<'a>| {
        let byte = *state.src_bytes.get(state.offset)?;
        if let Some(idx) = lut[byte as usize] {
            table[idx as usize].1.call(state)
        } else {
            #[cfg(feature = "diagnostics")]
            state.add_expected(label);
            None
        }
    })
}

/// First-byte dispatch with multiple bytes mapping to the same parser.
/// Avoids duplicating parsers for bytes that share the same handler (e.g., digits 0-9).
pub fn dispatch_byte_multi<'a, O: 'a>(table: Vec<(&[u8], Parser<'a, O>)>) -> Parser<'a, O> {
    // Build lookup table: byte → index into parsers vec
    let mut lut: [Option<u16>; 256] = [None; 256];
    let mut parsers: Vec<Parser<'a, O>> = Vec::with_capacity(table.len());
    #[cfg(feature = "diagnostics")]
    let mut all_bytes: Vec<u8> = Vec::new();
    for (bytes, parser) in table {
        let idx = parsers.len() as u16;
        parsers.push(parser);
        for &byte in bytes {
            lut[byte as usize] = Some(idx);
            #[cfg(feature = "diagnostics")]
            all_bytes.push(byte);
        }
    }
    #[cfg(feature = "diagnostics")]
    let label: &'static str = {
        let chars: Vec<char> = all_bytes.iter().map(|b| *b as char).collect();
        Box::leak(format!("one of {:?}", chars).into_boxed_str())
    };
    Parser::new(move |state: &mut ParserState<'a>| {
        let byte = *state.src_bytes.get(state.offset)?;
        if let Some(idx) = lut[byte as usize] {
            parsers[idx as usize].call(state)
        } else {
            #[cfg(feature = "diagnostics")]
            state.add_expected(label);
            None
        }
    })
}