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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
use std::fmt::{self, Display};

use hashbrown::HashSet;
use silkworm_err::{Error, ErrorBuilder, ErrorCtx};

use crate::ast;
use crate::lex::{self, LexStream};
use crate::symbol::{Interner, Symbol};
use crate::token::{Kind as TokenKind, Token};
use crate::Span;

mod block;
mod expr;
mod list;
mod misc;
mod node;
mod pragma;
mod str;

#[derive(Debug)]
pub struct ParseCtx<'a> {
    pub errors: &'a ErrorCtx,
    pub interner: &'a mut Interner,
    pub source: &'a str,
    pub span_base: u32,
}

#[derive(Debug)]
struct Parser<'a, I> {
    token: Token,
    last_token: Token,
    expected_tokens: Vec<TokenKind>,
    token_stream: Lookahead<I>,
    ctx: ParseCtx<'a>,
}

type PResult<'a, T> = std::result::Result<T, &'a mut ErrorBuilder>;

impl<'a, I> Parser<'a, I>
where
    I: Iterator<Item = Token>,
{
    fn new(ctx: ParseCtx<'a>, token_stream: I) -> Self {
        let mut parser = Parser {
            token: Token::new(TokenKind::Unknown, Span::nil()),
            last_token: Token::new(TokenKind::Unknown, Span::nil()),
            expected_tokens: Vec::new(),
            token_stream: Lookahead::new(token_stream),
            ctx,
        };

        parser.bump();
        parser
    }

    fn bump(&mut self) -> Token {
        if self.token.kind == TokenKind::Eof {
            panic!("bump called after EOF");
        }

        self.last_token = self.token;

        while {
            self.token = match self.token_stream.next() {
                Some(token) => token,
                None => {
                    self.ctx
                        .errors
                        .bug("unexpected end of token stream")
                        .span(self.token.span);
                    Token::new(TokenKind::Eof, self.token.span)
                }
            };

            // Skip comments, whitespace, and unknown tokens
            match self.token.kind {
                TokenKind::Comment | TokenKind::Whitespace => true,
                TokenKind::Unknown => {
                    self.ctx
                        .errors
                        .error("unparsable characters")
                        .span(self.token.span);
                    true
                }
                _ => false,
            }
        } {}

        self.expected_tokens.clear();

        self.last_token
    }

    fn is_eof(&self) -> bool {
        self.token.kind == TokenKind::Eof
    }

    /// Returns `true` if `is_eof`, or there is only an `UnIndent` left.
    fn is_almost_eof(&mut self) -> bool {
        self.is_eof()
            || (self.check(TokenKind::UnIndent)
                && self.check_nth(0, TokenKind::Eof).unwrap_or(true))
    }

    fn is_end_of_line(&self) -> bool {
        match self.token.kind {
            TokenKind::LineBreak | TokenKind::Eof => true,
            _ => false,
        }
    }

    /// Checks if the current token matches `kind`. This adds the token to `expected_tokens`
    /// on failure.
    #[must_use]
    fn check(&mut self, kind: TokenKind) -> bool {
        let is_current = self.token.kind == kind;
        if !is_current {
            self.expected_tokens.push(kind);
        }
        is_current
    }

    /// Checks if the current token is a `Pragma` and returns the style if true. This adds
    /// the token to `expected_tokens` on failure.
    #[must_use]
    fn check_pragma(&mut self) -> Option<crate::token::PragmaStyle> {
        match self.token.kind {
            TokenKind::Pragma(style) => Some(style),
            _ => {
                use crate::token::PragmaStyle as Style;

                self.expected_tokens.extend(&[
                    TokenKind::Pragma(Style::Outer),
                    TokenKind::Pragma(Style::Inner),
                ]);

                None
            }
        }
    }

    /// Eats a token if it matches `kind` and returns it. This adds the token to
    /// `expected_tokens` on failure.
    #[must_use]
    fn eat(&mut self, kind: TokenKind) -> Option<Token> {
        if self.check(kind) {
            self.bump();
            Some(self.last_token)
        } else {
            None
        }
    }

    /// Eats an `Ident` and interns it, returning the symbol and span. This adds the token
    /// to `expected_tokens` on failure.
    #[must_use]
    fn eat_symbol(&mut self) -> Option<(Symbol, Option<crate::token::Keyword>, Span)> {
        let (ident_span, keyword) = match self.token.kind {
            TokenKind::Ident => (self.bump().span, None),
            TokenKind::Keyword(kw) => (self.bump().span, Some(kw)),
            _ => return None,
        };

        let symbol = self.ctx.intern_span(ident_span);

        Some((symbol, keyword, ident_span))
    }

    /// Eat all tokens until end of line, without consuming the terminating token.
    /// Returns the span of all tokens eaten this way, or `None` if there
    /// is none.
    fn eat_until_end_of_line(&mut self) -> Option<Span> {
        let (_, span): (Option<()>, _) = self.eat_until_with_or_end_of_line(|_| None);
        span
    }

    /// Eat all tokens until the given kind, including line-breaks, without consuming
    /// the terminating token. Returns the span of all tokens eaten this way, or `None` if there
    /// is none.
    fn eat_lines_until(&mut self, kind: TokenKind) -> Option<Span> {
        let mut span = None;

        while !self.is_eof() && self.token.kind != kind {
            let span = span.get_or_insert(self.token.span);
            *span = span.union(self.token.span);

            self.bump();
        }

        span
    }

    /// Eat all tokens until `op` returns `Some` or end of line, without consuming the
    /// terminating token if the latter. Returns the return value of `op`.
    ///
    /// The span returned is the span of all tokens eaten this way, or `None` if there
    /// is none.
    fn eat_until_with_or_end_of_line<F, U>(&mut self, mut op: F) -> (Option<U>, Option<Span>)
    where
        F: FnMut(&mut Self) -> Option<U>,
    {
        let mut span = None;

        loop {
            if let Some(ret) = op(self) {
                return (Some(ret), span);
            } else {
                match self.token.kind {
                    TokenKind::LineBreak | TokenKind::Eof => return (None, span),
                    _ => {}
                }
            }

            let span = span.get_or_insert(self.token.span);
            *span = span.union(self.token.span);

            self.bump();
        }
    }

    /// Parse using a method. If `parse` has failed, it will then eat all tokens until
    /// `terminator` or end of line, without consuming the terminator if found.
    fn parse_or_eat_till<F, U>(&mut self, terminator: TokenKind, parse: F) -> PResult<'a, U>
    where
        F: FnOnce(&mut Self) -> PResult<'a, U>,
    {
        parse(self).map_err(|err| {
            let (_, span) = self.eat_until_with_or_end_of_line(|p| {
                if p.check(terminator) {
                    Some(())
                } else {
                    None
                }
            });
            if let Some(span) = span {
                err.annotate_span(span, "extra tokens");
            }
            err
        })
    }

    fn parse_reinterpret<P: Parse>(
        &mut self,
        span: Span,
        block_mode: lex::BlockMode,
        inline_mode: lex::InlineMode,
    ) -> Result<P, ()> {
        let source = span.read(self.ctx.source, self.ctx.span_base);

        let errors = self.ctx.errors;

        let ctx = ParseCtx {
            errors,
            interner: &mut self.ctx.interner,
            source,
            span_base: span.base,
        };

        let lex_stream = lex::LexStream::with_modes(source, span.base, block_mode, inline_mode);

        P::parse_with_ctx(
            ctx,
            lex_stream.filter_map(|result| match result {
                Ok(tok) => Some(tok),
                Err(err) => {
                    errors.bug(format!("fatal lexer error: {}", err));
                    None
                }
            }),
        )
    }

    /// Peeks the nth token *after* the current token. Returns `None` if beyond EOF.
    fn peek_nth(&mut self, n: usize) -> Option<Token> {
        self.token_stream.peek_nth(n)
    }

    /// Checks if the nth token *after* the current token is of `kind`. Returns `None` if
    /// beyond EOF.
    fn check_nth(&mut self, n: usize, kind: TokenKind) -> Option<bool> {
        self.peek_nth(n).map(|tok| tok.kind == kind)
    }

    fn expect(&mut self, kind: TokenKind) -> &'a mut ErrorBuilder {
        self.expect_one_of(&[kind])
    }

    fn expect_one_of(&mut self, expected: &[TokenKind]) -> &'a mut ErrorBuilder {
        let mut expected = expected
            .iter()
            .copied()
            .chain(self.expected_tokens.drain(..))
            .collect::<HashSet<_>>()
            .into_iter()
            .collect::<Vec<_>>();

        expected.sort();

        if expected.is_empty() {
            panic!("must expect at least one token");
        }

        let actual = self.token.kind;

        let msg = if expected.len() == 1 {
            format!("expected {}, found {}", TokenChoice(&expected), actual)
        } else {
            format!(
                "expected one of {}, found {}",
                TokenChoice(&expected),
                actual
            )
        };

        self.ctx.errors.error(msg).span(self.token.span)
    }
}

