rotext_core 0.2.0

The core (no_std) part of the official and de facto Rotext parser.
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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
mod line;
mod parser_inner;
mod stack_wrapper;
mod state;
mod types;
mod utils;

#[cfg(test)]
mod test_support;

pub use stack_wrapper::StackEntry;

use crate::{
    common::m,
    events::{ev, ThematicBreak},
    internal_utils::string::count_continuous_character,
    types::{cast_tym, Stack, Tym, TYM_UNIT},
    Event,
};

use state::{
    Exiting, ExitingAndThen, ExitingUntil, Expecting, ItemLikesState,
    ItemLikesStateMatchingLastLine, State,
};

use parser_inner::ParserInner;
use stack_wrapper::{
    GeneralItemLike, ItemLikeContainer, Meta, StackEntryItemLike, StackEntryItemLikeContainer,
    StackEntryTable, TopLeaf, TopLeafCodeBlock, TopLeafHeading, TopLeafParagraph,
};
use types::{CursorContext, YieldContext};

pub struct Parser<'a, TStack: Stack<StackEntry>> {
    input: &'a [u8],
    state: State,
    inner: ParserInner<TStack>,
    /// 其实只有在 `state` 为 [Expecting::ItemLikeOpening] 时有效,但将
    /// [ItemLikesState] 作为 [Expecting::ItemLikeOpening] 的字段并不是很可行。之后有
    /// 函数既需要传入 `&mut state`,又需要知道 `expecting` 的值是什么,而现在的
    /// [Expecting] 各分支都没有字段,[Copy] 起来很便宜。如果将
    /// [ItemLikesState] 作为 [Expecting::ItemLikeOpening] 的字段,开销一下子上来了。
    item_likes_state: ItemLikesState,

    #[cfg(debug_assertions)]
    is_errored: bool,
}

impl<'a, TStack: Stack<StackEntry>> Parser<'a, TStack> {
    pub fn new(input: &'a [u8]) -> Self {
        Self {
            input,
            state: Expecting::ItemLikeOpening.into(),
            inner: ParserInner::new(),
            item_likes_state: ItemLikesState::ProcessingNew,

            #[cfg(debug_assertions)]
            is_errored: false,
        }
    }

    #[inline(always)]
    fn parse(&mut self, mut expecting: Expecting) -> crate::Result<Tym<5>> {
        let spaces = count_continuous_character(self.input, b' ', self.inner.cursor());
        if spaces > 0 {
            self.inner.move_cursor_forward(spaces);
            self.inner.current_expecting.set_spaces_before(spaces);
        }

        let Some(&first_char) = self.input.get(self.inner.cursor()) else {
            self.state = if self.inner.stack.is_empty() {
                State::Ended
            } else {
                Exiting::new(ExitingUntil::StackIsEmpty, ExitingAndThen::End).into()
            };

            return Ok(TYM_UNIT.into());
        };

        loop {
            match expecting {
                Expecting::ItemLikeOpening => {
                    if !self
                        .item_likes_state
                        .has_unprocessed_item_likes_at_current_line()
                        && self.inner.stack.is_top_leaf_some()
                    {
                        expecting = Expecting::LeafContent;
                        self.state = expecting.into();
                        continue;
                    }
                    break branch::item_like::parse_opening_and_process(
                        self.input,
                        &mut self.state,
                        &mut self.inner,
                        &mut self.item_likes_state,
                        first_char,
                    )
                    .map(|tym| cast_tym!(tym));
                }
                Expecting::BracedOpening => {
                    if self.inner.stack.is_top_leaf_some() {
                        expecting = Expecting::LeafContent;
                        self.state = expecting.into();
                        continue;
                    }
                    break branch::braced::parse_opening_and_process(
                        self.input,
                        &mut self.state,
                        &mut self.inner,
                        first_char,
                    )
                    .map(|tym| cast_tym!(tym));
                }
                Expecting::LeafContent => {
                    if let Some(top_leaf) = self.inner.stack.pop_top_leaf() {
                        break leaf::parse_content_and_process(
                            self.input,
                            &mut self.state,
                            &mut self.inner,
                            top_leaf,
                        )
                        .map(|tym| cast_tym!(tym));
                    }
                    break leaf::parse_opening_and_process(
                        self.input,
                        &mut self.state,
                        &mut self.inner,
                        first_char,
                    )
                    .map(|tym| cast_tym!(tym));
                }
            }
        }
    }

