fatou-parser 0.10.0

Lossless CST parser, typed AST wrappers, and incremental reparser for the Julia language
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
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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
//! Typed navigation over documentation CST nodes.

use rowan::ast::AstNode;
use rowan::{TextRange, TextSize};

use super::syntax::{DocumentationLanguage, SyntaxKind, SyntaxNode, SyntaxToken};

macro_rules! ast_node {
    ($name:ident, $($kind:path)|+) => {
        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
        pub struct $name(SyntaxNode);

        impl AstNode for $name {
            type Language = DocumentationLanguage;

            fn can_cast(kind: SyntaxKind) -> bool {
                matches!(kind, $($kind)|+)
            }

            fn cast(syntax: SyntaxNode) -> Option<Self> {
                Self::can_cast(syntax.kind()).then_some(Self(syntax))
            }

            fn syntax(&self) -> &SyntaxNode {
                &self.0
            }
        }
    };
}

ast_node!(Document, SyntaxKind::ROOT);
ast_node!(Paragraph, SyntaxKind::PARAGRAPH);
ast_node!(
    Heading,
    SyntaxKind::ATX_HEADING | SyntaxKind::SETEXT_HEADING
);
ast_node!(BlockQuote, SyntaxKind::BLOCK_QUOTE);
ast_node!(Admonition, SyntaxKind::ADMONITION);
ast_node!(List, SyntaxKind::LIST);
ast_node!(ListItem, SyntaxKind::LIST_ITEM);
ast_node!(IndentedCodeBlock, SyntaxKind::INDENTED_CODE_BLOCK);
ast_node!(CodeBlock, SyntaxKind::FENCED_CODE_BLOCK);
ast_node!(MathBlock, SyntaxKind::MATH_BLOCK);
ast_node!(FootnoteDefinition, SyntaxKind::FOOTNOTE_DEFINITION);
ast_node!(Table, SyntaxKind::TABLE);
ast_node!(TableRow, SyntaxKind::TABLE_ROW);
ast_node!(TableCell, SyntaxKind::TABLE_CELL);
ast_node!(ThematicBreak, SyntaxKind::THEMATIC_BREAK);
ast_node!(Emphasis, SyntaxKind::EMPHASIS);
ast_node!(Strong, SyntaxKind::STRONG);
ast_node!(InlineCode, SyntaxKind::INLINE_CODE);
ast_node!(InlineMath, SyntaxKind::INLINE_MATH);
ast_node!(Link, SyntaxKind::LINK);
ast_node!(Image, SyntaxKind::IMAGE);
ast_node!(Autolink, SyntaxKind::AUTOLINK);
ast_node!(FootnoteReference, SyntaxKind::FOOTNOTE_REFERENCE);
ast_node!(Interpolation, SyntaxKind::INTERPOLATION);
ast_node!(HardBreak, SyntaxKind::HARD_BREAK);

/// A top-level documentation block.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Block {
    Paragraph(Paragraph),
    Heading(Heading),
    BlockQuote(BlockQuote),
    Admonition(Admonition),
    List(List),
    IndentedCodeBlock(IndentedCodeBlock),
    CodeBlock(CodeBlock),
    MathBlock(MathBlock),
    FootnoteDefinition(FootnoteDefinition),
    Table(Table),
    ThematicBreak(ThematicBreak),
    Interpolation(Interpolation),
    /// A recoverable or future block kind not yet covered by a typed wrapper.
    Other(SyntaxNode),
}