#[derive(Copy, Clone, Debug, Default)]
struct TokenChoice<'a>(&'a [TokenKind]);

impl<'a> Display for TokenChoice<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut iter = self.0.iter();

        if let Some(first) = iter.next() {
            write!(f, "{}", first)?;
        } else {
            return Ok(());
        }

        for t in iter {
            write!(f, ", {}", t)?;
        }

        Ok(())
    }
}

impl<'a> ParseCtx<'a> {
    fn intern_span(&mut self, span: Span) -> Symbol {
        let sym = span.read(self.source, self.span_base);
        self.interner.intern(sym)
    }
}

const LOOKAHEAD: usize = 2;

#[derive(Debug)]
struct Lookahead<I> {
    iter: I,
    buf: arraydeque::ArrayDeque<[Token; LOOKAHEAD], arraydeque::behavior::Wrapping>,
}

impl<I> Iterator for Lookahead<I>
where
    I: Iterator<Item = Token>,
{
    type Item = Token;

    fn next(&mut self) -> Option<Self::Item> {
        self.buf.pop_front().or_else(|| self.iter.next())
    }
}

impl<I> Lookahead<I>
where
    I: Iterator<Item = Token>,
{
    fn new(iter: I) -> Self {
        Lookahead {
            iter,
            buf: Default::default(),
        }
    }

    /// Get the nth token, buffering these tokens from the underlying iterator when necessary.
    /// Returns `None` if the underlying stream is empty.
    fn peek_nth(&mut self, n: usize) -> Option<Token> {
        assert!(
            n < LOOKAHEAD,
            "n must be less than or equal to LOOKAHEAD = {}",
            LOOKAHEAD
        );
        self.fill_buf();
        self.buf.get(n).copied()
    }

    fn fill_buf(&mut self) {
        while {
            !self.buf.is_full() && {
                if let Some(tok) = self.iter.next() {
                    let is_not_full = self.buf.push_back(tok).is_none();
                    assert!(is_not_full, "buf should not be full");
                    true
                } else {
                    false
                }
            }
        } {}
    }
}

