neure 0.10.1

A fast little combinational parsing library
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
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
use core::str::CharIndices;

use super::Context;
use super::PolicyCtx;
use super::PolicyMatch;
use super::Regex;
use super::Span;

use crate::ctx::Match;
use crate::err::Error;
use crate::iter::BytesIndices;
use crate::iter::IndexBySpan;

/// A context implementation that holds a reference to data and tracks an offset.
///
/// [`RegexCtx`] is a lightweight, zero-cost wrapper around a reference to data (typically
/// a byte slice or string) with an associated offset. It is the primary concrete
/// implementation of the [`Context`] trait used for pattern matching and parsing.
#[derive(Debug)]
pub struct RegexCtx<'a, T>
where
    T: ?Sized,
{
    dat: &'a T,
    offset: usize,
}

impl<T> Clone for RegexCtx<'_, T>
where
    T: ?Sized,
{
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for RegexCtx<'_, T> where T: ?Sized {}

impl<'a, T> RegexCtx<'a, T>
where
    T: ?Sized,
{
    /// Creates a new [`RegexCtx`] with the given data and offset set to 0.
    pub const fn new(dat: &'a T) -> Self {
        Self { dat, offset: 0 }
    }

    /// Returns a reference to the underlying data.
    pub const fn dat(&self) -> &'a T {
        self.dat
    }

    /// Returns the current offset.
    pub const fn offset(&self) -> usize {
        self.offset
    }

    /// Replaces the underlying data with a new reference, keeping the offset unchanged.
    pub fn with_dat(mut self, dat: &'a T) -> Self {
        self.dat = dat;
        self
    }

    /// Sets a new offset value, returning a new context with the same data.
    pub fn with_offset(mut self, offset: usize) -> Self {
        self.offset = offset;
        self
    }

    /// Resets the context with new data and sets offset to 0.
    pub fn reset_with(&mut self, dat: &'a T) -> &mut Self {
        self.dat = dat;
        self.offset = 0;
        self
    }

    /// Resets the offset to 0 without changing the data.
    pub fn reset(&mut self) -> &mut Self {
        self.offset = 0;
        self
    }

    /// Creates a span storer with the specified capacity (requires `alloc` feature).
    #[cfg(feature = "alloc")]
    pub fn span_storer(&self, capacity: usize) -> crate::span::VecStorer {
        crate::span::VecStorer::new(capacity)
    }

    /// Creates a temporary context and passes it to a closure.
    ///
    /// This is a convenience method that creates a new `RegexCtx` with offset 0
    /// and immediately passes it to the provided closure. It's useful for
    /// creating scoped parsing operations without explicitly managing the context.
    ///
    /// # Example
    ///
    /// ```
    /// # use neure::prelude::*;
    /// #
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let year = RegexCtx::with("rust2026", |mut ctx| {
    ///         let parser = neu::digit(10).many1().prefix("rust");
    ///         let parser = parser.try_map(map::from_str::<i32>());
    ///
    ///         ctx.ctor(&parser)
    ///     })?;
    ///
    ///     assert_eq!(year, 2026, "rust in 2026!");
    /// #   Ok(())
    /// # }
    /// ```
    pub fn with<F, R>(dat: &'a T, mut func: F) -> R
    where
        F: FnMut(Self) -> R,
    {
        let ctx = Self::new(dat);

        func(ctx)
    }
}

impl<T> RegexCtx<'_, T>
where
    T: ?Sized,
{
    ///
    /// Wraps the context with a policy regex that will be matched before any pattern.
    ///
    /// # Example
    ///
    /// ```
    /// # use neure::ctx::CtxGuard;
    /// # use neure::prelude::*;
    /// #
    /// # fn main() -> Result<(), Box<dyn core::error::Error>> {
    ///     #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    ///     pub struct Dat<'a> {
    ///         span: Span,
    ///
    ///         dat: &'a str,
    ///     }
    ///
    ///     // a sample data from https://adventofcode.com/2015/day/7
    ///     const DATA: &str = r#"
    ///      XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    ///      XXXOOOOOXXXOXXXXOXXXXOOOOOXXXOOOOOXXX
    ///      XXXOXXXOXXXOXXXXOXXXXOXXXXXXXXXOXXXXX
    ///      XXXOOOOOXXXOXXXXOXXXXOOOOOXXXXXOXXXXX
    ///      XXXOXOXXXXXOXXXXOXXXXXXXXOXXXXXOXXXXX
    ///      XXXOXXOXXXXOXXXXOXXXXXXXXOXXXXXOXXXXX
    ///      XXXOXXXOXXXOOOOOOXXXXOOOOOXXXXXOXXXXX
    ///      XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    ///      "#;
    ///
    ///     // match "\n" or anything not 'X'
    ///     let text = "\n".or('X'.not().many1());
    ///     let mut ctx = CharsCtx::new(DATA).skip_before(|ctx: &mut CharsCtx| {
    ///         let mut g = CtxGuard::new(ctx);
    ///         let ret = g.try_mat(&'X'.many0());
    ///
    ///         g.process_ret(ret)
    ///     });
    ///
    ///     let texts: Vec<Dat> = ctx.ctor_with(&text.repeat(1..), |ctx, span| {
    ///         Ok(Dat {
    ///             span: *span,
    ///             dat: span.orig(ctx)?,
    ///         })
    ///     })?;
    ///     let mut off = 0;
    ///
    ///     // output:
    ///     //    OOOOO   O    O    OOOOO   OOOOO
    ///     //    O   O   O    O    O         O
    ///     //    OOOOO   O    O    OOOOO     O
    ///     //    O O     O    O        O     O
    ///     //    O  O    O    O        O     O
    ///     //    O   O   OOOOOO    OOOOO     O
    ///     for text in texts {
    ///         let Span { beg, len } = text.span;
    ///         let dat = text.dat;
    ///
    ///         if off < beg {
    ///             print!("{}", " ".repeat(beg - off));
    ///             off = beg;
    ///         }
    ///         print!("{}", dat);
    ///         off += len;
    ///     }
    ///
    /// #   Ok(())
    /// # }
    /// ```
    pub const fn skip_before<R>(self, regex: R) -> PolicyCtx<Self, R> {
        PolicyCtx { inner: self, regex }
    }
}

impl<'a> RegexCtx<'a, [u8]> {
    /// Creates a policy context that skips ASCII whitespace before pattern matching.
    pub const fn skip_ascii_whitespace(
        self,
    ) -> PolicyCtx<Self, crate::neu::Many0<Self, crate::neu::AsciiWhiteSpace<u8>, u8>> {
        use crate::neu;

        self.skip_before(neu::Many0::new(neu::ascii_whitespace(), neu::EmptyCond))
    }
}

impl<'a> RegexCtx<'a, str> {
    ///
    /// Creates a policy context that skips ASCII whitespace before pattern matching.
    ///
    /// # Example
    ///
    /// A simple example ignore all the whitespace before any match.
    ///
    /// ```
    /// # use neure::prelude::*;
    /// #
    /// # fn main() -> Result<(), Box<dyn core::error::Error>> {
    ///     #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    ///     pub struct Dat<'a> {
    ///         span: Span,
    ///
    ///         dat: &'a str,
    ///     }
    ///
    ///     #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    ///     pub enum Op<'a> {
    ///         Sig(Dat<'a>),
    ///
    ///         Wire(Dat<'a>),
    ///     }
    ///
    ///     #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    ///     pub enum Inst<'a> {
    ///         Store(Op<'a>),
    ///
    ///         And((Op<'a>, Op<'a>)),
    ///
    ///         Or((Op<'a>, Op<'a>)),
    ///
    ///         LShift((Op<'a>, Op<'a>)),
    ///
    ///         RShift((Op<'a>, Op<'a>)),
    ///
    ///         Not(Op<'a>),
    ///     }
    ///
    ///     // a sample data from https://adventofcode.com/2015/day/7
    ///     const DATA: &str = r#"
    /// 123 -> x
    /// 456 -> y
    /// x AND y -> d
    /// x OR y -> e
    /// x LSHIFT 2 -> f
    /// y RSHIFT 2 -> g
    /// NOT x -> h
    /// NOT y -> i
    ///      "#;
    ///
    ///     let sig = neu::digit(10).many1().map(Op::Sig);
    ///     let wire = neu::ascii_lowercase().many1();
    ///     let op = sig.or(wire.map(Op::Wire));
    ///     let and = op.sep_once("AND", op).map(Inst::And);
    ///     let or = op.sep_once("OR", op).map(Inst::Or);
    ///     let lshift = op.sep_once("LSHIFT", op).map(Inst::LShift);
    ///     let rshift = op.sep_once("RSHIFT", op).map(Inst::RShift);
    ///     let not = op.prefix("NOT").map(Inst::Not);
    ///     let store = sig.map(Inst::Store);
    ///     let src = and
    ///         .or(or.or(lshift.or(rshift.or(not.or(store)))))
    ///         .into_box();
    ///     let parser = src.sep_once("->", wire).collect::<_, Vec<_>>();
    ///
    ///     // ignore white space using re_policy
    ///     let mut ctx = CharsCtx::new(DATA).skip_ascii_whitespace();
    ///
    ///     let insts: Vec<_> = ctx.ctor_with(&parser, |ctx, span| {
    ///         Ok(Dat {
    ///             span: *span,
    ///             dat: span.orig(ctx)?,
    ///         })
    ///     })?;
    ///
    ///     assert_eq!(insts.len(), 8);
    ///     assert_eq!(
    ///         insts[0],
    ///         (
    ///             Inst::Store(Op::Sig(Dat {
    ///                 span: Span::new(1, 3),
    ///                 dat: "123"
    ///             })),
    ///             Dat {
    ///                 span: Span::new(8, 1),
    ///                 dat: "x"
    ///             }
    ///         )
    ///     );
    ///     assert_eq!(
    ///         insts[6],
    ///         (
    ///             Inst::Not(Op::Wire(Dat {
    ///                 span: Span::new(80, 1),
    ///                 dat: "x"
    ///             })),
    ///             Dat {
    ///                 span: Span::new(85, 1),
    ///                 dat: "h"
    ///             }
    ///         )
    ///     );
    ///
    /// #   Ok(())
    /// # }
    /// ```
    pub const fn skip_ascii_whitespace(
        self,
    ) -> PolicyCtx<Self, crate::neu::Many0<Self, crate::neu::AsciiWhiteSpace<char>, char>> {
        use crate::neu;

        self.skip_before(neu::Many0::new(neu::ascii_whitespace(), neu::EmptyCond))
    }
}

impl<'a> RegexCtx<'a, str> {
    /// Creates a policy context that skips Unicode whitespace before pattern matching.
    pub const fn skip_whitespace(
        self,
    ) -> PolicyCtx<Self, crate::neu::Many0<Self, crate::neu::WhiteSpace, char>> {
        use crate::neu;

        self.skip_before(neu::Many0::new(neu::whitespace(), neu::EmptyCond))
    }
}

impl<'a> Context<'a> for RegexCtx<'a, [u8]> {
    type Orig<'b> = &'b [u8];

    type Item = u8;

    type Iter<'b> = BytesIndices<'b, u8>;

    fn len(&self) -> usize {
        self.dat.len()
    }

    fn offset(&self) -> usize {
        self.offset
    }

    fn set_offset(&mut self, offset: usize) -> &mut Self {
        self.offset = offset;
        crate::neure_debug!("RegexCtx: set offset => {}", self.offset);
        self
    }

    fn inc(&mut self, offset: usize) -> &mut Self {
        self.offset += offset;
        crate::neure_debug!("RegexCtx: + {} => {}", offset, self.offset);
        self
    }

    fn dec(&mut self, offset: usize) -> &mut Self {
        self.offset -= offset;
        crate::neure_debug!("RegexCtx: - {} => {}", offset, self.offset);
        self
    }

    fn peek_at(&self, offset: usize) -> Result<Self::Iter<'a>, Error> {
        Ok(BytesIndices::new(self.orig_at(offset)?))
    }

    fn orig_sub(&self, offset: usize, len: usize) -> Result<Self::Orig<'a>, Error> {
        self.dat
            .get(offset..(offset + len))
            .ok_or(Error::OutOfBound)
    }

    fn clone_at(&self, offset: usize) -> Result<Self, Error> {
        self.orig_at(offset).map(RegexCtx::new)
    }
}