impl Block {
    fn cast(syntax: SyntaxNode) -> Self {
        match syntax.kind() {
            SyntaxKind::PARAGRAPH => Self::Paragraph(Paragraph(syntax)),
            SyntaxKind::ATX_HEADING | SyntaxKind::SETEXT_HEADING => Self::Heading(Heading(syntax)),
            SyntaxKind::BLOCK_QUOTE => Self::BlockQuote(BlockQuote(syntax)),
            SyntaxKind::ADMONITION => Self::Admonition(Admonition(syntax)),
            SyntaxKind::LIST => Self::List(List(syntax)),
            SyntaxKind::INDENTED_CODE_BLOCK => Self::IndentedCodeBlock(IndentedCodeBlock(syntax)),
            SyntaxKind::FENCED_CODE_BLOCK => Self::CodeBlock(CodeBlock(syntax)),
            SyntaxKind::MATH_BLOCK => Self::MathBlock(MathBlock(syntax)),
            SyntaxKind::FOOTNOTE_DEFINITION => Self::FootnoteDefinition(FootnoteDefinition(syntax)),
            SyntaxKind::TABLE => Self::Table(Table(syntax)),
            SyntaxKind::THEMATIC_BREAK => Self::ThematicBreak(ThematicBreak(syntax)),
            SyntaxKind::INTERPOLATION => Self::Interpolation(Interpolation(syntax)),
            _ => Self::Other(syntax),
        }
    }

    /// Return the underlying lossless node.
    pub fn syntax(&self) -> &SyntaxNode {
        match self {
            Self::Paragraph(node) => node.syntax(),
            Self::Heading(node) => node.syntax(),
            Self::BlockQuote(node) => node.syntax(),
            Self::Admonition(node) => node.syntax(),
            Self::List(node) => node.syntax(),
            Self::IndentedCodeBlock(node) => node.syntax(),
            Self::CodeBlock(node) => node.syntax(),
            Self::MathBlock(node) => node.syntax(),
            Self::FootnoteDefinition(node) => node.syntax(),
            Self::Table(node) => node.syntax(),
            Self::ThematicBreak(node) => node.syntax(),
            Self::Interpolation(node) => node.syntax(),
            Self::Other(node) => node,
        }
    }
}

impl Document {
    /// Iterate top-level blocks in source order.
    pub fn blocks(&self) -> impl Iterator<Item = Block> + '_ {
        self.syntax().children().map(Block::cast)
    }
}

/// An inline node or semantically relevant inline token.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Inline {
    Text(SyntaxToken),
    Escape(SyntaxToken),
    /// An en dash written as `--` in the source.
    EnDash(SyntaxToken),
    /// An em dash written as `---`, following Julia 1.13's Markdown dialect.
    EmDash(SyntaxToken),
    SoftBreak(SyntaxToken),
    Emphasis(Emphasis),
    Strong(Strong),
    Code(InlineCode),
    Math(InlineMath),
    Link(Link),
    Image(Image),
    Autolink(Autolink),
    FootnoteReference(FootnoteReference),
    Interpolation(Interpolation),
    HardBreak(HardBreak),
}

impl Paragraph {
    /// Iterate the paragraph's inline content in source order.
    pub fn inlines(&self) -> impl Iterator<Item = Inline> + '_ {
        inline_children(self.syntax())
    }
}

impl BlockQuote {
    /// Iterate blocks nested below the quote markers.
    pub fn blocks(&self) -> impl Iterator<Item = Block> + '_ {
        self.syntax().children().map(Block::cast)
    }
}

impl Heading {
    /// Return the heading level from one through six.
    pub fn level(&self) -> u8 {
        let marker = token(self.syntax(), SyntaxKind::HEADING_MARKER)
            .map(|token| token.text().to_string())
            .unwrap_or_default();
        if self.syntax().kind() == SyntaxKind::SETEXT_HEADING {
            if marker.trim_start().starts_with('=') {
                1
            } else {
                2
            }
        } else {
            marker.bytes().filter(|&byte| byte == b'#').count() as u8
        }
    }

    /// Return the visible heading content without its heading delimiters.
    pub fn content(&self) -> String {
        visible_text(self.syntax())
    }