/// Trait for AST types that can be parsed.
pub trait Parse: Sized + private::Sealed {
    /// Default block mode to use when parsing from string sources.
    #[doc(hidden)]
    const SOURCE_BLOCK_MODE: lex::BlockMode;

    /// Default inline mode to use when parsing from string sources.
    #[doc(hidden)]
    const SOURCE_INLINE_MODE: lex::InlineMode;

    /// Parse an AST node with a shared parsing context. Errors are emitted into `ctx`.
    ///
    /// This emits an error if `partial` is `false` and the input is not completely consumed.
    fn partial_parse_with_ctx<I: IntoIterator<Item = Token>>(
        partial: bool,
        ctx: ParseCtx<'_>,
        token_stream: I,
    ) -> Result<Self, ()>;

    /// Parse an AST node with a shared parsing context. Errors are emitted into `ctx`.
    ///
    /// This emits an error if the input is not completely consumed.
    fn parse_with_ctx<I: IntoIterator<Item = Token>>(
        ctx: ParseCtx<'_>,
        token_stream: I,
    ) -> Result<Self, ()> {
        Self::partial_parse_with_ctx(false, ctx, token_stream)
    }

    /// Convenience method for parsing source without a shared context. Errors are returned
    /// in the `Err` variant.
    ///
    /// This emits an error if `partial` is `false` and the input is not completely consumed.
    ///
    /// # Errors
    ///
    /// If any errors are emitted by the parser.
    fn partial_parse_with_interner(
        partial: bool,
        source: &str,
        span_base: u32,
        interner: &mut Interner,
    ) -> Result<Self, Vec<Error>> {
        let errors = ErrorCtx::new();
        let lex_stream = LexStream::with_modes(
            source,
            span_base,
            Self::SOURCE_BLOCK_MODE,
            Self::SOURCE_INLINE_MODE,
        );

        let ast = Self::partial_parse_with_ctx(
            partial,
            ParseCtx {
                errors: &errors,
                interner,
                source,
                span_base,
            },
            lex_stream.filter_map(|result| match result {
                Ok(tok) => Some(tok),
                Err(err) => {
                    errors.bug(format!("fatal lexer error: {}", err));
                    None
                }
            }),
        );

        let errors = errors
            .into_vec()
            .into_iter()
            .map(ErrorBuilder::done)
            .collect::<Vec<_>>();

        ast.and_then(|ast| if errors.is_empty() { Ok(ast) } else { Err(()) })
            .map_err(|_| errors)
    }