    fn exit(
        inner: &mut ParserInner<TStack>,
        item_likes_state: &mut ItemLikesState,
        exiting: &mut Exiting,
    ) -> crate::Result<(Tym<3>, Option<State>)> {
        if let Some(top_leaf) = inner.stack.pop_top_leaf() {
            let tym: Tym<2> = match top_leaf {
                TopLeaf::Paragraph(top_leaf) => leaf::paragraph::exit(inner, top_leaf).into(),
                TopLeaf::Heading(top_leaf) => leaf::heading::exit(inner, top_leaf).into(),
                TopLeaf::CodeBlock(top_leaf) => leaf::code_block::exit(inner, top_leaf),
            };
            return Ok((cast_tym!(tym), None));
        }

        // 是属于 `Block` 分组的事件。
        let mut to_be_yielded_based_on_context: Option<Event> = None;

        let (is_done, should_exit_top) = match exiting.until {
            ExitingUntil::OnlyNItemLikesRemain {
                n,
                should_also_exit_containee_in_last_container,
            } => {
                debug_assert!(inner.stack.item_likes_in_stack() >= n);
                let mut is_done = inner.stack.item_likes_in_stack() == n;
                if should_also_exit_containee_in_last_container {
                    is_done = is_done && inner.stack.top_is_item_like_container();
                }
                (is_done, !is_done)
            }
            ExitingUntil::TopIsTable {
                should_also_exit_table,
            } => (inner.stack.top_is_table(), should_also_exit_table),
            ExitingUntil::TopIsAwareOfDoublePipes => {
                if inner.stack.top_is_table() {
                    to_be_yielded_based_on_context = Some(ev!(Block, IndicateTableDataCell));
                    (true, false)
                } else {
                    (false, true)
                }
            }
            ExitingUntil::StackIsEmpty => {
                let is_done = inner.stack.is_empty();
                (is_done, !is_done)
            }
        };

        let tym_a = if should_exit_top {
            match inner.stack.pop().unwrap() {
                StackEntry::ItemLike(stack_entry) => branch::item_like::exit(inner, stack_entry)?,
                StackEntry::ItemLikeContainer(stack_entry) => {
                    branch::item_like::exit_container(inner, stack_entry)?
                }
                StackEntry::Table(stack_entry) => branch::braced::table::exit(inner, stack_entry)?,
            }
        } else {
            TYM_UNIT.into()
        };

        let (tym_b, new_state) = if is_done {
            debug_assert!(exiting.and_then.is_some());
            let and_then = unsafe { exiting.and_then.take().unwrap_unchecked() };
            #[cfg(debug_assertions)]
            {
                if !matches!(
                    and_then,
                    ExitingAndThen::YieldBasedOnContextAndExpectBracedOpening
                ) {
                    assert!(to_be_yielded_based_on_context.is_none());
                }
            }
            match and_then {
                ExitingAndThen::EnterItemLikeAndExpectItemLike {
                    container,
                    item_like,
                } => {
                    let tym_a = if let Some(container) = container {
                        let ev = container.make_enter_event();
                        inner.stack.push_item_like_container(container)?;
                        inner.r#yield(ev)
                    } else {
                        TYM_UNIT.into()
                    };
                    let tym_b = {
                        let ev = item_like.make_enter_event();
                        inner.stack.push_item_like(item_like)?;
                        inner.r#yield(ev)
                    };
                    *item_likes_state = ItemLikesState::ProcessingNew;
                    (tym_a.add(tym_b), Some(Expecting::ItemLikeOpening.into()))
                }
                ExitingAndThen::ExpectBracedOpening => {
                    (TYM_UNIT.into(), Some(Expecting::BracedOpening.into()))
                }
                ExitingAndThen::YieldAndExpectBracedOpening(ev) => (
                    inner.r#yield(ev).into(),
                    Some(Expecting::BracedOpening.into()),
                ),
                ExitingAndThen::YieldBasedOnContextAndExpectBracedOpening => {
                    debug_assert!(to_be_yielded_based_on_context.is_some());
                    (
                        inner
                            .r#yield(unsafe { to_be_yielded_based_on_context.unwrap_unchecked() })
                            .into(),
                        Some(Expecting::BracedOpening.into()),
                    )
                }
                ExitingAndThen::End => (TYM_UNIT.into(), Some(State::Ended)),
            }
        } else {
            debug_assert!(to_be_yielded_based_on_context.is_none());
            (TYM_UNIT.into(), None)
        };

        Ok((tym_a.add(tym_b), new_state))
    }
}

impl<TStack: Stack<StackEntry>> Iterator for Parser<'_, TStack> {
    /// 承载的事件属于 `Block` 分组。
    type Item = crate::Result<Event>;

    fn next(&mut self) -> Option<Self::Item> {
        #[cfg(debug_assertions)]
        {
            assert!(!self.is_errored);
        }
        debug_assert!(!matches!(self.state, State::Ended));

        loop {
            if let Some(ev) = self.inner.pop_to_be_yielded() {
                break Some(Ok(ev));
            }

            let result: crate::Result<Tym<5>> = match &mut self.state {
                State::Exiting(exiting_branches) => match Self::exit(
                    &mut self.inner,
                    &mut self.item_likes_state,
                    exiting_branches,
                ) {
                    Ok((tym, state)) => {
                        if let Some(state) = state {
                            self.state = state;
                        }
                        Ok(tym)
                    }
                    Err(err) => Err(err),
                }
                .map(|tym| cast_tym!(tym)),
                State::Ended => {
                    break None;
                }
                State::Expecting(expecting) => {
                    if self.inner.stack.should_reset_state() {
                        self.inner.stack.reset_should_reset_state();
                        let item_likes_in_stack_at_last_line =
                            self.inner.stack.item_likes_in_stack();
                        *expecting = Expecting::ItemLikeOpening;
                        self.item_likes_state = if item_likes_in_stack_at_last_line > 0 {
                            ItemLikesStateMatchingLastLine::new(item_likes_in_stack_at_last_line)
                                .into()
                        } else {
                            ItemLikesState::ProcessingNew
                        };
                    }
                    self.inner.reset_current_expecting();

                    let expecting = *expecting;
                    self.parse(expecting)
                }
            };
            match result {
                Ok(tym) => self.inner.enforce_to_yield_mark(tym),
                Err(err) => {
                    #[cfg(debug_assertions)]
                    {
                        self.is_errored = true;
                    }
                    break Some(Err(err));
                }
            }
        }
    }
}