    /// Iterate typed inline content in source order.
    pub fn inlines(&self) -> impl Iterator<Item = Inline> + '_ {
        inline_children(self.syntax())
    }

    /// Return the anchor slug Documenter derives from the heading content.
    ///
    /// Lowercased, with runs of whitespace collapsed to a single hyphen and
    /// every other non-word character dropped. Both the linter's exemption set
    /// and the server's navigation read anchors through this one definition.
    pub fn slug(&self) -> String {
        slug(&self.content())
    }
}

/// Derive a Documenter anchor slug from heading content.
pub fn slug(heading: &str) -> String {
    let mut out = String::new();
    let mut separator = false;
    for character in heading.chars().flat_map(char::to_lowercase) {
        if character.is_alphanumeric() || character == '_' || character == '-' {
            if separator && !out.is_empty() && !out.ends_with('-') {
                out.push('-');
            }
            out.push(character);
            separator = false;
        } else if character.is_whitespace() {
            separator = true;
        }
    }
    out.trim_end_matches('-').to_string()
}

impl Admonition {
    /// Return the admonition category following `!!!`.
    pub fn category(&self) -> String {
        token(self.syntax(), SyntaxKind::ADMONITION_CATEGORY)
            .map(|token| token.text().to_string())
            .unwrap_or_default()
    }

    /// Return the explicit title, without quotes, or Julia's default title.
    pub fn title(&self) -> String {
        token(self.syntax(), SyntaxKind::ADMONITION_TITLE).map_or_else(
            || uppercase_first(&self.category()),
            |token| token.text().trim_matches('"').to_string(),
        )
    }

    /// Iterate Markdown blocks nested in the admonition body.
    pub fn blocks(&self) -> impl Iterator<Item = Block> + '_ {
        self.syntax().children().map(Block::cast)
    }
}

impl List {
    /// Iterate list items in source order.
    pub fn items(&self) -> impl Iterator<Item = ListItem> + '_ {
        self.syntax().children().filter_map(ListItem::cast)
    }

    /// Return the first ordinal, or `None` for an unordered list.
    pub fn ordered_start(&self) -> Option<u64> {
        nested_token(self.syntax(), SyntaxKind::LIST_MARKER)?
            .text()
            .trim_end_matches(['.', ')'])
            .parse()
            .ok()
    }

    /// Whether a blank line makes this a loose list in Julia Markdown.
    pub fn is_loose(&self) -> bool {
        self.syntax()
            .descendants_with_tokens()
            .filter_map(|element| element.into_token())
            .any(|token| token.kind() == SyntaxKind::BLANK_LINE)
    }
}

impl ListItem {
    /// Iterate the item's direct inline content.
    pub fn inlines(&self) -> impl Iterator<Item = Inline> + '_ {
        inline_children(self.syntax())
    }

    /// Iterate blocks nested below this item, such as sublists.
    pub fn blocks(&self) -> impl Iterator<Item = Block> + '_ {
        self.syntax().children().map(Block::cast)
    }
}

impl CodeBlock {
    /// Return the trimmed fence info string.
    pub fn info(&self) -> String {
        token(self.syntax(), SyntaxKind::INFO_STRING)
            .map(|token| token.text().trim().to_string())
            .unwrap_or_default()
    }

    /// Return the code body using Julia Markdown's trailing-newline chomp.
    pub fn content(&self) -> String {
        let mut content = String::new();
        for token in self
            .syntax()
            .children_with_tokens()
            .filter_map(|element| element.into_token())
        {
            if token.kind() == SyntaxKind::CODE_CONTENT {
                content.push_str(token.text());
            }
        }
        content.trim_end_matches(['\r', '\n']).to_string()
    }

    /// Return the decoded-text range covering the code body.
    ///
    /// In a container, the range includes its prefixes on continuation
    /// lines. Individual `CODE_CONTENT` tokens exclude those prefixes and
    /// preserve exact ranges for consumers of [`Self::content`].
    pub fn content_range(&self) -> Option<TextRange> {
        let mut tokens = self
            .syntax()
            .children_with_tokens()
            .filter_map(|element| element.into_token())
            .filter(|token| token.kind() == SyntaxKind::CODE_CONTENT);
        let first = tokens.next()?.text_range();
        Some(TextRange::new(
            first.start(),
            tokens
                .last()
                .map_or(first.end(), |token| token.text_range().end()),
        ))
    }