impl<'a> Context<'a> for RegexCtx<'a, str> {
    type Orig<'b> = &'b str;

    type Item = char;

    type Iter<'b> = CharIndices<'b>;

    fn len(&self) -> usize {
        self.dat.len()
    }

    fn offset(&self) -> usize {
        self.offset
    }

    fn set_offset(&mut self, offset: usize) -> &mut Self {
        self.offset = offset;
        crate::neure_debug!("RegexCtx: set offset = {}", self.offset);
        self
    }

    fn inc(&mut self, offset: usize) -> &mut Self {
        self.offset += offset;
        crate::neure_debug!("RegexCtx: + {} => {}", offset, self.offset);
        self
    }

    fn dec(&mut self, offset: usize) -> &mut Self {
        self.offset -= offset;
        crate::neure_debug!("RegexCtx: - {} => {}", offset, self.offset);
        self
    }

    fn orig_at(&self, offset: usize) -> Result<Self::Orig<'a>, Error> {
        self.dat.get(offset..).ok_or(Error::OutOfBound)
    }

    fn peek_at(&self, offset: usize) -> Result<Self::Iter<'a>, Error> {
        Ok(self.orig_at(offset)?.char_indices())
    }

    fn orig_sub(&self, offset: usize, len: usize) -> Result<Self::Orig<'a>, Error> {
        self.dat
            .get(offset..(offset + len))
            .ok_or(Error::OutOfBound)
    }

    fn clone_at(&self, offset: usize) -> Result<Self, Error> {
        self.orig_at(offset).map(RegexCtx::new)
    }
}