mod branch {
    use super::*;

    pub mod item_like {
        use super::*;

        pub fn parse_opening_and_process<TStack: Stack<StackEntry>>(
            input: &[u8],
            state: &mut State,
            inner: &mut ParserInner<TStack>,
            item_likes_state: &mut ItemLikesState,
            first_char: u8,
        ) -> crate::Result<Tym<5>> {
            use GeneralItemLike as I;
            use ItemLikeContainer as G;

            match first_char {
                m!('>') if is_indeed_opening_and_consume_if_true(input, inner) => {
                    process_greater_than_opening(inner, item_likes_state).map(|tym| cast_tym!(tym))
                }
                m!('#') if is_indeed_opening_and_consume_if_true(input, inner) => {
                    process_general_opening(state, inner, item_likes_state, G::OL, I::LI)
                        .map(|tym| cast_tym!(tym))
                }
                m!('*') if is_indeed_opening_and_consume_if_true(input, inner) => {
                    process_general_opening(state, inner, item_likes_state, G::UL, I::LI)
                        .map(|tym| cast_tym!(tym))
                }
                m!(';') if is_indeed_opening_and_consume_if_true(input, inner) => {
                    process_general_opening(state, inner, item_likes_state, G::DL, I::DT)
                        .map(|tym| cast_tym!(tym))
                }
                m!(':') if is_indeed_opening_and_consume_if_true(input, inner) => {
                    process_general_opening(state, inner, item_likes_state, G::DL, I::DD)
                        .map(|tym| cast_tym!(tym))
                }
                _ => match item_likes_state {
                    ItemLikesState::MatchingLastLine(matching_last_line) => {
                        *state = Exiting::new(
                            ExitingUntil::OnlyNItemLikesRemain {
                                n: matching_last_line.processed_item_likes(),
                                should_also_exit_containee_in_last_container: false,
                            },
                            ExitingAndThen::ExpectBracedOpening,
                        )
                        .into();
                        Ok(TYM_UNIT.into())
                    }
                    ItemLikesState::ProcessingNew => {
                        *state = State::Expecting(Expecting::BracedOpening);
                        braced::parse_opening_and_process(input, state, inner, first_char)
                            .map(|tym| cast_tym!(tym))
                    }
                },
            }
        }

        fn process_greater_than_opening<TStack: Stack<StackEntry>>(
            inner: &mut ParserInner<TStack>,
            item_likes_state: &mut ItemLikesState,
        ) -> crate::Result<Tym<1>> {
            let tym = match item_likes_state {
                ItemLikesState::MatchingLastLine(matching_last_line) => {
                    let is_all_processed = matching_last_line
                        .mark_first_unprocessed_item_like_as_processed_at_current_line(
                            &inner.stack,
                        );
                    if is_all_processed {
                        *item_likes_state = ItemLikesState::ProcessingNew;
                    }
                    TYM_UNIT.into()
                }
                ItemLikesState::ProcessingNew => {
                    let id = inner.pop_block_id();
                    inner
                        .stack
                        .push_item_like_container(StackEntryItemLikeContainer {
                            meta: Meta::new(id, inner.current_line()),
                            r#type: ItemLikeContainer::BlockQuote,
                        })?;
                    inner.r#yield(ev!(Block, EnterBlockQuote(id.into())))
                }
            };

            Ok(tym)
        }

        fn process_general_opening<TStack: Stack<StackEntry>>(
            state: &mut State,
            inner: &mut ParserInner<TStack>,
            item_likes_state: &mut ItemLikesState,
            container: ItemLikeContainer,
            item_like: GeneralItemLike,
        ) -> crate::Result<Tym<2>> {
            let tym = match item_likes_state {
                ItemLikesState::MatchingLastLine(matching_last_line) => {
                    let stack_entry = matching_last_line.first_unprocessed_item_like(&inner.stack);
                    if stack_entry.r#type == container {
                        matching_last_line
                            .mark_first_unprocessed_item_like_as_processed_at_current_line(
                                &inner.stack,
                            );
                        *state = Exiting::new(
                            ExitingUntil::OnlyNItemLikesRemain {
                                n: matching_last_line.processed_item_likes(),
                                should_also_exit_containee_in_last_container: true,
                            },
                            ExitingAndThen::EnterItemLikeAndExpectItemLike {
                                container: None,
                                item_like: make_stack_entry_from_general_item_like(
                                    item_like, inner,
                                ),
                            },
                        )
                        .into()
                    } else {
                        *state = Exiting::new(
                            ExitingUntil::OnlyNItemLikesRemain {
                                n: matching_last_line.processed_item_likes(),
                                should_also_exit_containee_in_last_container: false,
                            },
                            ExitingAndThen::EnterItemLikeAndExpectItemLike {
                                container: Some(make_stack_entry_from_item_like_container(
                                    container, inner,
                                )),
                                item_like: make_stack_entry_from_general_item_like(
                                    item_like, inner,
                                ),
                            },
                        )
                        .into();
                    }
                    TYM_UNIT.into()
                }
                ItemLikesState::ProcessingNew => {
                    let tym_a = {
                        let stack_entry =
                            make_stack_entry_from_item_like_container(container, inner);
                        let ev = stack_entry.make_enter_event();
                        inner.stack.push_item_like_container(stack_entry)?;
                        inner.r#yield(ev)
                    };
                    let tym_b = {
                        let stack_entry = make_stack_entry_from_general_item_like(item_like, inner);
                        let ev = stack_entry.make_enter_event();
                        inner.stack.push_item_like(stack_entry)?;
                        inner.r#yield(ev)
                    };

                    tym_a.add(tym_b)
                }
            };