    /// Classify ordinary Julia and Documenter fence info strings locally.
    pub fn fence_kind(&self) -> FenceKind {
        classify_fence(&self.info())
    }
}

impl IndentedCodeBlock {
    /// Return code after removing Julia Markdown's four-column block indent.
    pub fn content(&self) -> String {
        let mut out = String::new();
        for token in self
            .syntax()
            .descendants_with_tokens()
            .filter_map(|element| element.into_token())
        {
            if matches!(token.kind(), SyntaxKind::CODE_CONTENT | SyntaxKind::NEWLINE) {
                out.push_str(token.text());
            }
        }
        out.trim_end_matches(['\r', '\n']).to_string()
    }
}

impl MathBlock {
    /// Return the math formula without block delimiters or its final newline.
    pub fn content(&self) -> String {
        let mut content = String::new();
        for token in self
            .syntax()
            .children_with_tokens()
            .filter_map(|element| element.into_token())
        {
            if token.kind() == SyntaxKind::MATH_CONTENT {
                content.push_str(token.text());
            }
        }
        content.trim_end_matches(['\r', '\n']).to_string()
    }
}

impl FootnoteDefinition {
    /// Return the definition identifier without `[^` and `]:`.
    pub fn id(&self) -> String {
        token(self.syntax(), SyntaxKind::FOOTNOTE_LABEL)
            .map(|token| {
                token
                    .text()
                    .strip_prefix("[^")
                    .and_then(|text| text.strip_suffix("]:"))
                    .unwrap_or(token.text())
                    .to_string()
            })
            .unwrap_or_default()
    }

    /// Iterate Markdown blocks belonging to the footnote body.
    pub fn blocks(&self) -> impl Iterator<Item = Block> + '_ {
        self.syntax().children().map(Block::cast)
    }
}

impl Table {
    /// Iterate source rows, including the delimiter row at index one.
    pub fn rows(&self) -> impl Iterator<Item = TableRow> + '_ {
        self.syntax().children().filter_map(TableRow::cast)
    }
}

impl TableRow {
    /// Iterate row cells in source order.
    pub fn cells(&self) -> impl Iterator<Item = TableCell> + '_ {
        self.syntax().children().filter_map(TableCell::cast)
    }
}

impl TableCell {
    /// Iterate cell inline content in source order.
    pub fn inlines(&self) -> impl Iterator<Item = Inline> + '_ {
        inline_children(self.syntax())
    }
}

impl InlineCode {
    /// Return the code without delimiters, joining wrapped lines with spaces.
    pub fn content(&self) -> String {
        inline_payload(self.syntax(), SyntaxKind::CODE_CONTENT)
    }
}

impl InlineMath {
    /// Return the formula without delimiters, joining wrapped lines with spaces.
    pub fn content(&self) -> String {
        inline_payload(self.syntax(), SyntaxKind::MATH_CONTENT)
    }
}

impl Link {
    /// Return the link destination, joining paragraph continuations with spaces.
    pub fn destination(&self) -> String {
        payload_text(self.syntax(), SyntaxKind::LINK_DESTINATION)
    }

    /// Return the decoded-text range covering the destination inside `(…)`.
    ///
    /// Wrapped destinations include the intervening newline and container
    /// prefixes. Individual `LINK_DESTINATION` tokens exclude those prefixes.
    pub fn destination_range(&self) -> Option<TextRange> {
        let mut tokens = payload_tokens(self.syntax(), SyntaxKind::LINK_DESTINATION);
        let first = tokens.next()?.text_range();
        Some(TextRange::new(
            first.start(),
            tokens
                .last()
                .map_or(first.end(), |token| token.text_range().end()),
        ))
    }

