zngur-parser 0.9.0

Parser of the zng file
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
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
use crate::{BoxedZngParser, ParseContext, Span, Spanned, Token, ZngParser, spanned};
use chumsky::prelude::*;

/// a type that can be matched against a Pattern
pub trait Matchable: core::fmt::Debug + Clone + PartialEq + Eq {
    /// A pattern type to match Self against
    type Pattern: MatchPattern;
    /// compare self to `Pattern`
    fn eval(&self, pattern: &Self::Pattern, ctx: &mut ParseContext) -> bool;
}

/// a type that can be matched against a Pattern
pub trait MatchableParse<'src>: Matchable {
    /// return a parser for the item as it would appear in an `#if` or `#match` statement
    fn parser() -> impl ZngParser<'src, Self>;

    /// return an optional combined parser for use in `#if` statements
    #[allow(clippy::complexity)]
    fn combined()
    -> Option<BoxedZngParser<'src, (Spanned<Self>, Spanned<<Self as Matchable>::Pattern>)>> {
        None
    }
}

pub trait MatchPattern: core::fmt::Debug + Clone + PartialEq + Eq {
    /// a pattern that matches the existence of "some" value
    fn default_some(span: crate::Span) -> Self;
}

/// a Pattern that can be matched against
pub trait MatchPatternParse<'src>: MatchPattern {
    /// return a parser for for the pattern
    fn parser() -> impl ZngParser<'src, Self>;
}

pub trait BodyItem: core::fmt::Debug + Clone + PartialEq + Eq {
    /// The type Self turns into when added into the Spec
    type Processed;

    /// Transform self into `Processed` type
    fn process(self, ctx: &mut ParseContext) -> Self::Processed;
}

/// a type that hold the body of a conditional statement
pub trait ConditionBody<Pattern: MatchPattern, Item: BodyItem>: core::fmt::Debug {
    /// the pattern that guards this body
    fn pattern(&self) -> &Pattern;
}

/// a trait that marks the Cardinality of items inside a body (One? or Many?)
pub trait ConditionBodyCardinality<Item: BodyItem>:
    core::fmt::Debug + Clone + PartialEq + Eq
{
    /// the type that hold the body of the conditional statement
    type Body<Pattern: MatchPattern>: ConditionBody<Pattern, Item> + Clone + PartialEq + Eq;
    /// the type that holds the items in the body of a conditional statement
    type Block: core::fmt::Debug + Clone + PartialEq + Eq + IntoIterator<Item = Spanned<Item>>;
    /// the type that hold the items of a passing body
    type EvalResult: IntoIterator<Item = Spanned<<Item as BodyItem>::Processed>>;
    /// transform a single item into Self::Block
    fn single_to_block(item: Spanned<Item>) -> Self::Block;
    /// create a new empty Self::Bock
    fn empty_block() -> Self::Block;
    /// create a new Self::Body from a block and the pattern that guards it
    fn new_body<Pattern: MatchPattern>(
        pattern: Spanned<Pattern>,
        block: Self::Block,
    ) -> Self::Body<Pattern>;
    /// transform a block into it's processed result
    fn pass_block(block: &Self::Block, ctx: &mut ParseContext) -> Self::EvalResult;
    /// transform a body into it's processed result
    fn pass_body<Pattern: MatchPattern>(
        body: &Self::Body<Pattern>,
        ctx: &mut ParseContext,
    ) -> Self::EvalResult;
}

/// a trait for a conditional item in a parsed spec
pub trait ConditionalItem<Item: BodyItem, Cardinality: ConditionBodyCardinality<Item>> {
    /// Evaluate the statement and produce resulting items of the first arm that passes
    fn eval(&self, ctx: &mut ParseContext) -> Option<Cardinality::EvalResult>;
}

/// a body of a conditional statement that holds 0..N Items
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConditionBodyMany<Pattern: MatchPattern, Item: BodyItem> {
    pub pattern: Spanned<Pattern>,
    pub block: Vec<Spanned<Item>>,
}