            Ok(tym)
        }

        fn is_indeed_opening_and_consume_if_true<TStack: Stack<StackEntry>>(
            input: &[u8],
            inner: &mut ParserInner<TStack>,
        ) -> bool {
            match input.get(inner.cursor() + 1) {
                Some(b' ') => inner.move_cursor_forward(1 + " ".len()),
                None | Some(b'\r' | b'\n') => inner.move_cursor_forward(1),
                // TODO: 也许可以一步到位调用 `leaf::paragraph::enter_if_not_blank(input, inner, 1)`。
                _ => return false,
            }

            true
        }

        pub fn make_stack_entry_from_general_item_like<TStack: Stack<StackEntry>>(
            item_like: GeneralItemLike,
            inner: &mut ParserInner<TStack>,
        ) -> StackEntryItemLike {
            StackEntryItemLike {
                meta: Meta::new(inner.pop_block_id(), inner.current_line()),
                r#type: item_like,
            }
        }

        fn make_stack_entry_from_item_like_container<TStack: Stack<StackEntry>>(
            item_like: ItemLikeContainer,
            inner: &mut ParserInner<TStack>,
        ) -> StackEntryItemLikeContainer {
            StackEntryItemLikeContainer {
                meta: Meta::new(inner.pop_block_id(), inner.current_line()),
                r#type: item_like,
            }
        }

        pub fn exit_container<TStack: Stack<StackEntry>>(
            inner: &mut ParserInner<TStack>,
            stack_entry: StackEntryItemLikeContainer,
        ) -> crate::Result<Tym<1>> {
            let tym = inner.r#yield(stack_entry.make_exit_event(inner.current_line()));

            Ok(tym)
        }

        pub fn exit<TStack: Stack<StackEntry>>(
            inner: &mut ParserInner<TStack>,
            stack_entry: StackEntryItemLike,
        ) -> crate::Result<Tym<1>> {
            let tym = inner.r#yield(stack_entry.make_exit_event(inner.current_line()));

            Ok(tym)
        }
    }

    pub mod braced {
        use super::*;

        pub fn parse_opening_and_process<TStack: Stack<StackEntry>>(
            input: &[u8],
            state: &mut State,
            inner: &mut ParserInner<TStack>,
            first_char: u8,
        ) -> crate::Result<Tym<5>> {
            match first_char {
                m!('{') => match input.get(inner.cursor() + 1) {
                    Some(m!('|')) => {
                        inner.move_cursor_forward("{|".len());
                        table::enter(state, inner).map(|tym| cast_tym!(tym))
                    }
                    _ => leaf::paragraph::enter_if_not_blank(input, state, inner, 1)
                        .map(|tym| cast_tym!(tym)),
                },
                _ => leaf::parse_opening_and_process(input, state, inner, first_char)
                    .map(|tym| cast_tym!(tym)),
            }
        }

        pub mod table {
            use super::*;

            pub(super) fn enter<TStack: Stack<StackEntry>>(
                state: &mut State,
                inner: &mut ParserInner<TStack>,
            ) -> crate::Result<Tym<1>> {
                *state = Expecting::BracedOpening.into();

                let id = inner.pop_block_id();
                let stack_entry = StackEntryTable {
                    meta: Meta::new(id, inner.current_line()),
                };
                let ev = stack_entry.make_enter_event();
                inner.stack.push_table(stack_entry)?;
                let tym = inner.r#yield(ev);

                Ok(tym)
            }

            #[derive(Debug, PartialEq, Eq)]
            pub enum TableRelatedEnd {
                TableClosing,
                TableCaptionIndicator,
                TableRowIndicator,
                TableHeaderCellIndicator,
                DoublePipes,
            }
            impl TableRelatedEnd {
                pub fn process(self, state: &mut State) -> Tym<0> {
                    *state = match self {
                        TableRelatedEnd::TableClosing => Exiting::new(
                            ExitingUntil::TopIsTable {
                                should_also_exit_table: true,
                            },
                            ExitingAndThen::ExpectBracedOpening,
                        )
                        .into(),
                        TableRelatedEnd::TableCaptionIndicator => Exiting::new(
                            ExitingUntil::TopIsTable {
                                should_also_exit_table: false,
                            },
                            ExitingAndThen::YieldAndExpectBracedOpening(ev!(
                                Block,
                                IndicateTableCaption
                            )),
                        )
                        .into(),
                        TableRelatedEnd::TableRowIndicator => Exiting::new(
                            ExitingUntil::TopIsTable {
                                should_also_exit_table: false,
                            },
                            ExitingAndThen::YieldAndExpectBracedOpening(ev!(
                                Block,
                                IndicateTableRow
                            )),
                        )
                        .into(),
                        TableRelatedEnd::TableHeaderCellIndicator => Exiting::new(
                            ExitingUntil::TopIsTable {
                                should_also_exit_table: false,
                            },
                            ExitingAndThen::YieldAndExpectBracedOpening(ev!(
                                Block,
                                IndicateTableHeaderCell
                            )),
                        )
                        .into(),
                        TableRelatedEnd::DoublePipes => Exiting::new(
                            ExitingUntil::TopIsAwareOfDoublePipes,
                            ExitingAndThen::YieldBasedOnContextAndExpectBracedOpening,
                        )
                        .into(),
                    };

                    cast_tym!(TYM_UNIT)
                }
            }

            pub fn parse_end<TCtx: CursorContext>(
                input: &[u8],
                ctx: &mut TCtx,
                first_char: u8,
                is_caption_applicable: bool,
            ) -> Option<TableRelatedEnd> {
                let &second_char = input.get(ctx.cursor() + 1)?;
                let end = match first_char {
                    m!('|') => match second_char {
                        m!('}') => TableRelatedEnd::TableClosing,
                        m!('+') if is_caption_applicable => TableRelatedEnd::TableCaptionIndicator,
                        m!('-') => TableRelatedEnd::TableRowIndicator,
                        m!('|') => TableRelatedEnd::DoublePipes,
                        _ => return None,
                    },
                    m!('!') => match second_char {
                        m!('!') => TableRelatedEnd::TableHeaderCellIndicator,
                        _ => return None,
                    },
                    _ => return None,
                };
                ctx.move_cursor_forward(2);
                Some(end)
            }

            pub fn exit<TStack: Stack<StackEntry>>(
                inner: &mut ParserInner<TStack>,
                stack_entry: StackEntryTable,
            ) -> crate::Result<Tym<1>> {
                let tym = inner.r#yield(stack_entry.make_exit_event(inner.current_line()));

                Ok(tym)
            }

            pub fn make_table_related_end_condition<TStack: Stack<StackEntry>>(
                inner: &ParserInner<TStack>,
                is_caption_applicable: bool,
            ) -> Option<line::normal::TableRelated> {
                if inner.stack.tables_in_stack() > 0 {
                    Some(line::normal::TableRelated {
                        is_caption_applicable,
                    })
                } else {
                    None
                }
            }
        }
    }
}

