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
use core::fmt::Debug;
use core::marker::PhantomData;

use crate::ctor::Ctor;

use crate::ctor::Handler;
use crate::ctx::CtxGuard;
use crate::ctx::Match;
use crate::debug_ctor_beg;
use crate::debug_ctor_reval;
use crate::debug_ctor_stage;
use crate::debug_regex_beg;
use crate::debug_regex_reval;
use crate::debug_regex_stage;
use crate::err::Error;
use crate::regex::Regex;
use crate::regex::impl_not_for_regex;
use crate::span::Span;

///
/// Matches a pattern followed by a mandatory suffix, returning only the main pattern's value during construction.
///
/// This combinator requires both the main pattern and suffix pattern to match consecutively.
/// During construction, it returns only the value from the main pattern while still enforcing
/// the presence of the suffix. During matching, it returns the combined span of both patterns.
///
/// # Regex
///
/// Attempts to match the main pattern first, then immediately attempts to match the suffix
/// pattern at the new position. Returns a single span covering both matches concatenated
/// together. Fails if either pattern fails to match. The combined span is created by merging
/// the two spans sequentially, requiring them to be adjacent with no gaps.
///
/// ## Example
/// ```
/// # use neure::prelude::*;
/// #
/// # fn main() -> Result<(), Box<dyn core::error::Error>> {
///     let protocol = "https".or("http".or("ftp"));
///     let protocol = protocol.suffix("://");
///     let domain = neu::alphabetic().many1();
///     let domain = domain.sep(".").at_least(2);
///     let url = protocol.then(domain);
///     let mut ctx = CharsCtx::new(r#"ftp://ftp.kernel.org"#);
///
///     assert_eq!(ctx.try_mat(&url)?, Span::new(0, ctx.len()));
/// #   Ok(())
/// # }
/// ```
///
/// # Ctor
///
/// First constructs a value using the main pattern. If successful, it then attempts to match
/// the suffix pattern (without using its value). Returns the main pattern's constructed value
/// only if both patterns succeed. Fails if either pattern fails, with errors from the suffix
/// taking precedence when both fail. The context position advances past both patterns on success.
///
/// ## Example
/// ```
/// # use neure::prelude::*;
/// #
/// # fn main() -> Result<(), Box<dyn core::error::Error>> {
///     let protocol = "https".or("http".or("ftp"));
///     let protocol = protocol.suffix("://");
///     let domain = neu::alphabetic().many1();
///     let domain = domain.sep(".").at_least(2);
///     let url = protocol.then(domain);
///     let mut ctx = CharsCtx::new(r#"https://www.mozilla.org"#);
///
///     assert_eq!(ctx.ctor(&url)?, ("https", vec!["www", "mozilla", "org"]));
/// #   Ok(())
/// # }
/// ```
///
/// # Behavior Notes
///
/// - Both patterns must match consecutively with no gaps between them
/// - The suffix pattern is mandatory - failure to match it causes the entire pattern to fail
/// - During construction:
///   - Only the main pattern's value is returned
///   - The suffix pattern's value is ignored (but its match is required)
/// - During matching:
///   - Returns a single span covering both patterns
///   - The span length equals the sum of both pattern spans
/// - Context position is advanced past both patterns only on complete success
/// - Errors from the suffix pattern mask errors from the main pattern when both fail
///
/// # Performance
///
/// Both patterns are always evaluated in sequence. For optimal performance:
/// - Place cheaper patterns first when possible
/// - Ensure the main pattern fails quickly on invalid inputs
/// - Avoid expensive operations in the suffix pattern
pub struct Suffix<C, P, T> {
    pat: P,
    suffix: T,
    marker: PhantomData<C>,
}

impl_not_for_regex!(Suffix<C, P, T>);

impl<C, P, T> Debug for Suffix<C, P, T>
where
    P: Debug,
    T: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("PadUnit")
            .field("pat", &self.pat)
            .field("suffix", &self.suffix)
            .finish()
    }
}

impl<C, P, T> Default for Suffix<C, P, T>
where
    P: Default,
    T: Default,
{
    fn default() -> Self {
        Self {
            pat: Default::default(),
            suffix: Default::default(),
            marker: Default::default(),
        }
    }
}

impl<C, P, T> Clone for Suffix<C, P, T>
where
    P: Clone,
    T: Clone,
{
    fn clone(&self) -> Self {
        Self {
            pat: self.pat.clone(),
            suffix: self.suffix.clone(),
            marker: self.marker,
        }
    }
}