/// a body of a conditional statement that holds 0..1 items
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConditionBodySingle<Pattern: MatchPattern, Item: BodyItem> {
    pub pattern: Spanned<Pattern>,
    pub block: Option<Spanned<Item>>,
}

impl<Pattern: MatchPattern, Item: BodyItem> ConditionBody<Pattern, Item>
    for ConditionBodyMany<Pattern, Item>
{
    fn pattern(&self) -> &Pattern {
        &self.pattern.inner
    }
}

impl<Pattern: MatchPattern, Item: BodyItem> ConditionBody<Pattern, Item>
    for ConditionBodySingle<Pattern, Item>
{
    fn pattern(&self) -> &Pattern {
        &self.pattern.inner
    }
}

/// Marker type for a conditional statement that contextually only accepts one item
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct SingleItem;

impl<Item: BodyItem> ConditionBodyCardinality<Item> for SingleItem {
    type Body<Pattern: MatchPattern> = ConditionBodySingle<Pattern, Item>;
    type Block = Option<Spanned<Item>>;
    type EvalResult = Option<Spanned<<Item as BodyItem>::Processed>>;

    fn single_to_block(item: Spanned<Item>) -> Self::Block {
        Some(item)
    }

    fn empty_block() -> Self::Block {
        None
    }

    fn new_body<Pattern: MatchPattern>(
        pattern: Spanned<Pattern>,
        block: Self::Block,
    ) -> Self::Body<Pattern> {
        ConditionBodySingle { pattern, block }
    }

    fn pass_block(block: &Self::Block, ctx: &mut ParseContext) -> Self::EvalResult {
        block.clone().map(|item| {
            let span = item.span;
            Spanned {
                span,
                inner: item.inner.process(ctx),
            }
        })
    }

    fn pass_body<Pattern: MatchPattern>(
        body: &Self::Body<Pattern>,
        ctx: &mut ParseContext,
    ) -> Self::EvalResult {
        Self::pass_block(&body.block, ctx)
    }
}

/// Marker type for a conditional statement that contextually accepts any number of items
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct NItems;

impl<Item: BodyItem> ConditionBodyCardinality<Item> for NItems {
    type Body<Pattern: MatchPattern> = ConditionBodyMany<Pattern, Item>;
    type Block = Vec<Spanned<Item>>;
    type EvalResult = Vec<Spanned<<Item as BodyItem>::Processed>>;

    fn single_to_block(item: Spanned<Item>) -> Self::Block {
        vec![item]
    }

    fn empty_block() -> Self::Block {
        Vec::new()
    }

    fn new_body<Pattern: MatchPattern>(
        pattern: Spanned<Pattern>,
        block: Self::Block,
    ) -> Self::Body<Pattern> {
        ConditionBodyMany { pattern, block }
    }

    fn pass_block(block: &Self::Block, ctx: &mut ParseContext) -> Self::EvalResult {
        block
            .iter()
            .cloned()
            .map(|item| {
                let span = item.span;
                Spanned {
                    span,
                    inner: item.inner.process(ctx),
                }
            })
            .collect()
    }

    fn pass_body<Pattern: MatchPattern>(
        body: &Self::Body<Pattern>,
        ctx: &mut ParseContext,
    ) -> Self::EvalResult {
        Self::pass_block(&body.block, ctx)
    }
}

/// a guard for an #if statement
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConditionGuard<Scrutinee: Matchable> {
    Single {
        scrutinee: Spanned<Scrutinee>,
        pattern: Spanned<<Scrutinee as Matchable>::Pattern>,
        span: Span,
    },
    And(Vec<ConditionGuard<Scrutinee>>, Span),
    Or(Vec<ConditionGuard<Scrutinee>>, Span),
    Not(Box<ConditionGuard<Scrutinee>>, Span),
    Grouped(Box<ConditionGuard<Scrutinee>>, Span),
}