    /// Convenience method for parsing source without a shared context. Errors are returned
    /// in the `Err` variant.
    ///
    /// This emits an error if the input is not completely consumed.
    ///
    /// # Errors
    ///
    /// If any errors are emitted by the parser.
    fn parse_with_interner(
        source: &str,
        span_base: u32,
        interner: &mut Interner,
    ) -> Result<Self, Vec<Error>> {
        Self::partial_parse_with_interner(false, source, span_base, interner)
    }

    /// Convenience method for parsing source without a shared context. Errors are returned
    /// in the `Err` variant.
    ///
    /// Symbols will be interned using a new interner, which will be returned on success.
    ///
    /// This emits an error if `partial` is `false` and the input is not completely consumed.
    ///
    /// # Errors
    ///
    /// If any errors are emitted by the parser.
    fn partial_parse(
        partial: bool,
        source: &str,
        span_base: u32,
    ) -> Result<(Self, Interner), Vec<Error>> {
        let mut interner = Interner::new();
        Self::partial_parse_with_interner(partial, source, span_base, &mut interner)
            .map(|ast| (ast, interner))
    }

    /// Convenience method for parsing source without a shared context. Errors are returned
    /// in the `Err` variant.
    ///
    /// Symbols will be interned using a new interner, which will be returned on success.
    ///
    /// This emits an error if the input is not completely consumed.
    ///
    /// # Errors
    ///
    /// If any errors are emitted by the parser.
    fn parse(source: &str, span_base: u32) -> Result<(Self, Interner), Vec<Error>> {
        Self::partial_parse(false, source, span_base)
    }
}

macro_rules! impl_parse {
    {
        $(
            impl Parse for ast::$ast_type:ident => $parse_method:ident {
                const SOURCE_BLOCK_MODE: lex::BlockMode = $block_mode:expr;
                const SOURCE_INLINE_MODE: lex::InlineMode = $inline_mode:expr;
                [ .. ]
            }
        )*
    } => {
        $(
            impl private::Sealed for ast::$ast_type {}
            impl Parse for ast::$ast_type {
                const SOURCE_BLOCK_MODE: lex::BlockMode = $block_mode;
                const SOURCE_INLINE_MODE: lex::InlineMode = $inline_mode;
                fn partial_parse_with_ctx<I: IntoIterator<Item = Token>>(
                    partial: bool,
                    ctx: ParseCtx<'_>,
                    token_stream: I,
                ) -> Result<Self, ()> {
                    let mut parser = Parser::new(ctx, token_stream.into_iter());
                    let result = parser.$parse_method().map_err(|_| ());
                    if !partial && !parser.is_eof() {
                        parser.expect(TokenKind::Eof);
                    }
                    result
                }
            }
        )*
    }
}