impl<C, P, T> Copy for Suffix<C, P, T>
where
    P: Copy,
    T: Copy,
{
}

impl<C, P, T> Suffix<C, P, T> {
    pub const fn new(pat: P, suffix: T) -> Self {
        Self {
            pat,
            suffix,
            marker: PhantomData,
        }
    }

    pub const fn pat(&self) -> &P {
        &self.pat
    }

    pub const fn pat_mut(&mut self) -> &mut P {
        &mut self.pat
    }

    pub const fn suffix(&self) -> &T {
        &self.suffix
    }

    pub const fn suffix_mut(&mut self) -> &mut T {
        &mut self.suffix
    }

    pub fn set_pat(&mut self, pat: P) -> &mut Self {
        self.pat = pat;
        self
    }

    pub fn set_suffix(&mut self, suffix: T) -> &mut Self {
        self.suffix = suffix;
        self
    }
}

impl<'a, C, P, T, O, H> Ctor<C, O, H> for Suffix<C, P, T>
where
    T: Regex<C>,
    P: Ctor<C, O, H>,
    C: Match<'a>,
    H: Handler<C>,
{
    #[inline(always)]
    fn construct(&self, ctx: &mut C, func: &mut H) -> Result<O, Error> {
        let mut ctx = CtxGuard::new(ctx);

        debug_ctor_beg!("Suffix", ctx.beg());

        let ret = debug_ctor_stage!("Suffix", "pat", self.pat.construct(ctx.ctx(), func));

        if ret.is_ok() {
            let _ = debug_ctor_stage!("Suffix", "suffix", ctx.try_mat(&self.suffix)?);
        }
        debug_ctor_reval!("Suffix", ctx.beg(), ctx.end(), ret.is_ok());
        ctx.process_ret(ret)
    }
}

impl<'a, C, P, T> Regex<C> for Suffix<C, P, T>
where
    T: Regex<C>,
    P: Regex<C>,
    C: Match<'a>,
{
    #[inline(always)]
    fn try_parse(&self, ctx: &mut C) -> Result<Span, Error> {
        let mut ctx = CtxGuard::new(ctx);

        debug_regex_beg!("Suffix", ctx.beg());
        let mut ret = debug_regex_stage!("Suffix", "pat", ctx.try_mat(&self.pat)?);

        ret.add_assign(debug_regex_stage!(
            "Suffix",
            "suffix",
            ctx.try_mat(&self.suffix)?
        ));
        debug_regex_reval!("Suffix", Ok(ret))
    }
}

///
/// Matches a mandatory prefix followed by a pattern, returning only the main pattern's value during construction.
///
/// This combinator requires both the prefix pattern and main pattern to match consecutively.
/// During construction, it returns only the value from the main pattern while still enforcing
/// the presence of the prefix. During matching, it returns the combined span of both patterns.
///
/// # Regex
///
/// Attempts to match the prefix pattern first, then immediately attempts to match the main
/// pattern at the new position. Returns a single span covering both matches concatenated
/// together. Fails if either pattern fails to match. The combined span is created by merging
/// the two spans sequentially, requiring them to be adjacent with no gaps.
///
/// ## Example
/// ```
/// # use neure::prelude::*;
/// #
/// # fn main() -> Result<(), Box<dyn core::error::Error>> {
///     let protocol = "https".or("http".or("ftp")).suffix("://");
///     let domain = neu::alphabetic().many1();
///     let domain = domain.sep(".").at_least(2);
///     let url = domain.prefix(protocol);
///     let mut ctx = CharsCtx::new(r#"ftp://ftp.kernel.org"#);
///
///     assert_eq!(ctx.try_mat(&url)?, Span::new(0, ctx.len()));
/// #   Ok(())
/// # }
/// ```
///
/// # Ctor
///
/// First matches the prefix pattern (without using its value). If successful, it then constructs
/// a value using the main pattern. Returns the main pattern's constructed value only if both
/// patterns succeed. Fails if either pattern fails, with errors from the main pattern taking
/// precedence when both fail. The context position advances past both patterns on success.
///
/// ## Example
/// ```
/// # use neure::prelude::*;
/// #
/// # fn main() -> Result<(), Box<dyn core::error::Error>> {
///     let protocol = "https".or("http".or("ftp")).suffix("://");
///     let domain = neu::alphabetic().many1();
///     let domain = domain.sep(".").at_least(2);
///     let url = domain.prefix(protocol);
///     let mut ctx = CharsCtx::new(r#"ftp://ftp.kernel.org"#);
///
///     assert_eq!(ctx.ctor(&url)?, ["ftp", "kernel", "org"]);
/// #   Ok(())
/// # }
/// ```
///
/// # Behavior Notes
///
/// - Both patterns must match consecutively with no gaps between them
/// - The prefix pattern is mandatory - failure to match it causes the entire pattern to fail
/// - During construction:
///   - Only the main pattern's value is returned
///   - The prefix pattern's value is ignored (but its match is required)
/// - During matching:
///   - Returns a single span covering both patterns
///   - The span length equals the sum of both pattern spans
/// - Context position is advanced past both patterns only on complete success
/// - Errors from the main pattern mask errors from the prefix pattern when both fail
///
/// # Performance
///
/// Both patterns are evaluated in sequence. For optimal performance:
/// - Place cheaper patterns first (the prefix is evaluated before the main pattern)
/// - Ensure the prefix pattern fails quickly on invalid inputs
/// - Avoid expensive operations in the prefix pattern since it's evaluated unconditionally
pub struct Prefix<C, P, T> {
    pat: P,
    prefix: T,
    marker: PhantomData<C>,
}