impl<Scrutinee: Matchable> ConditionGuard<Scrutinee> {
    fn eval(&self, ctx: &mut ParseContext) -> bool {
        match self {
            Self::Single {
                scrutinee, pattern, ..
            } => scrutinee.inner.eval(&pattern.inner, ctx),
            Self::And(items, _) => items.iter().all(|item| item.eval(ctx)),
            Self::Or(items, _) => items.iter().any(|item| item.eval(ctx)),
            Self::Not(item, _) => !item.eval(ctx),
            Self::Grouped(item, _) => item.eval(ctx),
        }
    }
}

/// a branch of an `#if` statement
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConditionBranch<
    Scrutinee: Matchable,
    Item: BodyItem,
    Cardinality: ConditionBodyCardinality<Item>,
> {
    pub guard: ConditionGuard<Scrutinee>,
    pub block: <Cardinality as ConditionBodyCardinality<Item>>::Block,
}

/// a complete `#if {} #else if #else {}` statement
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConditionIf<
    Scrutinee: Matchable,
    Item: BodyItem,
    Cardinality: ConditionBodyCardinality<Item>,
> {
    pub arms: Vec<ConditionBranch<Scrutinee, Item, Cardinality>>,
    pub fallback: Option<Cardinality::Block>,
}

/// a `#match` statement
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConditionMatch<
    Scrutinee: Matchable,
    Item: BodyItem,
    Cardinality: ConditionBodyCardinality<Item>,
> {
    pub scrutinee: Spanned<Scrutinee>,
    pub arms: Vec<
        Spanned<
            <Cardinality as ConditionBodyCardinality<Item>>::Body<
                <Scrutinee as Matchable>::Pattern,
            >,
        >,
    >,
}

impl<Scrutinee: Matchable, Item: BodyItem, Cardinality: ConditionBodyCardinality<Item>>
    ConditionalItem<Item, Cardinality> for ConditionBranch<Scrutinee, Item, Cardinality>
{
    fn eval(
        &self,
        ctx: &mut ParseContext,
    ) -> Option<<Cardinality as ConditionBodyCardinality<Item>>::EvalResult> {
        if self.guard.eval(ctx) {
            return Some(<Cardinality as ConditionBodyCardinality<Item>>::pass_block(
                &self.block,
                ctx,
            ));
        }
        None
    }
}

impl<Scrutinee: Matchable, Item: BodyItem, Cardinality: ConditionBodyCardinality<Item>>
    ConditionalItem<Item, Cardinality> for ConditionMatch<Scrutinee, Item, Cardinality>
{
    fn eval(
        &self,
        ctx: &mut ParseContext,
    ) -> Option<<Cardinality as ConditionBodyCardinality<Item>>::EvalResult> {
        for arm in &self.arms {
            let pattern = arm.inner.pattern();
            if self.scrutinee.inner.eval(pattern, ctx) {
                return Some(<Cardinality as ConditionBodyCardinality<Item>>::pass_body(
                    &arm.inner, ctx,
                ));
            }
        }
        None
    }
}

impl<Scrutinee: Matchable, Item: BodyItem, Cardinality: ConditionBodyCardinality<Item>>
    ConditionalItem<Item, Cardinality> for ConditionIf<Scrutinee, Item, Cardinality>
{
    fn eval(
        &self,
        ctx: &mut ParseContext,
    ) -> Option<<Cardinality as ConditionBodyCardinality<Item>>::EvalResult> {
        for arm in &self.arms {
            if let Some(result) = arm.eval(ctx) {
                return Some(result);
            }
        }
        if let Some(fallback) = &self.fallback {
            return Some(<Cardinality as ConditionBodyCardinality<Item>>::pass_block(
                fallback, ctx,
            ));
        }
        None
    }
}

/// a conditional item behind an if or match statement
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Condition<
    Scrutinee: Matchable,
    Item: BodyItem,
    Cardinality: ConditionBodyCardinality<Item>,
> {
    If(ConditionIf<Scrutinee, Item, Cardinality>),
    Match(ConditionMatch<Scrutinee, Item, Cardinality>),
}

