litedoc-core 0.1.0

Deterministic document parser for machine-generated output with error recovery
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
//! Zero-allocation block parser for LiteDoc
//!
//! Borrows directly from input, avoiding String allocations.
//! Features graceful error recovery to continue parsing after errors.

use std::borrow::Cow;

use crate::ast::{
    AttrValue, Block, Callout, CodeBlock, CowStr, Document, Figure, FootnoteDef, Footnotes,
    Heading, HtmlBlock, List, ListItem, ListKind, MathBlock, Metadata, Module, Paragraph, Profile,
    Quote, RawBlock, Table, TableCell, TableRow,
};
use crate::error::{ParseError, ParseErrors};
use crate::lexer::Lexer;
use crate::span::Span;

/// Result type for parsing that includes recovered errors.
#[derive(Debug)]
pub struct ParseResult<'a> {
    /// The parsed document (may be partial if errors occurred).
    pub document: Document<'a>,
    /// Errors encountered during parsing.
    pub errors: ParseErrors,
}

impl<'a> ParseResult<'a> {
    /// Check if parsing completed without errors.
    pub fn is_ok(&self) -> bool {
        self.errors.is_empty()
    }

    /// Check if any fatal errors occurred.
    pub fn has_fatal_errors(&self) -> bool {
        self.errors.has_fatal()
    }
}

/// LiteDoc parser with configurable profile and error recovery.
pub struct Parser {
    profile: Profile,
    modules: Vec<Module>,
    /// Errors collected during parsing (for recovery mode).
    errors: ParseErrors,
    /// Whether to attempt recovery on errors.
    recover_on_error: bool,
}

impl Parser {
    /// Create a new parser with the given profile.
    #[inline]
    pub fn new(profile: Profile) -> Self {
        Self {
            profile,
            modules: Vec::new(),
            errors: ParseErrors::new(),
            recover_on_error: true,
        }
    }

    /// Enable or disable error recovery mode.
    ///
    /// When enabled (default), the parser will attempt to continue
    /// parsing after encountering errors, collecting them for later
    /// inspection. When disabled, parsing stops at the first error.
    pub fn with_recovery(mut self, recover: bool) -> Self {
        self.recover_on_error = recover;
        self
    }