    /// Iterate the link label's inline content.
    pub fn label(&self) -> impl Iterator<Item = Inline> + '_ {
        inline_children(self.syntax())
    }
}

impl Image {
    /// Return the image's alternative text.
    pub fn alt(&self) -> String {
        payload_text(self.syntax(), SyntaxKind::TEXT)
    }

    /// Return the image destination, joining wrapped lines with spaces.
    pub fn destination(&self) -> String {
        payload_text(self.syntax(), SyntaxKind::LINK_DESTINATION)
    }
}

impl Autolink {
    /// Return the destination between angle brackets.
    pub fn destination(&self) -> String {
        payload_text(self.syntax(), SyntaxKind::LINK_DESTINATION)
    }
}

impl FootnoteReference {
    /// Return the reference identifier without `[^` and `]`.
    pub fn id(&self) -> String {
        token(self.syntax(), SyntaxKind::FOOTNOTE_LABEL)
            .map(|token| {
                token
                    .text()
                    .strip_prefix("[^")
                    .and_then(|text| text.strip_suffix(']'))
                    .unwrap_or(token.text())
                    .to_string()
            })
            .unwrap_or_default()
    }
}

impl Interpolation {
    /// Return the unevaluated Julia expression text after `$`.
    pub fn expression(&self) -> String {
        payload_text(self.syntax(), SyntaxKind::TEXT)
    }
}

/// A statically recognized fenced-code role.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FenceKind {
    Plain,
    Julia,
    JuliaRepl,
    JlDoctest {
        label: Option<String>,
        options: Option<String>,
    },
    Documenter {
        directive: DocumenterDirective,
        arguments: Option<String>,
    },
    DocumenterExtension {
        directive: String,
        arguments: Option<String>,
    },
    Other(String),
}

impl FenceKind {
    /// Whether the fence declares content that Documenter treats as Julia code.
    pub fn contains_julia(&self) -> bool {
        match self {
            Self::Julia | Self::JuliaRepl | Self::JlDoctest { .. } => true,
            Self::Documenter { directive, .. } => !matches!(directive, DocumenterDirective::Raw),
            Self::Plain | Self::DocumenterExtension { .. } | Self::Other(_) => false,
        }
    }
}

/// Core fenced directives documented by Documenter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DocumenterDirective {
    Docs,
    Autodocs,
    Meta,
    Index,
    Contents,
    Example,
    Repl,
    Setup,
    Eval,
    Raw,
}

impl Link {
    /// Return Documenter link metadata for an `@ref`, `@id`, or extension URL.
    pub fn documenter_link(&self) -> Option<DocumenterLink> {
        let text = self.destination();
        let destination = self.syntax().clone();
        text.trim_start()
            .starts_with('@')
            .then_some(DocumenterLink { destination, text })
    }
}

/// A Documenter-style link destination with its decoded source ranges.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DocumenterLink {
    destination: SyntaxNode,
    text: String,
}

impl DocumenterLink {
    /// Return the core or extension link kind.
    pub fn kind(&self) -> DocumenterLinkKind<'_> {
        let (name, _) = split_at_word(self.text.trim());
        match name {
            "@ref" => DocumenterLinkKind::Ref,
            "@id" => DocumenterLinkKind::Id,
            other => DocumenterLinkKind::Extension(other.trim_start_matches('@')),
        }
    }

    /// Return an explicit target. `None` means Documenter infers it from the label.
    pub fn target(&self) -> Option<&str> {
        let (_, rest) = split_at_word(self.text.trim());
        (!rest.is_empty()).then_some(rest)
    }

    /// Return the explicit target's decoded-text range.
    pub fn target_range(&self) -> Option<TextRange> {
        let raw = &self.text;
        let trimmed_start = raw.len() - raw.trim_start().len();
        let trimmed = raw.trim();
        let name_end = trimmed.find(char::is_whitespace)?;
        let target_start =
            name_end + trimmed[name_end..].len() - trimmed[name_end..].trim_start().len();
        if target_start >= trimmed.len() {
            return None;
        }
        let target_end = trimmed.trim_end().len();
        payload_range(
            &self.destination,
            SyntaxKind::LINK_DESTINATION,
            trimmed_start + target_start,
            trimmed_start + target_end,
        )
    }
}