impl<Scrutinee: Matchable, Item: BodyItem, Cardinality: ConditionBodyCardinality<Item>>
    ConditionalItem<Item, Cardinality> for Condition<Scrutinee, Item, Cardinality>
{
    fn eval(
        &self,
        ctx: &mut ParseContext,
    ) -> Option<<Cardinality as ConditionBodyCardinality<Item>>::EvalResult> {
        match self {
            Self::If(item) => item.eval(ctx),
            Self::Match(item) => item.eval(ctx),
        }
    }
}

/// a trait that helps build combined parsers for ConditionalItem's that accept `#if {} #else {}` or `#match`
pub trait Conditional<'src, Item: BodyItem, Cardinality: ConditionBodyCardinality<Item>> {
    type Scrutinee: MatchableParse<'src>;
    fn if_parser(
        item_parser: impl ZngParser<'src, Item> + 'src,
    ) -> BoxedZngParser<'src, Condition<Self::Scrutinee, Item, Cardinality>>;
    fn match_parser(
        item_parser: impl ZngParser<'src, Item> + 'src,
    ) -> BoxedZngParser<'src, Condition<Self::Scrutinee, Item, Cardinality>>;
}

/// a parser for a block used in a SingleItemBody
pub fn block_for_single<'src, Item: BodyItem>(
    item_parser: impl ZngParser<'src, Item>,
) -> impl ZngParser<'src, Option<Spanned<Item>>> {
    spanned(item_parser)
        .repeated()
        .at_most(1)
        .collect::<Vec<_>>()
        .map(|items| {
            // should be 1 or zero because of `.at_most(1)`
            items.into_iter().next()
        })
}

/// a parser for a block used in a ManyItemBody
pub fn block_for_many<'src, Item: BodyItem>(
    item_parser: impl ZngParser<'src, Item>,
) -> impl ZngParser<'src, Vec<Spanned<Item>>> {
    spanned(item_parser).repeated().collect::<Vec<_>>()
}

/// parser for a guarded block used in `#if`
pub fn guarded_block<
    'src,
    Scrutinee: MatchableParse<'src> + 'src,
    Item: BodyItem,
    Cardinality: ConditionBodyCardinality<Item>,
>(
    block: impl ZngParser<'src, Cardinality::Block>,
) -> impl ZngParser<'src, ConditionBranch<Scrutinee, Item, Cardinality>>
where
    <Scrutinee as Matchable>::Pattern: MatchPatternParse<'src>,
{
    let guard = recursive(|guard| {
        let single = if let Some(combined) = <Scrutinee as MatchableParse<'src>>::combined() {
            combined
        } else {
            spanned(<Scrutinee as MatchableParse<'src>>::parser())
                .then(
                    just(Token::Eq)
                        .ignore_then(spanned(
                            <<Scrutinee as Matchable>::Pattern as MatchPatternParse<'src>>::parser(
                            ),
                        ))
                        .or_not()
                        .map_with(|pat, e| {
                            pat.unwrap_or_else(|| Spanned {
                                inner: <Scrutinee as Matchable>::Pattern::default_some(e.span()),
                                span: e.span(),
                            })
                        }),
                )
                .boxed()
        }
        .map_with(|(scrutinee, pattern), e| ConditionGuard::Single {
            scrutinee,
            pattern,
            span: e.span(),
        })
        .or(
            spanned(guard.delimited_by(just(Token::ParenOpen), just(Token::ParenClose)))
                .map(|item| ConditionGuard::Grouped(Box::new(item.inner), item.span)),
        );

        let not_pat = just(Token::Bang)
            .repeated()
            .foldr_with(single, |_op, rhs, e| {
                ConditionGuard::Not(Box::new(rhs), e.span())
            });

        let and_pat = not_pat.clone().foldl_with(
            just([Token::And, Token::And])
                .ignore_then(not_pat)
                .repeated(),
            |lhs, rhs, e| match lhs {
                ConditionGuard::And(mut items, _span) => {
                    items.push(rhs);
                    ConditionGuard::And(items, e.span())
                }
                _ => ConditionGuard::And(vec![lhs, rhs], e.span()),
            },
        );

        // or pat
        and_pat.clone().foldl_with(
            just([Token::Pipe, Token::Pipe])
                .ignore_then(and_pat)
                .repeated(),
            |lhs, rhs, e| match lhs {
                ConditionGuard::Or(mut items, _span) => {
                    items.push(rhs);
                    ConditionGuard::Or(items, e.span())
                }
                _ => ConditionGuard::Or(vec![lhs, rhs], e.span()),
            },
        )
    });

    guard
        .then(block.delimited_by(just(Token::BraceOpen), just(Token::BraceClose)))
        .map(move |(guard, block)| ConditionBranch { guard, block })
}