mod leaf {
    use super::*;

    pub fn parse_opening_and_process<TStack: Stack<StackEntry>>(
        input: &[u8],
        state: &mut State,
        inner: &mut ParserInner<TStack>,
        first_char: u8,
    ) -> crate::Result<Tym<5>> {
        match first_char {
            m!('-') => {
                let count = 1 + count_continuous_character(input, m!('-'), inner.cursor() + 1);
                if count >= 3 {
                    inner.move_cursor_forward(count);
                    thematic_break::process(inner).map(|tym| cast_tym!(tym))
                } else {
                    paragraph::enter_if_not_blank(input, state, inner, count)
                        .map(|tym| cast_tym!(tym))
                }
            }
            m!('=') => {
                let count = 1 + count_continuous_character(input, m!('='), inner.cursor() + 1);
                if (1..=6).contains(&count) && input.get(inner.cursor() + count) == Some(&b' ') {
                    inner.move_cursor_forward(count + " ".len());
                    heading::enter(inner, count).map(|tym| cast_tym!(tym))
                } else {
                    paragraph::enter_if_not_blank(input, state, inner, count)
                        .map(|tym| cast_tym!(tym))
                }
            }
            m!('`') => {
                let count = 1 + count_continuous_character(input, m!('`'), inner.cursor() + 1);
                if count >= 3 {
                    inner.move_cursor_forward(count);
                    code_block::enter(inner, count).map(|tym| cast_tym!(tym))
                } else {
                    paragraph::enter_if_not_blank(input, state, inner, count)
                        .map(|tym| cast_tym!(tym))
                }
            }
            _ => paragraph::enter_if_not_blank(input, state, inner, 0).map(|tym| cast_tym!(tym)),
        }
    }

    pub fn parse_content_and_process<TStack: Stack<StackEntry>>(
        input: &[u8],
        state: &mut State,
        inner: &mut ParserInner<TStack>,
        top_leaf: TopLeaf,
    ) -> crate::Result<Tym<5>> {
        match top_leaf {
            TopLeaf::Paragraph(top_leaf) => {
                leaf::paragraph::parse_content_and_process(input, state, inner, top_leaf)
                    .map(|tym| cast_tym!(tym))
            }
            TopLeaf::Heading(top_leaf) => {
                leaf::heading::parse_content_and_process(input, state, inner, top_leaf)
                    .map(|tym| cast_tym!(tym))
            }
            TopLeaf::CodeBlock(top_leaf) => {
                leaf::code_block::parse_content_and_process(input, inner, top_leaf)
                    .map(|tym| cast_tym!(tym))
            }
        }
    }

    mod thematic_break {
        use super::*;