    /// Parse with error recovery, returning both document and errors.
    #[inline]
    pub fn parse_with_recovery<'a>(&mut self, input: &'a str) -> ParseResult<'a> {
        self.errors = ParseErrors::new();
        let doc = self.parse_internal(input);
        ParseResult {
            document: doc,
            errors: std::mem::take(&mut self.errors),
        }
    }

    /// Parse the input, returning an error on first failure.
    #[inline]
    pub fn parse<'a>(&mut self, input: &'a str) -> Result<Document<'a>, ParseError> {
        self.errors = ParseErrors::new();
        let doc = self.parse_internal(input);
        if self.errors.is_empty() {
            Ok(doc)
        } else {
            // Return the first error
            Err(self.errors.iter().next().unwrap().clone())
        }
    }

    #[inline]
    fn parse_internal<'a>(&mut self, input: &'a str) -> Document<'a> {
        let mut lexer = Lexer::new(input);

        lexer.skip_blank_lines();

        let profile = self.parse_profile_directive(&mut lexer);
        let modules = self.parse_modules_directive(&mut lexer);
        self.modules = modules.clone();

        lexer.skip_blank_lines();

        let metadata = self.parse_metadata(&mut lexer, input);

        lexer.skip_blank_lines();

        let blocks = self.parse_blocks(&mut lexer, input);

        Document {
            profile: profile.unwrap_or(self.profile),
            modules,
            metadata,
            blocks,
            span: Span::new(0, input.len() as u32),
        }
    }

    /// Record an error during parsing.
    #[inline]
    fn record_error(&mut self, error: ParseError) {
        self.errors.push(error);
    }

    /// Check if the given module is enabled.
    #[inline]
    pub fn has_module(&self, module: Module) -> bool {
        self.modules.contains(&module)
    }

    #[inline]
    fn parse_profile_directive(&self, lexer: &mut Lexer) -> Option<Profile> {
        let line = lexer.peek_line()?;
        let trimmed = line.trimmed();

        if let Some(rest) = trimmed.strip_prefix("@profile") {
            let profile = match rest.trim() {
                "litedoc" => Some(Profile::Litedoc),
                "md" => Some(Profile::Md),
                "md-strict" => Some(Profile::MdStrict),
                _ => None,
            };
            if profile.is_some() {
                lexer.next_line();
                lexer.skip_blank_lines();
            }
            profile
        } else {
            None
        }
    }

    #[inline]
    fn parse_modules_directive(&self, lexer: &mut Lexer) -> Vec<Module> {
        let line = lexer.peek_line();
        let trimmed = match line {
            Some(l) => l.trimmed(),
            None => return Vec::new(),
        };

        if let Some(rest) = trimmed.strip_prefix("@modules") {
            let mut modules = Vec::with_capacity(4);
            for part in rest.split(',') {
                match part.trim() {
                    "tables" => modules.push(Module::Tables),
                    "footnotes" => modules.push(Module::Footnotes),
                    "math" => modules.push(Module::Math),
                    "tasks" => modules.push(Module::Tasks),
                    "strikethrough" => modules.push(Module::Strikethrough),
                    "autolink" => modules.push(Module::Autolink),
                    "html" => modules.push(Module::Html),
                    _ => {}
                }
            }
            lexer.next_line();
            lexer.skip_blank_lines();
            modules
        } else {
            Vec::new()
        }
    }

    #[inline]
    fn parse_metadata<'a>(&self, lexer: &mut Lexer, input: &'a str) -> Option<Metadata<'a>> {
        let start_span;
        {
            let line = lexer.peek_line()?;
            let trimmed = line.trimmed();
            if !trimmed.starts_with("---") || !trimmed.contains("meta") {
                return None;
            }
            start_span = line.span;
        }
        lexer.next_line();

        let mut entries: Vec<(CowStr<'a>, AttrValue<'a>)> = Vec::with_capacity(8);
        let mut end_span = start_span;

        loop {
            let (trimmed, span, is_end) = {
                match lexer.peek_line() {
                    Some(line) => {
                        let t = line.trimmed();
                        let s = line.span;
                        let end = t == "---";
                        (t.to_string(), s, end)
                    }
                    None => break,
                }
            };

            if is_end {
                end_span = span;
                lexer.next_line();
                break;
            }

            if let Some(_colon_pos) = trimmed.find(':') {
                // We need to get slices from input, not from trimmed
                let line_start = span.start as usize;
                let line_text = &input[line_start..span.end as usize];

                if let Some(cp) = line_text.find(':') {
                    let key_slice = line_text[..cp].trim();
                    let val_slice = line_text[cp + 1..].trim();

                    let key: CowStr<'a> = Cow::Borrowed(key_slice);
                    let value = self.parse_attr_value(val_slice);
                    entries.push((key, value));
                }
            }

            end_span = span;
            lexer.next_line();
        }

        Some(Metadata {
            entries,
            span: Span::new(start_span.start, end_span.end),
        })
    }

    #[inline]
    fn parse_attr_value<'a>(&self, s: &'a str) -> AttrValue<'a> {
        if s == "true" {
            return AttrValue::Bool(true);
        }
        if s == "false" {
            return AttrValue::Bool(false);
        }

        if s.starts_with('[') && s.ends_with(']') {
            let inner = &s[1..s.len() - 1];
            let items = self.parse_list_items(inner);
            return AttrValue::List(items);
        }

        if let Ok(i) = s.parse::<i64>() {
            return AttrValue::Int(i);
        }

        if s.contains('.') {
            if let Ok(f) = s.parse::<f64>() {
                return AttrValue::Float(f);
            }
        }

        let unquoted = if (s.starts_with('"') && s.ends_with('"'))
            || (s.starts_with('\'') && s.ends_with('\''))
        {
            &s[1..s.len() - 1]
        } else {
            s
        };

        AttrValue::Str(Cow::Borrowed(unquoted))
    }

    #[inline]
    fn parse_list_items<'a>(&self, s: &'a str) -> Vec<AttrValue<'a>> {
        let mut items = Vec::with_capacity(4);
        let mut start = 0;
        let mut in_quotes = false;
        let bytes = s.as_bytes();

        for i in 0..bytes.len() {
            match bytes[i] {
                b'"' | b'\'' => in_quotes = !in_quotes,
                b',' if !in_quotes => {
                    let item = s[start..i].trim();
                    if !item.is_empty() {
                        items.push(self.parse_attr_value(item));
                    }
                    start = i + 1;
                }
                _ => {}
            }
        }

        let item = s[start..].trim();
        if !item.is_empty() {
            items.push(self.parse_attr_value(item));
        }

        items
    }

    #[inline]
    fn parse_blocks<'a>(&mut self, lexer: &mut Lexer, input: &'a str) -> Vec<Block<'a>> {
        let mut blocks = Vec::with_capacity(16);

        while !lexer.is_eof() {
            lexer.skip_blank_lines();

            if lexer.is_eof() {
                break;
            }

            if let Some(block) = self.parse_block(lexer, input) {
                blocks.push(block);
            }
        }

        blocks
    }

    #[inline]
    fn parse_block<'a>(&mut self, lexer: &mut Lexer, input: &'a str) -> Option<Block<'a>> {
        let (first_byte, trimmed_starts_triple, is_hr, starts_colon, span) = {
            let line = lexer.peek_line()?;
            let trimmed = line.trimmed();
            (
                trimmed.as_bytes().first().copied(),
                trimmed.starts_with("```"),
                trimmed == "---",
                trimmed.starts_with("::"),
                line.span,
            )
        };

        match first_byte {
            Some(b'#') => self.parse_heading(lexer, input),
            Some(b'`') if trimmed_starts_triple => self.parse_code_block(lexer, input),
            Some(b'-') if is_hr => {
                lexer.next_line();
                Some(Block::ThematicBreak(span))
            }
            Some(b':') if starts_colon => self.parse_fenced_block(lexer, input),
            _ => self.parse_paragraph(lexer, input),
        }
    }

    #[inline]
    fn parse_heading<'a>(&mut self, lexer: &mut Lexer, input: &'a str) -> Option<Block<'a>> {
        let line = lexer.next_line()?;
        let text = &input[line.span.start as usize..line.span.end as usize];
        let bytes = text.as_bytes();

        let level = bytes.iter().take_while(|&&b| b == b'#').count() as u8;

        if level == 0 || level > 6 {
            return Some(Block::Paragraph(Paragraph {
                content: crate::inline::parse_inlines(text, line.span.start, input),
                span: line.span,
            }));
        }

        let rest = &text[level as usize..];
        if !rest.starts_with(' ') && !rest.is_empty() {
            return Some(Block::Paragraph(Paragraph {
                content: crate::inline::parse_inlines(text, line.span.start, input),
                span: line.span,
            }));
        }

        let content_text = rest.trim_start();
        let content_offset = line.span.start + (text.len() - content_text.len()) as u32;

        Some(Block::Heading(Heading {
            level,
            content: crate::inline::parse_inlines(content_text, content_offset, input),
            span: line.span,
        }))
    }

    #[inline]
    fn parse_code_block<'a>(&mut self, lexer: &mut Lexer, input: &'a str) -> Option<Block<'a>> {
        let (start_span, lang_start, lang_end) = {
            let open_line = lexer.next_line()?;
            let text = &input[open_line.span.start as usize..open_line.span.end as usize];
            let trimmed = text.trim();
            let after_ticks = trimmed.strip_prefix("```").unwrap_or("");
            let lang = after_ticks.trim();

            // Calculate where lang is in input
            let lang_offset = if lang.is_empty() {
                open_line.span.end as usize
            } else {
                // Find lang in the line
                open_line.span.start as usize + text.find(lang).unwrap_or(0)
            };

            (open_line.span, lang_offset, lang_offset + lang.len())
        };

        let lang = &input[lang_start..lang_end];

        // Content starts after the opening fence line. Add 1 to skip newline if present,
        // but clamp to input length to handle EOF without trailing newline.
        let content_start = (start_span.end as usize + 1).min(input.len());
        let mut content_end = content_start;
        let mut end_span = start_span;

        loop {
            let (is_close, span) = {
                match lexer.peek_line() {
                    Some(line) => (line.trimmed() == "```", line.span),
                    None => break,
                }
            };

            if is_close {
                end_span = span;
                lexer.next_line();
                break;
            }

            end_span = span;
            content_end = span.end as usize;
            lexer.next_line();
        }

        let content = if content_start < content_end && content_end <= input.len() {
            &input[content_start..content_end]
        } else {
            ""
        };

        Some(Block::CodeBlock(CodeBlock {
            lang: Cow::Borrowed(lang),
            content: Cow::Borrowed(content),
            span: Span::new(start_span.start, end_span.end),
        }))
    }

    #[inline]
    fn parse_fenced_block<'a>(&mut self, lexer: &mut Lexer, input: &'a str) -> Option<Block<'a>> {
        let (block_type, span) = {
            let line = lexer.peek_line()?;
            let trimmed = line.trimmed();
            let after_colons = trimmed.strip_prefix("::")?;
            let bt = after_colons
                .split_whitespace()
                .next()
                .unwrap_or("")
                .to_string();
            (bt, line.span)
        };

        match block_type.as_str() {
            "list" => self.parse_list_block(lexer, input),
            "callout" => self.parse_callout_block(lexer, input),
            "quote" => self.parse_quote_block(lexer, input),
            "figure" => self.parse_figure_block(lexer, input),
            "table" => self.parse_table_block(lexer, input),
            "footnotes" => self.parse_footnotes_block(lexer, input),
            "math" => self.parse_math_block(lexer, input),
            "html" => self.parse_html_block(lexer, input),
            _ => {
                // Record error for unknown directive but continue with raw block
                if self.recover_on_error && !block_type.is_empty() {
                    self.record_error(ParseError::unknown_directive(&block_type, Some(span)));
                }
                self.parse_raw_fenced_block(lexer, input)
            }
        }
    }

    #[inline]
    fn parse_html_block<'a>(&mut self, lexer: &mut Lexer, input: &'a str) -> Option<Block<'a>> {
        // Check if HTML module is enabled
        if !self.has_module(Module::Html) {
            return self.parse_raw_fenced_block(lexer, input);
        }

        let start_span = lexer.next_line()?.span;

        // Content starts after opening fence, clamped to input length
        let content_start = (start_span.end as usize + 1).min(input.len());
        let mut content_end = content_start;
        let mut end_span = start_span;

        loop {
            let (is_close, span) = {
                match lexer.peek_line() {
                    Some(line) => (line.trimmed() == "::", line.span),
                    None => {
                        // Record unclosed HTML block error
                        self.record_error(ParseError::unclosed_delimiter(
                            "HTML block",
                            Some(start_span),
                        ));
                        break;
                    }
                }
            };

            if is_close {
                end_span = span;
                lexer.next_line();
                break;
            }

            content_end = span.end as usize;
            end_span = span;
            lexer.next_line();
        }

        let content = if content_start < content_end && content_end <= input.len() {
            &input[content_start..content_end]
        } else {
            ""
        };

        Some(Block::Html(HtmlBlock {
            content: Cow::Borrowed(content),
            span: Span::new(start_span.start, end_span.end),
        }))
    }

    #[inline]
    fn parse_list_block<'a>(&mut self, lexer: &mut Lexer, input: &'a str) -> Option<Block<'a>> {
        let (start_span, kind, start_num) = {
            let open_line = lexer.next_line()?;
            let text = &input[open_line.span.start as usize..open_line.span.end as usize];
            let trimmed = text.trim();
            let after_list = trimmed.strip_prefix("::list").unwrap_or("").trim();

            let mut k = ListKind::Unordered;
            let mut sn: Option<u64> = None;

            for part in after_list.split_whitespace() {
                match part {
                    "ordered" => k = ListKind::Ordered,
                    "unordered" => k = ListKind::Unordered,
                    _ if part.starts_with("start=") => {
                        sn = part[6..].parse().ok();
                    }
                    _ => {}
                }
            }
            (open_line.span, k, sn)
        };

        let mut items: Vec<ListItem<'a>> = Vec::with_capacity(8);
        let mut item_start: Option<u32> = None;
        let mut item_end: u32 = start_span.end;
        let mut end_span = start_span;
        let mut last_span = start_span;

        let finalize_item = |items: &mut Vec<ListItem<'a>>, start: Option<u32>, end: u32| {
            if let Some(start) = start {
                let content_slice = &input[start as usize..end as usize];
                let content = crate::inline::parse_inlines(content_slice, start, input);
                items.push(ListItem {
                    blocks: vec![Block::Paragraph(Paragraph {
                        content,
                        span: Span::new(start, end),
                    })],
                    span: Span::new(start, end),
                });
            }
        };

        while let Some(&line) = lexer.peek_line() {
            let text = &input[line.span.start as usize..line.span.end as usize];
            let trimmed = text.trim();

            if trimmed == "::" {
                lexer.next_line();
                finalize_item(&mut items, item_start.take(), item_end);
                end_span = line.span;
                break;
            }

            if trimmed.starts_with("- ") {
                lexer.next_line();
                finalize_item(&mut items, item_start.take(), item_end);
                let dash_offset = text.find("- ").unwrap_or(0);
                item_start = Some(line.span.start + dash_offset as u32 + 2);
                item_end = line.span.end;
                last_span = line.span;
                end_span = line.span;
                continue;
            }

            if trimmed.starts_with("| ") {
                lexer.next_line();
                item_end = line.span.end;
                last_span = line.span;
                end_span = line.span;
                continue;
            }

            if line.is_blank() {
                lexer.next_line();
                last_span = line.span;
                end_span = line.span;
                continue;
            }

            if trimmed.starts_with("::")
                || trimmed.starts_with("```")
                || trimmed.starts_with('#')
                || trimmed.starts_with("@profile")
                || trimmed.starts_with("@modules")
                || trimmed == "---"
                || trimmed.starts_with("--- meta ---")
            {
                self.record_error(ParseError::unclosed_delimiter("::list", Some(start_span)));
                finalize_item(&mut items, item_start.take(), item_end);
                end_span = last_span;
                break;
            }

            self.record_error(ParseError::invalid_syntax("list item", Some(line.span)));
            finalize_item(&mut items, item_start.take(), item_end);
            end_span = last_span;
            break;
        }

        Some(Block::List(List {
            kind,
            start: start_num,
            items,
            span: Span::new(start_span.start, end_span.end),
        }))
    }

    #[inline]
    fn parse_callout_block<'a>(&mut self, lexer: &mut Lexer, input: &'a str) -> Option<Block<'a>> {
        let (start_span, kind, title) = {
            let open_line = lexer.next_line()?;
            let text = &input[open_line.span.start as usize..open_line.span.end as usize];
            let trimmed = text.trim();
            let after_callout = trimmed.strip_prefix("::callout").unwrap_or("").trim();
            let (k, t) = self.parse_callout_attrs(after_callout, input, open_line.span.start);
            (open_line.span, k, t)
        };

        let (blocks, end_span) = self.parse_until_fence_close(lexer, input);

        Some(Block::Callout(Callout {
            kind,
            title,
            blocks,
            span: Span::new(start_span.start, end_span.end),
        }))
    }

    #[inline]
    fn parse_callout_attrs<'a>(
        &self,
        s: &str,
        _input: &'a str,
        _base: u32,
    ) -> (CowStr<'a>, Option<CowStr<'a>>) {
        let mut kind: CowStr<'a> = Cow::Owned("note".to_string());
        let mut title: Option<CowStr<'a>> = None;

        let mut remaining = s;
        while !remaining.is_empty() {
            let eq_pos = match remaining.find('=') {
                Some(p) => p,
                None => break,
            };

            let key = remaining[..eq_pos].trim();
            remaining = remaining[eq_pos + 1..].trim_start();

            if remaining.starts_with('"') {
                if let Some(end) = remaining[1..].find('"') {
                    let val = &remaining[1..end + 1];
                    remaining = remaining[end + 2..].trim_start();

                    match key {
                        "type" => kind = Cow::Owned(val.to_string()),
                        "title" => title = Some(Cow::Owned(val.to_string())),
                        _ => {}
                    }
                } else {
                    break;
                }
            } else {
                let end = remaining.find(' ').unwrap_or(remaining.len());
                let val = &remaining[..end];
                remaining = remaining[end..].trim_start();

                match key {
                    "type" => kind = Cow::Owned(val.to_string()),
                    "title" => title = Some(Cow::Owned(val.to_string())),
                    _ => {}
                }
            }
        }

        (kind, title)
    }

    #[inline]
    fn parse_quote_block<'a>(&mut self, lexer: &mut Lexer, input: &'a str) -> Option<Block<'a>> {
        let start_span = lexer.next_line()?.span;
        let (blocks, end_span) = self.parse_until_fence_close(lexer, input);

        Some(Block::Quote(Quote {
            blocks,
            span: Span::new(start_span.start, end_span.end),
        }))
    }

    #[inline]
    fn parse_figure_block<'a>(&mut self, lexer: &mut Lexer, input: &'a str) -> Option<Block<'a>> {
        let (start_span, src, alt, caption) = {
            let open_line = lexer.next_line()?;
            let text = &input[open_line.span.start as usize..open_line.span.end as usize];
            let trimmed = text.trim();
            let after_figure = trimmed.strip_prefix("::figure").unwrap_or("").trim();
            let (s, a, c) = self.parse_figure_attrs(after_figure);
            (open_line.span, s, a, c)
        };

        let mut end_span = start_span;
        if let Some(line) = lexer.peek_line() {
            if line.trimmed() == "::" {
                end_span = line.span;
                lexer.next_line();
            }
        }

        Some(Block::Figure(Figure {
            src,
            alt,
            caption,
            span: Span::new(start_span.start, end_span.end),
        }))
    }

    #[inline]
    fn parse_figure_attrs<'a>(&self, s: &str) -> (CowStr<'a>, CowStr<'a>, Option<CowStr<'a>>) {
        let mut src: CowStr<'a> = Cow::Owned(String::new());
        let mut alt: CowStr<'a> = Cow::Owned(String::new());
        let mut caption: Option<CowStr<'a>> = None;

        let mut remaining = s;
        while !remaining.is_empty() {
            let eq_pos = match remaining.find('=') {
                Some(p) => p,
                None => break,
            };

            let key = remaining[..eq_pos].trim();
            remaining = remaining[eq_pos + 1..].trim_start();

            if remaining.starts_with('"') {
                if let Some(end) = remaining[1..].find('"') {
                    let val = remaining[1..end + 1].to_string();
                    remaining = remaining[end + 2..].trim_start();

                    match key {
                        "src" => src = Cow::Owned(val),
                        "alt" => alt = Cow::Owned(val),
                        "caption" => caption = Some(Cow::Owned(val)),
                        _ => {}
                    }
                } else {
                    break;
                }
            } else {
                let end = remaining.find(' ').unwrap_or(remaining.len());
                let val = remaining[..end].to_string();
                remaining = remaining[end..].trim_start();

                match key {
                    "src" => src = Cow::Owned(val),
                    "alt" => alt = Cow::Owned(val),
                    "caption" => caption = Some(Cow::Owned(val)),
                    _ => {}
                }
            }
        }

        (src, alt, caption)
    }

    #[inline]
    fn parse_table_block<'a>(&mut self, lexer: &mut Lexer, input: &'a str) -> Option<Block<'a>> {
        let start_span = lexer.next_line()?.span;

        let mut rows: Vec<TableRow<'a>> = Vec::with_capacity(8);
        let mut end_span = start_span;
        let mut found_separator = false;

        loop {
            let (is_close, is_sep, is_row, span, line_text) = {
                match lexer.peek_line() {
                    Some(line) => {
                        let text = &input[line.span.start as usize..line.span.end as usize];
                        let trimmed = text.trim();
                        (
                            trimmed == "::",
                            trimmed.starts_with('|') && trimmed.contains("---"),
                            trimmed.starts_with('|'),
                            line.span,
                            trimmed,
                        )
                    }
                    None => break,
                }
            };

            if is_close {
                end_span = span;
                lexer.next_line();
                break;
            }

            if is_sep {
                found_separator = true;
                end_span = span;
                lexer.next_line();
                continue;
            }

            if is_row {
                let cells = self.parse_table_row(line_text, span.start, input);
                let is_header = !found_separator && rows.is_empty();
                rows.push(TableRow {
                    cells,
                    header: is_header,
                    span,
                });
                end_span = span;
                lexer.next_line();
                continue;
            }

            self.record_error(ParseError::unclosed_delimiter("::table", Some(start_span)));
            break;
        }

        Some(Block::Table(Table {
            rows,
            span: Span::new(start_span.start, end_span.end),
        }))
    }

    #[inline]
    fn parse_table_row<'a>(
        &self,
        line: &'a str,
        base_offset: u32,
        input: &'a str,
    ) -> Vec<TableCell<'a>> {
        let mut cells = Vec::with_capacity(8);
        let mut offset = base_offset;

        for (i, part) in line.split('|').enumerate() {
            if i == 0 {
                offset += part.len() as u32 + 1;
                continue;
            }

            let trimmed = part.trim();
            if trimmed.is_empty() {
                offset += part.len() as u32 + 1;
                continue;
            }

            let content = crate::inline::parse_inlines(trimmed, offset, input);
            cells.push(TableCell {
                content,
                span: Span::new(offset, offset + part.len() as u32),
            });

            offset += part.len() as u32 + 1;
        }

        cells
    }

    #[inline]
    fn parse_footnotes_block<'a>(
        &mut self,
        lexer: &mut Lexer,
        input: &'a str,
    ) -> Option<Block<'a>> {
        let start_span = lexer.next_line()?.span;

        let mut defs: Vec<FootnoteDef<'a>> = Vec::with_capacity(4);
        let mut end_span = start_span;

        loop {
            let (is_close, is_def, span, label, content_text) = {
                match lexer.peek_line() {
                    Some(line) => {
                        let text = &input[line.span.start as usize..line.span.end as usize];
                        let trimmed = text.trim();
                        let is_close = trimmed == "::";
                        let mut is_def = false;
                        let mut label = "";
                        let mut content = "";

                        if trimmed.starts_with("[^") {
                            if let Some(bracket_end) = trimmed.find("]:") {
                                is_def = true;
                                label = &trimmed[2..bracket_end];
                                content = trimmed[bracket_end + 2..].trim();
                            }
                        }
                        (is_close, is_def, line.span, label, content)
                    }
                    None => break,
                }
            };

            if is_close {
                end_span = span;
                lexer.next_line();
                break;
            }

            if is_def {
                let content_inlines = crate::inline::parse_inlines(content_text, span.start, input);
                defs.push(FootnoteDef {
                    label: Cow::Owned(label.to_string()),
                    blocks: vec![Block::Paragraph(Paragraph {
                        content: content_inlines,
                        span,
                    })],
                    span,
                });
            }

            end_span = span;
            lexer.next_line();
        }

        Some(Block::Footnotes(Footnotes {
            defs,
            span: Span::new(start_span.start, end_span.end),
        }))
    }

    #[inline]
    fn parse_math_block<'a>(&mut self, lexer: &mut Lexer, input: &'a str) -> Option<Block<'a>> {
        let (start_span, display) = {
            let open_line = lexer.next_line()?;
            let text = &input[open_line.span.start as usize..open_line.span.end as usize];
            let trimmed = text.trim();
            let d = trimmed.contains("block") || trimmed.contains("display");
            (open_line.span, d)
        };

        // Content starts after opening fence, clamped to input length
        let content_start = (start_span.end as usize + 1).min(input.len());
        let mut content_end = content_start;
        let mut end_span = start_span;

        loop {
            let (is_close, span) = {
                match lexer.peek_line() {
                    Some(line) => (line.trimmed() == "::", line.span),
                    None => break,
                }
            };

            if is_close {
                end_span = span;
                lexer.next_line();
                break;
            }

            content_end = span.end as usize;
            end_span = span;
            lexer.next_line();
        }

        let content = if content_start < content_end && content_end <= input.len() {
            &input[content_start..content_end]
        } else {
            ""
        };

        Some(Block::Math(MathBlock {
            display,
            content: Cow::Borrowed(content),
            span: Span::new(start_span.start, end_span.end),
        }))
    }

    #[inline]
    fn parse_raw_fenced_block<'a>(
        &mut self,
        lexer: &mut Lexer,
        input: &'a str,
    ) -> Option<Block<'a>> {
        let start_span = lexer.next_line()?.span;

        // Content starts after opening fence, clamped to input length
        let content_start = (start_span.end as usize + 1).min(input.len());
        let mut content_end = content_start;
        let mut end_span = start_span;

        loop {
            let (is_close, span) = {
                match lexer.peek_line() {
                    Some(line) => (line.trimmed() == "::", line.span),
                    None => break,
                }
            };

            if is_close {
                end_span = span;
                lexer.next_line();
                break;
            }

            content_end = span.end as usize;
            end_span = span;
            lexer.next_line();
        }

        let content = if content_start < content_end && content_end <= input.len() {
            &input[content_start..content_end]
        } else {
            ""
        };

        Some(Block::Raw(RawBlock {
            content: Cow::Borrowed(content),
            span: Span::new(start_span.start, end_span.end),
        }))
    }

    #[inline]
    fn parse_until_fence_close<'a>(
        &mut self,
        lexer: &mut Lexer,
        input: &'a str,
    ) -> (Vec<Block<'a>>, Span) {
        let mut blocks = Vec::with_capacity(4);
        let mut para_start: Option<u32> = None;
        let mut para_end: u32 = 0;
        let mut end_span = Span::new(0, 0);

        loop {
            let (is_close, is_blank, span) = {
                match lexer.next_line() {
                    Some(line) => (line.trimmed() == "::", line.is_blank(), line.span),
                    None => break,
                }
            };

            if is_close {
                if let Some(start) = para_start {
                    let content_slice = &input[start as usize..para_end as usize];
                    let content = crate::inline::parse_inlines(content_slice, start, input);
                    blocks.push(Block::Paragraph(Paragraph {
                        content,
                        span: Span::new(start, para_end),
                    }));
                }
                end_span = span;
                break;
            }

            if is_blank {
                if let Some(start) = para_start.take() {
                    let content_slice = &input[start as usize..para_end as usize];
                    let content = crate::inline::parse_inlines(content_slice, start, input);
                    blocks.push(Block::Paragraph(Paragraph {
                        content,
                        span: Span::new(start, para_end),
                    }));
                }
            } else {
                if para_start.is_none() {
                    para_start = Some(span.start);
                }
                para_end = span.end;
            }

            end_span = span;
        }

        (blocks, end_span)
    }

    #[inline]
    fn parse_paragraph<'a>(&mut self, lexer: &mut Lexer, input: &'a str) -> Option<Block<'a>> {
        let mut start_span: Option<Span> = None;
        let mut end_span = Span::new(0, 0);

        loop {
            let should_break = {
                match lexer.peek_line() {
                    Some(line) => {
                        if line.is_blank() {
                            true
                        } else {
                            let trimmed = line.trimmed();
                            let first = trimmed.as_bytes().first().copied();
                            match first {
                                Some(b'#') | Some(b':') => true,
                                Some(b'`') if trimmed.starts_with("```") => true,
                                Some(b'-') if trimmed == "---" => true,
                                _ => false,
                            }
                        }
                    }
                    None => true,
                }
            };

            if should_break {
                break;
            }

            let line = lexer.next_line().unwrap();
            if start_span.is_none() {
                start_span = Some(line.span);
            }
            end_span = line.span;
        }

        let start = start_span?;
        let content_slice = &input[start.start as usize..end_span.end as usize];
        let content = crate::inline::parse_inlines(content_slice, start.start, input);

        Some(Block::Paragraph(Paragraph {
            content,
            span: Span::new(start.start, end_span.end),
        }))
    }
}