/// parser for an `#if {} #else if {} #else {}` statement
pub fn if_stmnt<
    'src,
    Scrutinee: MatchableParse<'src>,
    Item: BodyItem,
    Cardinality: ConditionBodyCardinality<Item>,
>(
    guard: impl ZngParser<'src, ConditionBranch<Scrutinee, Item, Cardinality>>,
    fallback: impl ZngParser<'src, Cardinality::Block>,
) -> impl ZngParser<'src, ConditionIf<Scrutinee, Item, Cardinality>>
where
    <Scrutinee as Matchable>::Pattern: MatchPatternParse<'src>,
{
    just([Token::Sharp, Token::KwIf])
        .ignore_then(guard.clone())
        .then(
            just([Token::Sharp, Token::KwElse, Token::KwIf])
                .ignore_then(guard)
                .repeated()
                .collect::<Vec<_>>()
                .or_not(),
        )
        .then(
            just([Token::Sharp, Token::KwElse])
                .ignore_then(fallback.delimited_by(just(Token::BraceOpen), just(Token::BraceClose)))
                .or_not(),
        )
        .map(|((if_block, else_if_blocks), else_block)| {
            let mut arms: Vec<ConditionBranch<Scrutinee, Item, Cardinality>> = vec![if_block];
            arms.extend(else_if_blocks.unwrap_or_default());
            ConditionIf {
                arms,
                fallback: else_block,
            }
        })
}

/// a parser for the arm of a `#match` statement
fn match_arm<
    'src,
    Scrutinee: MatchableParse<'src>,
    Item: BodyItem,
    Cardinality: ConditionBodyCardinality<Item>,
>(
    block: impl ZngParser<'src, Cardinality::Block>,
    item_parser: impl ZngParser<'src, Item>,
) -> impl ZngParser<
    'src,
    <Cardinality as ConditionBodyCardinality<Item>>::Body<<Scrutinee as Matchable>::Pattern>,
>
where
    <Scrutinee as Matchable>::Pattern: MatchPatternParse<'src>,
{
    let arm_choices = (
        block.delimited_by(just(Token::BraceOpen), just(Token::BraceClose)),
        spanned(item_parser).map(<Cardinality as ConditionBodyCardinality<Item>>::single_to_block),
        just([Token::BraceOpen, Token::BraceClose])
            .map(|_| <Cardinality as ConditionBodyCardinality<Item>>::empty_block()),
    );
    spanned(<<Scrutinee as Matchable>::Pattern as MatchPatternParse<
        'src,
    >>::parser())
    .then(just(Token::ArrowArm).ignore_then(choice(arm_choices)))
    .map(|(pattern, block)| {
        <Cardinality as ConditionBodyCardinality<Item>>::new_body(pattern, block)
    })
}

/// a parser for a `#match` statement
fn match_stmt<
    'src,
    Scrutinee: MatchableParse<'src>,
    Item: BodyItem,
    Cardinality: ConditionBodyCardinality<Item>,
>(
    block: impl ZngParser<'src, Cardinality::Block>,
    item_parser: impl ZngParser<'src, Item>,
) -> impl ZngParser<'src, ConditionMatch<Scrutinee, Item, Cardinality>>
where
    <Scrutinee as Matchable>::Pattern: MatchPatternParse<'src>,
{
    let arm = match_arm::<Scrutinee, Item, Cardinality>(block, item_parser);

    just([Token::Sharp, Token::KwMatch])
        .ignore_then(spanned(<Scrutinee as MatchableParse>::parser()))
        .then(
            spanned(arm)
                .separated_by(just(Token::Comma).or_not())
                .allow_trailing()
                .collect::<Vec<_>>()
                .delimited_by(just(Token::BraceOpen), just(Token::BraceClose)),
        )
        .map(|(scrutinee, arms)| ConditionMatch { scrutinee, arms })
}