impl_parse! {
    impl Parse for ast::Path => parse_path {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::Interpolation;
        [ .. ]
    }
    impl Parse for ast::Pragma => parse_pragma {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Header;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::Meta;
        [ .. ]
    }
    impl Parse for ast::Meta => parse_meta {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Header;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::Meta;
        [ .. ]
    }
    impl Parse for ast::StrBody => parse_str_body {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::InterpolatedStringLiteral;
        [ .. ]
    }
    impl Parse for ast::StrSegment => parse_str_segment {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::InterpolatedStringLiteral;
        [ .. ]
    }
    impl Parse for ast::Text => parse_text {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::InterpolatedStringLiteral;
        [ .. ]
    }
    impl Parse for ast::Expr => parse_expr {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::Interpolation;
        [ .. ]
    }
    impl Parse for ast::FormatFunc => parse_format_func {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::FormatFunction;
        [ .. ]
    }
    impl Parse for ast::FormatFuncArg => parse_format_func_arg {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::FormatFunction;
        [ .. ]
    }
    impl Parse for ast::FormatFuncArgKey => parse_format_func_arg_key {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::FormatFunction;
        [ .. ]
    }
    impl Parse for ast::Var => parse_var {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::Interpolation;
        [ .. ]
    }
    impl Parse for ast::Lit => parse_lit {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::Interpolation;
        [ .. ]
    }
    impl Parse for ast::Stmt => parse_stmt {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::StartOfLine;
        [ .. ]
    }
    impl Parse for ast::StmtBody => parse_stmt_body {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::StartOfLine;
        [ .. ]
    }
    impl Parse for ast::Command => parse_command {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::Command;
        [ .. ]
    }
    impl Parse for ast::ShortcutOption => parse_shortcut_option {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::StartOfLine;
        [ .. ]
    }
    impl Parse for ast::Hashtag => parse_hashtag {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::Hashtag;
        [ .. ]
    }
    impl Parse for ast::Flow => parse_flow {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::OptionTextOrTarget;
        [ .. ]
    }
    impl Parse for ast::FlowTarget => parse_flow_target {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Body;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::OptionTarget;
        [ .. ]
    }
    impl Parse for ast::Node => parse_node {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Header;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::StartOfLine;
        [ .. ]
    }
    impl Parse for ast::NodeHeader => parse_node_header {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Header;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::HeaderKey;
        [ .. ]
    }
    impl Parse for ast::File => parse_file {
        const SOURCE_BLOCK_MODE: lex::BlockMode = lex::BlockMode::Header;
        const SOURCE_INLINE_MODE: lex::InlineMode = lex::InlineMode::StartOfLine;
        [ .. ]
    }
}

mod private {
    pub trait Sealed {}
}

#[cfg(test)]
mod test_utils {
    use super::*;

    // Use pretty_assertions for `assert_eq` diffs.
    use pretty_assertions::assert_eq;

    pub fn assert_partial_parse_with<T, F>(partial: bool, source: &str, op: F)
    where
        T: Parse,
        F: FnOnce(T, Interner) -> (),
    {
        let (ast, interner) = T::partial_parse(partial, source, 0).unwrap_or_else(|err| {
            panic!(
                "errors parsing source:```\n{}\n```\nerrors: {:#?}",
                source, err
            );
        });
        op(ast, interner);
    }

    pub fn assert_partial_parse<T, F>(partial: bool, source: &str, expected: F)
    where
        T: Parse + Eq + fmt::Debug,
        F: FnOnce(&mut Interner) -> T,
    {
        assert_partial_parse_with(partial, source, |ast, mut interner| {
            let expected = expected(&mut interner);
            assert_eq!(expected, ast);
        });
    }

    pub fn assert_parse<T, F>(source: &str, expected: F)
    where
        T: Parse + Eq + fmt::Debug,
        F: FnOnce(&mut Interner) -> T,
    {
        assert_partial_parse(false, source, expected)
    }
}