impl<'a, T> Match<'a> for RegexCtx<'a, T>
where
    T: ?Sized,
    Self: Context<'a>,
{
    fn try_mat<Pat>(&mut self, pat: &Pat) -> Result<Span, Error>
    where
        Pat: Regex<RegexCtx<'a, T>> + ?Sized,
    {
        self.try_mat_before(pat, &|_: &mut Self| Ok(Span::default()))
    }
}

impl<'a, T> PolicyMatch<'a> for RegexCtx<'a, T>
where
    T: ?Sized,
    Self: Context<'a>,
{
    fn try_mat_policy<P, B, A>(&mut self, pat: &P, before: &B, after: &A) -> Result<Span, Error>
    where
        P: Regex<RegexCtx<'a, T>> + ?Sized,
        B: Regex<RegexCtx<'a, T>> + ?Sized,
        A: Regex<RegexCtx<'a, T>> + ?Sized,
    {
        before.try_parse(self)?;
        let ret = pat.try_parse(self)?;

        after.try_parse(self)?;
        Ok(ret)
    }
}

impl<'a> IndexBySpan for RegexCtx<'a, [u8]> {
    type Output = [u8];

    fn get_by_span(&self, span: &Span) -> Option<&Self::Output> {
        span.orig(self).ok()
    }
}

impl<'a> IndexBySpan for RegexCtx<'a, str> {
    type Output = str;

    fn get_by_span(&self, span: &Span) -> Option<&Self::Output> {
        span.orig(self).ok()
    }
}