pub fn conditional_item<
    'src,
    Item: BodyItem,
    Cond: Conditional<'src, Item, Cardinality>,
    Cardinality: ConditionBodyCardinality<Item>,
>(
    item_parser: impl ZngParser<'src, Item> + 'src,
) -> impl ZngParser<
    'src,
    Condition<<Cond as Conditional<'src, Item, Cardinality>>::Scrutinee, Item, Cardinality>,
> {
    let if_parser = <Cond as Conditional<'src, Item, Cardinality>>::if_parser(item_parser.clone()).try_map_with(|match_, e| {
        if !e.state().unstable_features.cfg_if {
            Err(Rich::custom(e.span(), "`#if` statements are unstable. Enable them by using `#unstable(cfg_if)` at the top of the file."))
        } else {
            Ok(match_)
        }
    });
    let match_parser = <Cond as Conditional<'src, Item, Cardinality>>::match_parser(item_parser).try_map_with(|match_, e| {
        if !e.state().unstable_features.cfg_match {
            Err(Rich::custom(e.span(), "`#match` statements are unstable. Enable them by using `#unstable(cfg_match)` at the top of the file."))
        } else {
            Ok(match_)
        }
    });
    choice((if_parser, match_parser))
}

impl<'src, Scrutinee: MatchableParse<'src> + 'src, Item: BodyItem + 'src>
    Conditional<'src, Item, SingleItem> for Scrutinee
where
    <Scrutinee as Matchable>::Pattern: MatchPatternParse<'src>,
{
    type Scrutinee = Scrutinee;
    fn if_parser(
        item_parser: impl ZngParser<'src, Item> + 'src,
    ) -> BoxedZngParser<'src, Condition<Scrutinee, Item, SingleItem>> {
        let block = block_for_single::<Item>(item_parser);
        let guard = guarded_block::<Scrutinee, Item, SingleItem>(block.clone());

        if_stmnt::<Scrutinee, Item, SingleItem>(guard, block)
            .map(|item| Condition::<Scrutinee, Item, SingleItem>::If(item))
            .boxed()
    }

    fn match_parser(
        item_parser: impl ZngParser<'src, Item> + 'src,
    ) -> BoxedZngParser<'src, Condition<Scrutinee, Item, SingleItem>> {
        let block = block_for_single::<Item>(item_parser.clone());
        match_stmt::<Scrutinee, Item, SingleItem>(block, item_parser)
            .map(|item| Condition::<Scrutinee, Item, SingleItem>::Match(item))
            .boxed()
    }
}

impl<'src, Scrutinee: MatchableParse<'src> + 'src, Item: BodyItem + 'src>
    Conditional<'src, Item, NItems> for Scrutinee
where
    <Scrutinee as Matchable>::Pattern: MatchPatternParse<'src>,
{
    type Scrutinee = Scrutinee;
    fn if_parser(
        item_parser: impl ZngParser<'src, Item> + 'src,
    ) -> BoxedZngParser<'src, Condition<Scrutinee, Item, NItems>> {
        let block = block_for_many::<Item>(item_parser);
        let guard = guarded_block::<Scrutinee, Item, NItems>(block.clone());

        if_stmnt::<Scrutinee, Item, NItems>(guard, block)
            .map(|item| Condition::<Scrutinee, Item, NItems>::If(item))
            .boxed()
    }

    fn match_parser(
        item_parser: impl ZngParser<'src, Item> + 'src,
    ) -> BoxedZngParser<'src, Condition<Scrutinee, Item, NItems>> {
        let block = block_for_many::<Item>(item_parser.clone());
        match_stmt::<Scrutinee, Item, NItems>(block, item_parser)
            .map(|item| Condition::<Scrutinee, Item, NItems>::Match(item))
            .boxed()
    }
}