impl_not_for_regex!(Prefix<C, P, T>);

impl<C, P, T> Debug for Prefix<C, P, T>
where
    P: Debug,
    T: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("PaddedUnit")
            .field("pat", &self.pat)
            .field("prefix", &self.prefix)
            .finish()
    }
}

impl<C, P, T> Default for Prefix<C, P, T>
where
    P: Default,
    T: Default,
{
    fn default() -> Self {
        Self {
            pat: Default::default(),
            prefix: Default::default(),
            marker: Default::default(),
        }
    }
}

impl<C, P, T> Clone for Prefix<C, P, T>
where
    P: Clone,
    T: Clone,
{
    fn clone(&self) -> Self {
        Self {
            pat: self.pat.clone(),
            prefix: self.prefix.clone(),
            marker: self.marker,
        }
    }
}

impl<C, P, T> Copy for Prefix<C, P, T>
where
    P: Copy,
    T: Copy,
{
}

impl<C, P, T> Prefix<C, P, T> {
    pub const fn new(pat: P, prefix: T) -> Self {
        Self {
            pat,
            prefix,
            marker: PhantomData,
        }
    }

    pub const fn pat(&self) -> &P {
        &self.pat
    }

    pub const fn pat_mut(&mut self) -> &mut P {
        &mut self.pat
    }

    pub const fn prefix(&self) -> &T {
        &self.prefix
    }

    pub const fn prefix_mut(&mut self) -> &mut T {
        &mut self.prefix
    }

    pub fn set_pat(&mut self, pat: P) -> &mut Self {
        self.pat = pat;
        self
    }

    pub fn set_prefix(&mut self, prefix: T) -> &mut Self {
        self.prefix = prefix;
        self
    }
}

impl<'a, C, P, T, O, H> Ctor<C, O, H> for Prefix<C, P, T>
where
    T: Regex<C>,
    P: Ctor<C, O, H>,
    C: Match<'a>,
    H: Handler<C>,
{
    #[inline(always)]
    fn construct(&self, ctx: &mut C, func: &mut H) -> Result<O, Error> {
        let mut ctx = CtxGuard::new(ctx);

        debug_ctor_beg!("Prefix", ctx.beg());

        let _ = debug_ctor_stage!("Prefix", "head", ctx.try_mat(&self.prefix)?);
        let r = debug_ctor_stage!("Prefix", "prefix", self.pat.construct(ctx.ctx(), func));

        debug_ctor_reval!("Prefix", ctx.beg(), ctx.end(), r.is_ok());
        ctx.process_ret(r)
    }
}

impl<'a, C, P, T> Regex<C> for Prefix<C, P, T>
where
    T: Regex<C>,
    P: Regex<C>,
    C: Match<'a>,
{
    #[inline(always)]
    fn try_parse(&self, ctx: &mut C) -> Result<Span, Error> {
        let mut ctx = CtxGuard::new(ctx);

        debug_regex_beg!("Prefix", ctx.beg());

        let mut ret = debug_regex_stage!("Prefix", "head", ctx.try_mat(&self.prefix)?);

        ret.add_assign(debug_regex_stage!(
            "Prefix",
            "prefix",
            ctx.try_mat(&self.pat)?
        ));
        debug_regex_reval!("Prefix", Ok(ret))
    }
}