/// The directive carried by a Documenter-style link destination.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DocumenterLinkKind<'a> {
    Ref,
    Id,
    Extension(&'a str),
}

fn classify_fence(info: &str) -> FenceKind {
    if info.is_empty() {
        return FenceKind::Plain;
    }
    if info == "julia" {
        return FenceKind::Julia;
    }
    if info == "julia-repl" {
        return FenceKind::JuliaRepl;
    }
    if info == "jldoctest"
        || info
            .strip_prefix("jldoctest")
            .is_some_and(|rest| rest.starts_with(|ch: char| ch.is_whitespace() || ch == ';'))
    {
        let rest = info.strip_prefix("jldoctest").unwrap().trim();
        let (label, options) = split_label_options(rest);
        return FenceKind::JlDoctest {
            label: nonempty(label),
            options: nonempty(options),
        };
    }
    if let Some(at) = info.strip_prefix('@') {
        let name_end = at
            .find(|ch: char| ch.is_whitespace() || ch == ';')
            .unwrap_or(at.len());
        let name = &at[..name_end];
        let arguments = nonempty(at[name_end..].trim().trim_start_matches(';').trim());
        let directive = match name {
            "docs" => Some(DocumenterDirective::Docs),
            "autodocs" => Some(DocumenterDirective::Autodocs),
            "meta" => Some(DocumenterDirective::Meta),
            "index" => Some(DocumenterDirective::Index),
            "contents" => Some(DocumenterDirective::Contents),
            "example" => Some(DocumenterDirective::Example),
            "repl" => Some(DocumenterDirective::Repl),
            "setup" => Some(DocumenterDirective::Setup),
            "eval" => Some(DocumenterDirective::Eval),
            "raw" => Some(DocumenterDirective::Raw),
            _ => None,
        };
        return match directive {
            Some(directive) => FenceKind::Documenter {
                directive,
                arguments,
            },
            None => FenceKind::DocumenterExtension {
                directive: name.to_string(),
                arguments,
            },
        };
    }
    FenceKind::Other(info.to_string())
}

fn split_label_options(rest: &str) -> (&str, &str) {
    match rest.split_once(';') {
        Some((label, options)) => (label.trim(), options.trim()),
        None => (rest.trim(), ""),
    }
}

fn nonempty(text: &str) -> Option<String> {
    (!text.is_empty()).then(|| text.to_string())
}

fn split_at_word(text: &str) -> (&str, &str) {
    match text.find(char::is_whitespace) {
        Some(index) => (&text[..index], text[index..].trim()),
        None => (text, ""),
    }
}

/// Find a node's own `kind` token.
///
/// Direct children only: a link label may itself contain a link or an image,
/// and a descendant search would then answer with the nested node's
/// destination rather than this one's.
fn token(node: &SyntaxNode, kind: SyntaxKind) -> Option<SyntaxToken> {
    node.children_with_tokens()
        .filter_map(|element| element.into_token())
        .find(|token| token.kind() == kind)
}

/// Find the first `kind` token anywhere below `node`.
fn nested_token(node: &SyntaxNode, kind: SyntaxKind) -> Option<SyntaxToken> {
    node.descendants_with_tokens()
        .filter_map(|element| element.into_token())
        .find(|token| token.kind() == kind)
}

fn visible_text(node: &SyntaxNode) -> String {
    let mut out = String::new();
    for token in node
        .descendants_with_tokens()
        .filter_map(|element| element.into_token())
    {
        match token.kind() {
            SyntaxKind::TEXT | SyntaxKind::CODE_CONTENT | SyntaxKind::MATH_CONTENT => {
                out.push_str(token.text())
            }
            SyntaxKind::ESCAPE => out.push_str(token.text().trim_start_matches('\\')),
            SyntaxKind::EN_DASH => out.push('–'),
            SyntaxKind::EM_DASH => out.push('—'),
            SyntaxKind::SOFT_BREAK => out.push(' '),
            _ => {}
        }
    }
    out.trim().to_string()
}