        pub fn process<TStack: Stack<StackEntry>>(
            inner: &mut ParserInner<TStack>,
        ) -> crate::Result<Tym<1>> {
            let id = inner.pop_block_id();
            let tym = inner.r#yield(ev!(
                Block,
                ThematicBreak(ThematicBreak {
                    id,
                    line: inner.current_line(),
                })
            ));

            Ok(tym)
        }
    }

    pub mod heading {
        use line::normal::AtxClosing;

        use super::*;

        pub(super) fn enter<TStack: Stack<StackEntry>>(
            inner: &mut ParserInner<TStack>,
            level: usize,
        ) -> crate::Result<Tym<1>> {
            let id = inner.pop_block_id();
            let top_leaf = TopLeafHeading {
                meta: Meta::new(id, inner.current_line()),
                level,
                has_content_before: false,
            };
            let ev = top_leaf.make_enter_event();
            inner.stack.push_top_leaf(top_leaf.into());
            let tym = inner.r#yield(ev);

            Ok(tym)
        }

        pub fn parse_content_and_process<TStack: Stack<StackEntry>>(
            input: &[u8],
            state: &mut State,
            inner: &mut ParserInner<TStack>,
            mut top_leaf: TopLeafHeading,
        ) -> crate::Result<Tym<2>> {
            let (mut content, end) = line::normal::parse(
                input,
                inner,
                line::normal::EndCondition {
                    on_atx_closing: Some(AtxClosing {
                        character: m!('='),
                        count: top_leaf.level,
                    }),
                    on_table_related: branch::braced::table::make_table_related_end_condition(
                        inner, false,
                    ),
                    on_description_definition_opening: false,
                },
                if inner.current_expecting.spaces_before() > 0 {
                    line::normal::ContentBefore::Space
                } else {
                    line::normal::ContentBefore::NotSpace(0)
                },
            );

            if top_leaf.has_content_before
                && inner.current_expecting.spaces_before() > 0
                && end.is_verbatim_escaping()
            {
                content.start -= inner.current_expecting.spaces_before();
            }

            let tym_a = if !content.is_empty() {
                inner.r#yield(ev!(Block, __Unparsed(content)))
            } else {
                TYM_UNIT.into()
            };

            let tym_b = match end {
                line::normal::End::Eof | line::normal::End::NewLine(_) => exit(inner, top_leaf),
                line::normal::End::VerbatimEscaping(verbatim_escaping) => {
                    top_leaf.has_content_before = true;
                    inner.stack.push_top_leaf(top_leaf.into());
                    line::global_phase::process_verbatim_escaping(inner, verbatim_escaping)
                }
                line::normal::End::TableRelated(table_related_end) => {
                    let tym_a = exit(inner, top_leaf);
                    let tym_b = table_related_end.process(state);

                    tym_a.add(tym_b)
                }
                line::normal::End::DescriptionDefinitionOpening => {
                    unreachable!()
                }
                line::normal::End::None => TYM_UNIT.into(),
            };

            Ok(tym_a.add(tym_b))
        }

        pub fn exit<TStack: Stack<StackEntry>>(
            inner: &mut ParserInner<TStack>,
            top_leaf: TopLeafHeading,
        ) -> Tym<1> {
            inner.r#yield(top_leaf.make_exit_event(inner.current_line()))
        }
    }

    pub mod code_block {
        use stack_wrapper::{TopLeafCodeBlockState, TopLeafCodeBlockStateInCode};

        use super::*;

        pub(super) fn enter<TStack: Stack<StackEntry>>(
            inner: &mut ParserInner<TStack>,
            backticks: usize,
        ) -> crate::Result<Tym<1>> {
            let id = inner.pop_block_id();
            let top_leaf = TopLeafCodeBlock {
                meta: Meta::new(id, inner.current_line()),
                backticks,
                indent: inner.current_expecting.spaces_before(),
                state: TopLeafCodeBlockState::InInfoString,
            };
            let ev = top_leaf.make_enter_event();
            inner.stack.push_top_leaf(top_leaf.into());
            let tym = inner.r#yield(ev);

            Ok(tym)
        }

        pub fn parse_content_and_process<TStack: Stack<StackEntry>>(
            input: &[u8],
            inner: &mut ParserInner<TStack>,
            mut top_leaf: TopLeafCodeBlock,
        ) -> crate::Result<Tym<3>> {
            let tym = match top_leaf.state {
                TopLeafCodeBlockState::InInfoString => {
                    let (content, end) = line::verbatim::parse(
                        input,
                        inner,
                        line::verbatim::EndCondition { on_fence: None },
                        inner.current_expecting.spaces_before(),
                        None,
                    );

                    let tym_a = if !content.is_empty() {
                        inner.r#yield(ev!(Block, Text(content)))
                    } else {
                        TYM_UNIT.into()
                    };

                    let tym_b = match end {
                        line::verbatim::End::Eof => TYM_UNIT.into(),
                        line::verbatim::End::NewLine(_new_line) => {
                            top_leaf.state = TopLeafCodeBlockState::InCode(
                                TopLeafCodeBlockStateInCode::AtFirstLineBeginning,
                            );
                            inner.r#yield(ev!(Block, IndicateCodeBlockCode))
                        }
                        line::verbatim::End::VerbatimEscaping(verbatim_escaping) => {
                            line::global_phase::process_verbatim_escaping(inner, verbatim_escaping)
                        }
                        line::verbatim::End::Fence => unreachable!(),
                        line::verbatim::End::None => TYM_UNIT.into(),
                    };

                    inner.stack.push_top_leaf(top_leaf.into());

                    tym_a.add(tym_b).into()
                }
                TopLeafCodeBlockState::InCode(ref in_code) => {
                    let (at_line_beginning, new_line) = match in_code {
                        TopLeafCodeBlockStateInCode::AtFirstLineBeginning => (
                            Some(line::verbatim::AtLineBeginning {
                                indent: top_leaf.indent,
                            }),
                            None,
                        ),
                        TopLeafCodeBlockStateInCode::AtLineBeginning(new_line) => (
                            Some(line::verbatim::AtLineBeginning {
                                indent: top_leaf.indent,
                            }),
                            Some(new_line.clone()),
                        ),
                        TopLeafCodeBlockStateInCode::Normal => (None, None),
                    };

                    let (content, end) = line::verbatim::parse(
                        input,
                        inner,
                        line::verbatim::EndCondition {
                            on_fence: Some(line::verbatim::Fence {
                                character: m!('`'),
                                minimum_count: top_leaf.backticks,
                            }),
                        },
                        inner.current_expecting.spaces_before(),
                        at_line_beginning,
                    );

                    let tym_a = if let Some(new_line) = new_line {
                        if !matches!(end, line::verbatim::End::Eof) {
                            inner.r#yield(ev!(Block, NewLine(new_line)))
                        } else {
                            TYM_UNIT.into()
                        }
                    } else {
                        TYM_UNIT.into()
                    };

                    let tym_b = if !content.is_empty() {
                        inner.r#yield(ev!(Block, Text(content)))
                    } else {
                        TYM_UNIT.into()
                    };

                    let tym_c = match end {
                        line::verbatim::End::Eof => {
                            inner.stack.push_top_leaf(top_leaf.into());
                            TYM_UNIT.into()
                        }
                        line::verbatim::End::NewLine(new_line) => {
                            top_leaf.state = TopLeafCodeBlockState::InCode(
                                TopLeafCodeBlockStateInCode::AtLineBeginning(new_line),
                            );
                            inner.stack.push_top_leaf(top_leaf.into());
                            TYM_UNIT.into()
                        }
                        line::verbatim::End::VerbatimEscaping(verbatim_escaping) => {
                            top_leaf.state =
                                TopLeafCodeBlockState::InCode(TopLeafCodeBlockStateInCode::Normal);
                            inner.stack.push_top_leaf(top_leaf.into());
                            line::global_phase::process_verbatim_escaping(inner, verbatim_escaping)
                        }
                        line::verbatim::End::Fence => {
                            exit_when_indicator_already_yielded(inner, top_leaf)
                        }
                        line::verbatim::End::None => {
                            top_leaf.state =
                                TopLeafCodeBlockState::InCode(TopLeafCodeBlockStateInCode::Normal);
                            inner.stack.push_top_leaf(top_leaf.into());
                            TYM_UNIT.into()
                        }
                    };

                    tym_a.add(tym_b).add(tym_c)
                }
            };

            Ok(tym)
        }

        fn exit_when_indicator_already_yielded<TStack: Stack<StackEntry>>(
            inner: &mut ParserInner<TStack>,
            top_leaf: TopLeafCodeBlock,
        ) -> Tym<1> {
            inner.r#yield(top_leaf.make_exit_event(inner.current_line()))
        }

        pub fn exit<TStack: Stack<StackEntry>>(
            inner: &mut ParserInner<TStack>,
            top_leaf: TopLeafCodeBlock,
        ) -> Tym<2> {
            let tym_a = if matches!(top_leaf.state, TopLeafCodeBlockState::InInfoString) {
                inner.r#yield(ev!(Block, IndicateCodeBlockCode))
            } else {
                TYM_UNIT.into()
            };

            let tym_b = exit_when_indicator_already_yielded(inner, top_leaf);

            tym_a.add(tym_b)
        }
    }

    pub mod paragraph {
        use super::*;

        /// `content_before` 是已经确认是段落一部分的内容的长度。传入的 `inner.cursor`
        /// 的位置并未加上这些值。调用者要确保如果 `content_before` 不为 0,那
        /// `inner.cursor` 就能作为段落的开头(段落开头应该是并非空格或换行的字符)。
        pub fn enter_if_not_blank<TStack: Stack<StackEntry>>(
            input: &[u8],
            state: &mut State,
            inner: &mut ParserInner<TStack>,
            content_before: usize,
        ) -> crate::Result<Tym<5>> {
            #[cfg(debug_assertions)]
            {
                if content_before > 0 {
                    assert!(!matches!(
                        input.get(inner.cursor()),
                        None | Some(b' ' | b'\r' | b'\n')
                    ))
                }
            }

            // [line::normal::parse] 的过程中可能会涉及到逐字转义,导致行数增加,因此
            // 需要提前取得行数。
            let line_start = inner.current_line();

            let has_just_entered_table = inner.has_just_entered_table();
            let (content, mut end) = line::normal::parse(
                input,
                inner,
                line::normal::EndCondition {
                    on_atx_closing: None,
                    on_table_related: branch::braced::table::make_table_related_end_condition(
                        inner,
                        has_just_entered_table,
                    ),
                    on_description_definition_opening: inner.stack.top_is_description_term(),
                },
                line::normal::ContentBefore::NotSpace(content_before),
            );

            let tym_ab = if !content.is_empty() || end.is_verbatim_escaping() {
                let id = inner.pop_block_id();
                let top_leaf = TopLeafParagraph {
                    meta: Meta::new(id, line_start),
                    new_line: end.try_take_new_line(),
                };
                let ev = top_leaf.make_enter_event();
                inner.stack.push_top_leaf(top_leaf.into());
                let tym_a = inner.r#yield(ev);

                let tym_b = if !content.is_empty() {
                    inner.r#yield(ev!(Block, __Unparsed(content)))
                } else {
                    TYM_UNIT.into()
                };

                tym_a.add(tym_b)
            } else {
                TYM_UNIT.into()
            };

            let tym_c = process_normal_end(end, state, inner)?;

            Ok(tym_ab.add(tym_c))
        }

        fn process_normal_end<TStack: Stack<StackEntry>>(
            end: line::normal::End,
            state: &mut State,
            inner: &mut ParserInner<TStack>,
        ) -> crate::Result<Tym<3>> {
            let ret = match end {
                line::normal::End::Eof |
                // 段落处理换行是在换行后的那一行,而非换行前的那一行(现在),因此这里跳过处
                // 理。这么做是因为现在不知道下一行还有没有内容,没有内容的话就不应该产出换行
                // 符。此外,这么做也能防止空行产出换行符。
                line::normal::End::NewLine(_) => TYM_UNIT.into(),
                line::normal::End::VerbatimEscaping(verbatim_escaping) => {
                    let tym = line::global_phase::process_verbatim_escaping(inner, verbatim_escaping);
                    cast_tym!(tym)
                }
                line::normal::End::TableRelated(table_related_end) => {
                    let tym = table_related_end.process(state, );
                    cast_tym!(tym)
                }
                line::normal::End::DescriptionDefinitionOpening => {
                    // 退出当前的段落。
                    let tym_a = {
                        let Some(TopLeaf::Paragraph(top_leaf)) = inner.stack.pop_top_leaf() else {
                            unreachable!()
                        };
                        exit(inner, top_leaf)
                    };

                    // 退出当前的 DT。
                    let tym_b = {
                        let Some(StackEntry::ItemLike(dt)) = inner.stack.pop() else {
                            unreachable!()
                        };
                        debug_assert!(matches!(dt.r#type, GeneralItemLike::DT));
                        branch::item_like::exit(inner, dt)?
                    };

                    // 进入 DD
                    let tym_c = {
                        let stack_entry =
                            branch::item_like::make_stack_entry_from_general_item_like(GeneralItemLike::DD, inner);
                        let ev = stack_entry.make_enter_event();
                        inner.stack.push_item_like(stack_entry)?;
                        inner.r#yield(ev)
                    };

                    tym_a.add(tym_b).add(tym_c)
                }
                line::normal::End::None => TYM_UNIT.into()
            };

            Ok(ret)
        }

        pub fn parse_content_and_process<TStack: Stack<StackEntry>>(
            input: &[u8],
            state: &mut State,
            inner: &mut ParserInner<TStack>,
            mut top_leaf: TopLeafParagraph,
        ) -> crate::Result<Tym<5>> {
            let (mut content, mut end) = line::normal::parse(
                input,
                inner,
                line::normal::EndCondition {
                    on_atx_closing: None,
                    on_table_related: branch::braced::table::make_table_related_end_condition(
                        inner, false,
                    ),
                    on_description_definition_opening: inner.stack.top_is_description_term(),
                },
                if inner.current_expecting.spaces_before() > 0 {
                    line::normal::ContentBefore::Space
                } else {
                    line::normal::ContentBefore::NotSpace(0)
                },
            );

            let is_still_in_paragraph =
                !content.is_empty() || top_leaf.new_line.is_none() || end.is_verbatim_escaping();
            let tym_ab = if is_still_in_paragraph {
                let tym_a = if let Some(new_line) = top_leaf.new_line {
                    inner.r#yield(ev!(Block, NewLine(new_line)))
                } else {
                    if inner.current_expecting.spaces_before() > 0 {
                        // 在一行的中间,那就不能忽略空格。
                        content.start -= inner.current_expecting.spaces_before();
                    }
                    TYM_UNIT.into()
                };

                top_leaf.new_line = end.try_take_new_line();
                inner.stack.push_top_leaf(top_leaf.into());

                let tym_b = if !content.is_empty() {
                    inner.r#yield(ev!(Block, __Unparsed(content)))
                } else {
                    TYM_UNIT.into()
                };

                tym_a.add(tym_b)
            } else {
                exit(inner, top_leaf).into()
            };

            let tym_c = process_normal_end(end, state, inner)?;

            Ok(tym_ab.add(tym_c))
        }

        pub fn exit<TStack: Stack<StackEntry>>(
            inner: &mut ParserInner<TStack>,
            top_leaf: TopLeafParagraph,
        ) -> Tym<1> {
            inner.r#yield(top_leaf.make_exit_event(inner.current_line()))
        }
    }
}