fn inline_children(node: &SyntaxNode) -> impl Iterator<Item = Inline> + '_ {
    node.children_with_tokens()
        .filter_map(|element| match element {
            rowan::NodeOrToken::Token(token) => match token.kind() {
                SyntaxKind::TEXT => Some(Inline::Text(token)),
                SyntaxKind::ESCAPE => Some(Inline::Escape(token)),
                SyntaxKind::EN_DASH => Some(Inline::EnDash(token)),
                SyntaxKind::EM_DASH => Some(Inline::EmDash(token)),
                SyntaxKind::SOFT_BREAK => Some(Inline::SoftBreak(token)),
                _ => None,
            },
            rowan::NodeOrToken::Node(node) => match node.kind() {
                SyntaxKind::EMPHASIS => Some(Inline::Emphasis(Emphasis(node))),
                SyntaxKind::STRONG => Some(Inline::Strong(Strong(node))),
                SyntaxKind::INLINE_CODE => Some(Inline::Code(InlineCode(node))),
                SyntaxKind::INLINE_MATH => Some(Inline::Math(InlineMath(node))),
                SyntaxKind::LINK => Some(Inline::Link(Link(node))),
                SyntaxKind::IMAGE => Some(Inline::Image(Image(node))),
                SyntaxKind::AUTOLINK => Some(Inline::Autolink(Autolink(node))),
                SyntaxKind::FOOTNOTE_REFERENCE => {
                    Some(Inline::FootnoteReference(FootnoteReference(node)))
                }
                SyntaxKind::INTERPOLATION => Some(Inline::Interpolation(Interpolation(node))),
                SyntaxKind::HARD_BREAK => Some(Inline::HardBreak(HardBreak(node))),
                _ => None,
            },
        })
}

fn inline_payload(node: &SyntaxNode, kind: SyntaxKind) -> String {
    payload_text(node, kind).trim().to_string()
}

fn payload_tokens(node: &SyntaxNode, kind: SyntaxKind) -> impl Iterator<Item = SyntaxToken> + '_ {
    node.children_with_tokens()
        .filter_map(|element| element.into_token())
        .filter(move |token| token.kind() == kind || token.kind() == SyntaxKind::NEWLINE)
}

fn payload_text(node: &SyntaxNode, kind: SyntaxKind) -> String {
    let mut out = String::new();
    for token in payload_tokens(node, kind) {
        if token.kind() == SyntaxKind::NEWLINE {
            out.push('\n');
        } else if matches!(token.text(), "\n" | "\r\n") {
            out.push(' ');
        } else {
            out.push_str(token.text());
        }
    }
    out
}

fn payload_range(
    node: &SyntaxNode,
    kind: SyntaxKind,
    start: usize,
    end: usize,
) -> Option<TextRange> {
    let mut offset = 0;
    let mut source_start = None;
    for token in payload_tokens(node, kind) {
        let length = if matches!(token.text(), "\n" | "\r\n") {
            1
        } else {
            token.text().len()
        };
        if source_start.is_none() && start < offset + length {
            source_start =
                Some(token.text_range().start() + TextSize::from((start - offset) as u32));
        }
        if end <= offset + length {
            let source_end = if end == offset + length {
                token.text_range().end()
            } else {
                token.text_range().start() + TextSize::from((end - offset) as u32)
            };
            return Some(TextRange::new(source_start?, source_end));
        }
        offset += length;
    }
    None
}

fn uppercase_first(text: &str) -> String {
    let mut chars = text.chars();
    chars
        .next()
        .map(char::to_uppercase)
        .into_iter()
        .flatten()
        .collect::<String>()
        + chars.as_str()
}