acdc-parser 0.11.0

`AsciiDoc` 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
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
use crate::{ColumnStyle, HorizontalAlignment, Table, VerticalAlignment};

pub(crate) const MAX_TABLE_COLUMNS: usize = 100;
pub(crate) const MAX_TABLE_ROWS: usize = 1_000;

/// A cell part with its unescaped content and original start position.
struct CellPart {
    /// Unescaped content (e.g., `\|` becomes `|`)
    content: String,
    /// Start position in the original line
    start: usize,
}

/// Split a line by separator, respecting backslash escapes.
///
/// For PSV (`|`) and DSV (`:`), a backslash before the separator escapes it.
/// Returns parts with their original byte positions for accurate source mapping.
fn split_escaped(line: &str, separator: char) -> Vec<CellPart> {
    let mut parts = Vec::new();
    let mut current_content = String::new();
    let mut part_start = 0;
    let mut chars = line.char_indices().peekable();

    while let Some((byte_idx, ch)) = chars.next() {
        if ch == '\\' {
            // Check if next char is the separator
            if let Some(&(_, next_ch)) = chars.peek()
                && next_ch == separator
            {
                current_content.push(separator);
                chars.next();
                continue;
            }
            // Not an escape - add backslash literally
            current_content.push(ch);
        } else if ch == separator {
            // Unescaped separator - end current part
            parts.push(CellPart {
                content: std::mem::take(&mut current_content),
                start: part_start,
            });
            part_start = byte_idx + ch.len_utf8();
        } else {
            current_content.push(ch);
        }
    }

    // Add final part
    parts.push(CellPart {
        content: current_content,
        start: part_start,
    });

    parts
}

/// Split a single line into cell parts for line-per-row formats (DSV, TSV, or a
/// custom multi-character separator). Single-character separators honor `\`
/// escapes; multi-character separators are matched literally.
fn split_row_line(line: &str, separator: &str) -> Vec<CellPart> {
    match separator.chars().next() {
        Some(sep_char) if separator.len() == 1 => split_escaped(line, sep_char),
        Some(_) => split_multi_char(line, separator),
        None => vec![CellPart {
            content: line.to_string(),
            start: 0,
        }],
    }
}

/// Split by a multi-character separator (no escape handling).
fn split_multi_char(line: &str, separator: &str) -> Vec<CellPart> {
    let mut parts = Vec::new();
    let mut last_end = 0;
    for (idx, _) in line.match_indices(separator) {
        parts.push(CellPart {
            content: line.get(last_end..idx).unwrap_or("").to_string(),
            start: last_end,
        });
        last_end = idx + separator.len();
    }
    parts.push(CellPart {
        content: line.get(last_end..).unwrap_or("").to_string(),
        start: last_end,
    });
    parts
}

/// Parse a CSV-style table body using the `csv` crate for full RFC 4180
/// compliance. Used for both CSV (`,`) and TSV (`\t`) — `delimiter` selects
/// which.
///
/// This handles multi-line quoted values, escaped quotes, and all CSV edge cases.
/// Returns rows with cells containing their content and accurate byte positions.
fn parse_csv_table(text: &str, base_offset: usize, delimiter: u8) -> Vec<Vec<CellPart>> {
    let text_bytes = text.as_bytes();
    let mut reader = csv::ReaderBuilder::new()
        .has_headers(false)
        .flexible(true) // allow variable column counts
        .delimiter(delimiter)
        .from_reader(text_bytes);

    let mut rows = Vec::new();

    for result in reader.records() {
        let Ok(record) = result else {
            continue;
        };

        // Get the byte position where this record starts in the input
        let record_start = record
            .position()
            .map_or(0, |p| usize::try_from(p.byte()).unwrap_or(0));

        let mut cells = Vec::new();
        let mut scan_pos = record_start;

        for field in &record {
            // Find actual field position by scanning the original text
            let (field_content_start, next_pos) =
                find_csv_field_position(text_bytes, scan_pos, field, delimiter);

            cells.push(CellPart {
                content: field.to_string(),
                start: base_offset + field_content_start,
            });

            scan_pos = next_pos;
        }

        rows.push(cells);
    }

    rows
}

/// Find the actual byte position of a CSV field's content in the original text.
///
/// Returns `(content_start, next_scan_position)` where:
/// - `content_start` is where the field's actual content begins (after opening quote if quoted)
/// - `next_scan_position` is where to start scanning for the next field
fn find_csv_field_position(
    text: &[u8],
    start: usize,
    expected_content: &str,
    delimiter: u8,
) -> (usize, usize) {
    let Some(&first_byte) = text.get(start) else {
        return (start, start);
    };

    if first_byte == b'"' {
        // Quoted field: content starts after the opening quote
        let content_start = start + 1;
        // Find the closing quote (handle escaped quotes "")
        let end_pos = find_closing_quote(text, start + 1);
        // Next field starts after closing quote and delimiter (or newline)
        let next_pos = skip_to_next_field(text, end_pos, delimiter);
        (content_start, next_pos)
    } else {
        // Unquoted field: content starts at current position
        let content_start = start;
        // Find end of field (delimiter or newline)
        let end_pos = find_unquoted_field_end(text, start, expected_content.len(), delimiter);
        // Next field starts after the separator
        let next_pos = skip_to_next_field(text, end_pos, delimiter);
        (content_start, next_pos)
    }
}

/// Find the closing quote of a quoted CSV field, handling escaped quotes (`""`).
fn find_closing_quote(text: &[u8], start: usize) -> usize {
    let mut pos = start;
    while let Some(&byte) = text.get(pos) {
        if byte == b'"' {
            // Check if this is an escaped quote ("")
            if text.get(pos + 1) == Some(&b'"') {
                // Escaped quote - skip both and continue
                pos += 2;
            } else {
                // Closing quote found
                return pos;
            }
        } else {
            pos += 1;
        }
    }
    // No closing quote found - return end of text
    text.len()
}

/// Find the end of an unquoted CSV field.
fn find_unquoted_field_end(text: &[u8], start: usize, content_len: usize, delimiter: u8) -> usize {
    // The field ends at the delimiter, CR, LF, or content_len bytes (whichever comes first)
    let mut pos = start;
    let mut remaining = content_len;
    while let Some(&byte) = text.get(pos) {
        if byte == delimiter || byte == b'\n' || byte == b'\r' {
            return pos;
        }
        if remaining == 0 {
            return pos;
        }
        remaining = remaining.saturating_sub(1);
        pos += 1;
    }
    text.len()
}

/// Skip past the current field separator to find the start of the next field.
fn skip_to_next_field(text: &[u8], pos: usize, delimiter: u8) -> usize {
    let mut pos = pos;
    // Skip closing quote if present
    if text.get(pos) == Some(&b'"') {
        pos += 1;
    }
    // Skip the delimiter or newline characters
    while let Some(&byte) = text.get(pos) {
        if byte == delimiter {
            return pos + 1;
        }
        if byte == b'\r' || byte == b'\n' {
            // Skip CRLF or just LF
            if byte == b'\r' && text.get(pos + 1) == Some(&b'\n') {
                return pos + 2;
            }
            return pos + 1;
        }
        pos += 1;
    }
    pos
}

/// The delimiter byte for CSV-style (RFC 4180 quoted) formats, or `None` for
/// separators handled line-per-row. asciidoctor parses both CSV (`,`) and TSV
/// (`\t`) with the same quoting rules; DSV (`:`) and custom separators are not
/// quote-aware.
fn csv_style_delimiter(separator: &str) -> Option<u8> {
    match separator {
        "," => Some(b','),
        "\t" => Some(b'\t'),
        _ => None,
    }
}

/// Represents a parsed cell specifier with span, alignment, and style information.
///
/// In `AsciiDoc`, cell specifiers appear before the cell separator with format:
/// `[colspan][.rowspan][op][halign][valign][style]|`. Alignment without a span
/// can appear directly before the style and separator.
///
/// Examples:
/// - `2+|content` → colspan=2
/// - `.3+|content` → rowspan=3
/// - `2.3+|content` → colspan=2, rowspan=3
/// - `2+^.>s|content` → center, bottom, colspan=2, strong style
/// - `3*|content` → duplicate cell 3 times
#[derive(Debug, Clone, Copy)]
pub(crate) struct CellSpecifier {
    pub colspan: usize,
    pub rowspan: usize,
    pub halign: Option<HorizontalAlignment>,
    pub valign: Option<VerticalAlignment>,
    pub style: Option<ColumnStyle>,
    /// If true, this is a duplication specifier (`*`) rather than a span (`+`).
    pub is_duplication: bool,
    /// For duplication, this is the count (e.g., `3*` means 3 copies).
    pub duplication_count: usize,
}

impl Default for CellSpecifier {
    fn default() -> Self {
        Self {
            colspan: 1,
            rowspan: 1,
            halign: None,
            valign: None,
            style: None,
            is_duplication: false,
            duplication_count: 1,
        }
    }
}

/// Parse a single style letter into a `ColumnStyle`.
fn parse_style_byte(byte: u8) -> Option<ColumnStyle> {
    match byte {
        b'a' => Some(ColumnStyle::AsciiDoc),
        b'd' => Some(ColumnStyle::Default),
        b'e' => Some(ColumnStyle::Emphasis),
        b'h' => Some(ColumnStyle::Header),
        b'l' => Some(ColumnStyle::Literal),
        b'm' => Some(ColumnStyle::Monospace),
        b's' => Some(ColumnStyle::Strong),
        _ => None,
    }
}

impl CellSpecifier {
    /// Parse a cell specifier from the beginning of cell content.
    ///
    /// Returns the specifier and the offset where actual content begins. A
    /// specifier is only ever recognized as the line-leading token before a
    /// cell delimiter, so style-only specifiers (e.g. `s|` for strong) are
    /// always accepted here.
    /// Full pattern: `[colspan][.rowspan][+|*][halign][valign][style]`
    ///
    /// Examples:
    /// - `"2+rest"` → colspan=2
    /// - `".3+rest"` → rowspan=3
    /// - `"2.3+rest"` → colspan=2, rowspan=3
    /// - `"2+^.>srest"` → center, bottom, colspan=2, strong style
    /// - `"3*rest"` → `duplication_count`=3
    /// - `"plain"` → defaults (no specifier found)
    #[must_use]
    pub fn parse(content: &str) -> (Self, usize) {
        let bytes = content.as_bytes();
        let mut pos = 0;

        // Parse optional alignment markers
        let (halign, valign, align_end) = Self::parse_alignments(bytes, pos);
        pos = align_end;

        // Parse optional `colspan` (digits)
        let (colspan, colspan_end) = Self::parse_number(content, bytes, pos);
        pos = colspan_end;

        // Parse optional `rowspan` (dot followed by digits)
        let (rowspan, rowspan_end) = Self::parse_rowspan(content, bytes, pos);
        pos = rowspan_end;

        // Check for operator and build result
        Self::build(bytes, pos, colspan, rowspan, halign, valign)
    }

    /// Parse alignment markers at the current position.
    /// Returns `(halign, valign, new_position)`.
    fn parse_alignments(
        bytes: &[u8],
        mut pos: usize,
    ) -> (
        Option<HorizontalAlignment>,
        Option<VerticalAlignment>,
        usize,
    ) {
        let mut halign: Option<HorizontalAlignment> = None;
        let mut valign: Option<VerticalAlignment> = None;

        loop {
            match bytes.get(pos) {
                Some(b'<') => {
                    halign = Some(HorizontalAlignment::Left);
                    pos += 1;
                }
                Some(b'^') => {
                    halign = Some(HorizontalAlignment::Center);
                    pos += 1;
                }
                Some(b'>') => {
                    halign = Some(HorizontalAlignment::Right);
                    pos += 1;
                }
                Some(b'.') => {
                    // Could be vertical alignment (.< .^ .>) or rowspan (.N)
                    match bytes.get(pos + 1) {
                        Some(b'<') => {
                            valign = Some(VerticalAlignment::Top);
                            pos += 2;
                        }
                        Some(b'^') => {
                            valign = Some(VerticalAlignment::Middle);
                            pos += 2;
                        }
                        Some(b'>') => {
                            valign = Some(VerticalAlignment::Bottom);
                            pos += 2;
                        }
                        _ => break, // Not vertical alignment, might be rowspan
                    }
                }
                _ => break,
            }
        }

        (halign, valign, pos)
    }

    /// Parse a number (for colspan) at the current position.
    /// Returns `(parsed_value, new_position)`.
    fn parse_number(content: &str, bytes: &[u8], mut pos: usize) -> (Option<usize>, usize) {
        let start = pos;
        while bytes.get(pos).is_some_and(u8::is_ascii_digit) {
            pos += 1;
        }
        let value = if pos > start {
            content
                .get(start..pos)
                .and_then(|s| s.parse::<usize>().ok())
        } else {
            None
        };
        (value, pos)
    }

    /// Parse `rowspan` (dot followed by digits) at the current position.
    /// Returns `(parsed_value, new_position)`.
    fn parse_rowspan(content: &str, bytes: &[u8], mut pos: usize) -> (Option<usize>, usize) {
        if bytes.get(pos) != Some(&b'.') {
            return (None, pos);
        }

        let dot_pos = pos;
        pos += 1;
        let start = pos;
        while bytes.get(pos).is_some_and(u8::is_ascii_digit) {
            pos += 1;
        }

        if pos > start {
            let value = content
                .get(start..pos)
                .and_then(|s| s.parse::<usize>().ok());
            (value, pos)
        } else {
            // Dot without following digits - not a rowspan specifier
            (None, dot_pos)
        }
    }

    /// Build the final result based on parsed components.
    fn build(
        bytes: &[u8],
        mut pos: usize,
        colspan: Option<usize>,
        rowspan: Option<usize>,
        halign: Option<HorizontalAlignment>,
        valign: Option<VerticalAlignment>,
    ) -> (Self, usize) {
        let has_span_or_dup = colspan.is_some() || rowspan.is_some();
        let is_duplication = bytes.get(pos) == Some(&b'*');
        let is_span = bytes.get(pos) == Some(&b'+');

        if (is_span || is_duplication) && has_span_or_dup {
            pos += 1;

            // Asciidoctor places alignment after the span operator. Keep
            // accepting the older acdc alignment-first order as well.
            let (after_span_horizontal, after_span_vertical, alignment_end) =
                Self::parse_alignments(bytes, pos);
            pos = alignment_end;
            let halign = after_span_horizontal.or(halign);
            let valign = after_span_vertical.or(valign);

            // Parse optional style letter after operator
            let style = bytes.get(pos).and_then(|&b| parse_style_byte(b));
            if style.is_some() {
                pos += 1;
            }

            let spec = if is_duplication {
                Self {
                    colspan: 1,
                    rowspan: 1,
                    halign,
                    valign,
                    style,
                    is_duplication: true,
                    duplication_count: colspan.unwrap_or(1),
                }
            } else {
                Self {
                    colspan: colspan.unwrap_or(1),
                    rowspan: rowspan.unwrap_or(1),
                    halign,
                    valign,
                    style,
                    is_duplication: false,
                    duplication_count: 1,
                }
            };
            (spec, pos)
        } else if halign.is_some() || valign.is_some() {
            // Alignment without span operator - still valid.
            let style = bytes.get(pos).and_then(|&b| parse_style_byte(b));
            if style.is_some() {
                pos += 1;
            }
            (
                Self {
                    colspan: 1,
                    rowspan: 1,
                    halign,
                    valign,
                    style,
                    is_duplication: false,
                    duplication_count: 1,
                },
                pos,
            )
        } else if let Some(style) = bytes.get(pos).and_then(|&b| parse_style_byte(b)) {
            // Style-only specifier (e.g., `s|` for strong).
            pos += 1;
            (
                Self {
                    colspan: 1,
                    rowspan: 1,
                    halign: None,
                    valign: None,
                    style: Some(style),
                    is_duplication: false,
                    duplication_count: 1,
                },
                pos,
            )
        } else {
            // No valid specifier found
            (Self::default(), 0)
        }
    }
}

/// A parsed table cell with position, span, alignment, and style information.
///
/// `start` marks the document offset of the cell as a whole (the byte just
/// past the cell specifier and separator). `content_start` marks the offset
/// of the first byte of `content` in the document — they diverge when the
/// cell's content begins on a continuation line, e.g.:
///
/// ```text
/// a|              <- start points here (end of `a|`)
/// !===            <- content_start points here
/// ```
///
/// Recursive parsers consuming the cell content (in particular the
/// `AsciiDoc`-style `a|` cell) must use `content_start` so that diagnostics
/// resolve to the line of the offending token, not the cell's style prefix.
#[derive(Debug)]
pub(crate) struct ParsedCell {
    pub content: String,
    pub start: usize,
    pub content_start: usize,
    pub end: usize,
    pub spec: CellSpecifier,
}

#[derive(Debug)]
pub(crate) struct TableLimitViolation {
    pub(crate) resource: &'static str,
    pub(crate) requested: usize,
    pub(crate) limit: usize,
    pub(crate) start: usize,
    pub(crate) end: usize,
}

impl TableLimitViolation {
    const fn new(
        resource: &'static str,
        requested: usize,
        limit: usize,
        start: usize,
        end: usize,
    ) -> Self {
        Self {
            resource,
            requested,
            limit,
            start,
            end,
        }
    }
}

/// Check if a blank line after the first row indicates a header.
/// A header is indicated only if the first non-empty line after the blank
/// contains a separator. If it's a continuation line (no separator), it's content
/// that attaches to the previous cell, not a header indicator.
fn detect_header_after_first_row(lines: &[&str], start_idx: usize, separator: &str) -> bool {
    for &line in lines.iter().skip(start_idx) {
        let trimmed = line.trim_end();
        if !trimmed.is_empty() {
            return trimmed.contains(separator);
        }
    }
    false
}

/// Whether cell specifiers (`a|`, `2+|`, `.3+|`, `^|`, ...) are recognized for a
/// separator. Only PSV (`|`) and the nested separator (`!`) carry specifiers; DSV (`:`)
/// cells are always plain content.
fn separator_uses_specifiers(separator: &str) -> bool {
    matches!(separator, "|" | "!")
}

/// Split a part's content into `(content_before_spec, trailing_specifier)`.
///
/// A cell specifier (`2+`, `.3+`, `^`, `a`, ...) is recognized as the trailing token
/// immediately before the delimiter that ends the part, provided it is separated from the
/// cell content by whitespace (or a newline, or the start of the table body). This
/// matches asciidoctor: `cell 2+|next` makes `next` span two columns, while `|2+|`, where
/// `2+` sits flush against the opening delimiter, keeps `2+` as literal cell content. A
/// space *between* the specifier and the delimiter (`2+ |`) likewise makes it literal.
///
/// `allow_at_start` lets a specifier flush against the very start of the table
/// body (the leading part, before the first delimiter) be recognized, so
/// `2+|cell` and `a|cell` at the start of the body work.
fn extract_trailing_spec(content: &str, allow_at_start: bool) -> (&str, Option<CellSpecifier>) {
    // The specifier sits immediately before the delimiter: trailing whitespace
    // means the `|` is a plain cell break, not a spec terminator.
    if content.is_empty() || content.ends_with([' ', '\t']) {
        return (content, None);
    }
    // The candidate is the trailing run of non-whitespace characters.
    let token_start = content.rfind([' ', '\t', '\n']).map_or(0, |i| i + 1);
    let candidate = &content[token_start..];
    let (spec, spec_len) = CellSpecifier::parse(candidate);
    if spec_len == 0 || spec_len != candidate.len() {
        return (content, None);
    }
    // Only recognized when separated from the cell content: preceded by
    // whitespace/newline (`token_start > 0`) or sitting at the very start of the
    // table body (`allow_at_start`). A spec flush against the opening delimiter
    // (`|2+|`) is literal content.
    if token_start > 0 || allow_at_start {
        (&content[..token_start], Some(spec))
    } else {
        (content, None)
    }
}

/// Scan the table body into a flat stream of cells.
///
/// The whole body is split on the separator (respecting `\|` escapes), so
/// newlines and blank lines are insignificant for cell boundaries — a cell's
/// content runs until the next unescaped delimiter, spanning as many physical
/// lines as needed. This mirrors asciidoctor's PSV/DSV model and is what makes
/// multi-line cells and rows split across lines parse correctly.
fn scan_cells(text: &str, separator: &str, base_offset: usize) -> Vec<ParsedCell> {
    let Some(sep_char) = separator.chars().next() else {
        return Vec::new();
    };
    let uses_spec = separator_uses_specifiers(separator);
    let parts = split_escaped(text, sep_char);
    let last_idx = parts.len().saturating_sub(1);

    let mut cells = Vec::new();
    let mut carried_spec: Option<CellSpecifier> = None;

    for (i, part) in parts.iter().enumerate() {
        // A trailing specifier only exists if another delimiter follows this part.
        let (kept, trailing_spec) = if uses_spec && i < last_idx {
            extract_trailing_spec(&part.content, i == 0)
        } else {
            (part.content.as_str(), None)
        };

        // For PSV/`!`, the leading part (before the first delimiter) is not a
        // cell — only its trailing line-leading specifier matters.
        if uses_spec && i == 0 {
            carried_spec = trailing_spec;
            continue;
        }

        let leading_ws = kept.len() - kept.trim_start().len();
        let content = kept.trim().to_string();
        let cell_start = base_offset + part.start;
        let content_start = cell_start + leading_ws;
        let end = if content.is_empty() {
            content_start
        } else {
            content_start + content.len().saturating_sub(1)
        };

        cells.push(ParsedCell {
            spec: carried_spec.take().unwrap_or_default(),
            content,
            start: cell_start,
            content_start,
            end,
        });
        carried_spec = trailing_spec;
    }

    cells
}

/// Number of cells on the first non-empty physical line of the body.
///
/// asciidoctor derives the column count from the first line when no `cols`
/// attribute is present (e.g. one `|`-led cell per line with no `cols` yields a
/// single-column table).
fn first_line_column_count(text: &str, separator: &str) -> usize {
    let Some(sep_char) = separator.chars().next() else {
        return 0;
    };
    let first_line = text
        .lines()
        .find(|line| !line.trim().is_empty())
        .unwrap_or("");
    let parts = split_escaped(first_line, sep_char);
    if separator_uses_specifiers(separator) {
        // The leading part before the first delimiter is not a cell.
        parts.len().saturating_sub(1)
    } else {
        parts.len()
    }
}

fn validate_cell_specifiers(cells: &[ParsedCell]) -> Result<(), TableLimitViolation> {
    for cell in cells {
        if cell.spec.colspan > MAX_TABLE_COLUMNS {
            return Err(TableLimitViolation::new(
                "column span",
                cell.spec.colspan,
                MAX_TABLE_COLUMNS,
                cell.start,
                cell.end,
            ));
        }
        if cell.spec.rowspan > MAX_TABLE_ROWS {
            return Err(TableLimitViolation::new(
                "row span",
                cell.spec.rowspan,
                MAX_TABLE_ROWS,
                cell.start,
                cell.end,
            ));
        }
        if cell.spec.duplication_count > MAX_TABLE_COLUMNS {
            return Err(TableLimitViolation::new(
                "cell duplication",
                cell.spec.duplication_count,
                MAX_TABLE_COLUMNS,
                cell.start,
                cell.end,
            ));
        }
    }
    Ok(())
}

fn validate_row_widths(rows: &[Vec<ParsedCell>]) -> Result<(), TableLimitViolation> {
    if rows.len() > MAX_TABLE_ROWS {
        let (start, end) = rows
            .get(MAX_TABLE_ROWS)
            .and_then(|row| row.first().zip(row.last()))
            .map_or((0, 0), |(first, last)| (first.start, last.end));
        return Err(TableLimitViolation::new(
            "row count",
            rows.len(),
            MAX_TABLE_ROWS,
            start,
            end,
        ));
    }
    for row in rows {
        if row.len() > MAX_TABLE_COLUMNS {
            let (start, end) = row
                .first()
                .zip(row.last())
                .map_or((0, 0), |(first, last)| (first.start, last.end));
            return Err(TableLimitViolation::new(
                "column count",
                row.len(),
                MAX_TABLE_COLUMNS,
                start,
                end,
            ));
        }
    }
    Ok(())
}

/// Group a flat cell stream into rows of `ncols` columns.
///
/// Placement is colspan-, duplication-, and rowspan-aware: a cell spanning
/// columns occupies them, a `k*` cell occupies `k` columns (and is expanded
/// downstream), and a `.n+` rowspan reserves its column position in the next
/// `n - 1` rows so those rows need fewer new cells. A trailing partial row that
/// cannot be completed is dropped, matching asciidoctor; its inclusive
/// `(start, end)` document offsets are written to `dropped` so the caller can
/// warn about it.
fn group_cells_into_rows(
    cells: Vec<ParsedCell>,
    ncols: usize,
    dropped: &mut Option<(usize, usize)>,
) -> Result<Vec<Vec<ParsedCell>>, TableLimitViolation> {
    let ncols = ncols.max(1);
    let mut rows = Vec::new();
    // Columns occupied by rowspans carried down from earlier rows.
    let mut active: Vec<(usize, usize, usize)> = Vec::new(); // (col, remaining_rows, width)
    let mut iter = cells.into_iter();
    let mut next = iter.next();

    while next.is_some() {
        let mut row = Vec::new();
        let mut new_spans: Vec<(usize, usize, usize)> = Vec::new();
        let mut col = 0;
        let mut filled = false;

        while col < ncols {
            // Skip columns occupied by an active rowspan from a previous row.
            if let Some(&(_, _, width)) = active
                .iter()
                .find(|(pos, _, width)| col >= *pos && col < pos + width)
            {
                col += width;
                continue;
            }
            let Some(cell) = next.take() else {
                break;
            };
            next = iter.next();

            let occupied = if cell.spec.is_duplication {
                cell.spec.duplication_count.max(1) * cell.spec.colspan.max(1)
            } else {
                cell.spec.colspan.max(1)
            };
            if cell.spec.rowspan > 1 {
                new_spans.push((col, cell.spec.rowspan - 1, occupied));
            }
            row.push(cell);
            col += occupied;
            filled = col >= ncols;
        }

        if !filled && next.is_none() {
            // Incomplete final row — asciidoctor drops it and warns. Capture
            // the span of the dropped cells for the warning location.
            if let (Some(first), Some(last)) = (row.first(), row.last()) {
                *dropped = Some((first.start, last.end));
            }
            break;
        }
        if rows.len() == MAX_TABLE_ROWS {
            let (start, end) = row
                .first()
                .zip(row.last())
                .map_or((0, 0), |(first, last)| (first.start, last.end));
            return Err(TableLimitViolation::new(
                "row count",
                rows.len() + 1,
                MAX_TABLE_ROWS,
                start,
                end,
            ));
        }
        rows.push(row);
        // Age existing rowspans, then add the ones introduced by this row.
        active.retain_mut(|(_, remaining, _)| {
            *remaining -= 1;
            *remaining > 0
        });
        active.extend(new_spans);
    }

    Ok(rows)
}

impl Table<'_> {
    pub(crate) fn parse_rows_with_positions(
        text: &str,
        separator: &str,
        has_header: &mut bool,
        base_offset: usize,
        ncols: Option<usize>,
        dropped: &mut Option<(usize, usize)>,
    ) -> Result<Vec<Vec<ParsedCell>>, TableLimitViolation> {
        // CSV-style formats (CSV, TSV) need special handling for multi-line
        // quoted values.
        if let Some(delimiter) = csv_style_delimiter(separator) {
            let rows =
                Self::parse_csv_rows_with_positions(text, has_header, base_offset, delimiter);
            validate_row_widths(&rows)?;
            return Ok(rows);
        }

        let lines: Vec<&str> = text.lines().collect();

        // Implicit header: the first physical line is immediately followed by a
        // blank line (with a real row after it). A leading blank line means
        // there is no header. We only ever *set* the header here — an explicit
        // `options="header"` from the caller is left untouched.
        if lines.first().is_some_and(|l| l.trim().is_empty()) {
            *has_header = false;
        } else if lines.get(1).is_some_and(|l| l.trim().is_empty())
            && detect_header_after_first_row(&lines, 1, separator)
        {
            tracing::debug!("Detected table header via blank line after first row");
            *has_header = true;
        }

        // PSV (`|`) and the nested separator (`!`) follow a flat cell-stream
        // model: newlines are insignificant and cells flow into rows by column
        // count. DSV (`:`), TSV (`\t`), and any custom separator are line-per-row.
        if !separator_uses_specifiers(separator) {
            let rows = Self::parse_delimited_rows(&lines, separator, base_offset);
            validate_row_widths(&rows)?;
            return Ok(rows);
        }

        // Column count: the `cols` attribute when given, otherwise the number of
        // cells on the first physical line (asciidoctor's implicit rule).
        let ncols = ncols
            .filter(|&n| n > 0)
            .unwrap_or_else(|| first_line_column_count(text, separator));
        if ncols > MAX_TABLE_COLUMNS {
            return Err(TableLimitViolation::new(
                "column count",
                ncols,
                MAX_TABLE_COLUMNS,
                base_offset,
                base_offset,
            ));
        }

        tracing::debug!(?has_header, ncols, "Starting table parsing");

        let cells = scan_cells(text, separator, base_offset);
        validate_cell_specifiers(&cells)?;
        group_cells_into_rows(cells, ncols, dropped)
    }

    /// Parse a line-per-row table body (DSV, TSV, or a custom separator).
    ///
    /// Each non-empty line is one row; the separator splits cells within the
    /// line. These formats do not use cell specifiers.
    fn parse_delimited_rows(
        lines: &[&str],
        separator: &str,
        base_offset: usize,
    ) -> Vec<Vec<ParsedCell>> {
        let mut rows = Vec::new();
        let mut offset = base_offset;
        for line in lines {
            if !line.trim().is_empty() {
                let cells: Vec<ParsedCell> = split_row_line(line, separator)
                    .into_iter()
                    .map(|part| {
                        let leading_ws = part.content.len() - part.content.trim_start().len();
                        let content = part.content.trim().to_string();
                        let start = offset + part.start + leading_ws;
                        let end = if content.is_empty() {
                            start
                        } else {
                            start + content.len().saturating_sub(1)
                        };
                        ParsedCell {
                            content,
                            start,
                            content_start: start,
                            end,
                            spec: CellSpecifier::default(),
                        }
                    })
                    .collect();
                if !cells.is_empty() {
                    rows.push(cells);
                }
            }
            offset += line.len() + 1; // +1 for newline
        }
        rows
    }

    /// Parse CSV-style (CSV/TSV) table rows using the `csv` crate for RFC 4180
    /// compliance. `delimiter` is the field separator byte.
    ///
    /// This handles multi-line quoted values correctly by processing the entire
    /// table body at once rather than line-by-line.
    fn parse_csv_rows_with_positions(
        text: &str,
        has_header: &mut bool,
        base_offset: usize,
        delimiter: u8,
    ) -> Vec<Vec<ParsedCell>> {
        // Check for header indicator: first row followed by blank line
        // For CSV, we need to detect this before parsing since the csv crate
        // consumes the text as a stream.
        let lines: Vec<&str> = text.lines().collect();
        if lines.len() >= 2 {
            // Find where first CSV record ends - look for first complete record
            // A simple heuristic: if line 1 (0-indexed) is empty, we have a header
            if let Some(&line) = lines.get(1)
                && line.trim().is_empty()
            {
                *has_header = true;
            }
        }

        let csv_rows = parse_csv_table(text, base_offset, delimiter);
        let mut rows = Vec::new();

        for csv_row in csv_rows {
            let mut cells = Vec::new();
            for part in csv_row {
                let content = part.content.trim();
                let start = part.start;
                let end = if content.is_empty() {
                    start
                } else {
                    start + content.len().saturating_sub(1)
                };

                cells.push(ParsedCell {
                    content: content.to_string(),
                    start,
                    content_start: start,
                    end,
                    spec: CellSpecifier::default(),
                });
            }
            if !cells.is_empty() {
                rows.push(cells);
            }
        }

        rows
    }
}

#[cfg(test)]
#[allow(clippy::panic, clippy::indexing_slicing)]
mod tests {
    use super::*;

    fn parse_rows(
        input: &str,
        separator: &str,
        has_header: &mut bool,
        ncols: Option<usize>,
    ) -> Vec<Vec<ParsedCell>> {
        match Table::parse_rows_with_positions(input, separator, has_header, 0, ncols, &mut None) {
            Ok(rows) => rows,
            Err(error) => panic!("table should parse: {error:?}"),
        }
    }

    #[test]
    fn combined_span_accepts_canonical_and_legacy_alignment_order() {
        for source in ["2.2+^.^e", "^.^2.2+e"] {
            let (specifier, consumed) = CellSpecifier::parse(source);

            assert_eq!(consumed, source.len());
            assert_eq!(specifier.colspan, 2);
            assert_eq!(specifier.rowspan, 2);
            assert_eq!(specifier.halign, Some(HorizontalAlignment::Center));
            assert_eq!(specifier.valign, Some(VerticalAlignment::Middle));
            assert_eq!(specifier.style, Some(ColumnStyle::Emphasis));
            assert!(!specifier.is_duplication);
        }
    }

    #[test]
    fn split_escaped_psv_no_escapes() {
        let parts = split_escaped("| cell1 | cell2 |", '|');
        let [p0, p1, p2, p3] = parts.as_slice() else {
            panic!("expected 4 parts, got {}", parts.len());
        };
        assert_eq!(p0.content, "");
        assert_eq!(p1.content, " cell1 ");
        assert_eq!(p2.content, " cell2 ");
        assert_eq!(p3.content, "");
    }

    #[test]
    fn split_escaped_psv_with_escape() {
        let parts = split_escaped(r"| cell with \| pipe | normal |", '|');
        let [p0, p1, p2, p3] = parts.as_slice() else {
            panic!("expected 4 parts, got {}", parts.len());
        };
        assert_eq!(p0.content, "");
        assert_eq!(p1.content, " cell with | pipe ");
        assert_eq!(p2.content, " normal ");
        assert_eq!(p3.content, "");
    }

    #[test]
    fn split_escaped_dsv_no_escapes() {
        let parts = split_escaped("cell1:cell2:cell3", ':');
        let [p0, p1, p2] = parts.as_slice() else {
            panic!("expected 3 parts, got {}", parts.len());
        };
        assert_eq!(p0.content, "cell1");
        assert_eq!(p1.content, "cell2");
        assert_eq!(p2.content, "cell3");
    }

    #[test]
    fn split_escaped_dsv_with_escape() {
        let parts = split_escaped(r"cell with \: colon:normal", ':');
        let [p0, p1] = parts.as_slice() else {
            panic!("expected 2 parts, got {}", parts.len());
        };
        assert_eq!(p0.content, "cell with : colon");
        assert_eq!(p1.content, "normal");
    }

    #[test]
    fn split_escaped_backslash_not_before_separator() {
        // Backslash before non-separator should be preserved
        let parts = split_escaped(r"cell\n with backslash|next", '|');
        let [p0, p1] = parts.as_slice() else {
            panic!("expected 2 parts, got {}", parts.len());
        };
        assert_eq!(p0.content, r"cell\n with backslash");
        assert_eq!(p1.content, "next");
    }

    #[test]
    fn split_escaped_multiple_escapes() {
        let parts = split_escaped(r"\|start\|middle\|end", '|');
        let [p0] = parts.as_slice() else {
            panic!("expected 1 part, got {}", parts.len());
        };
        assert_eq!(p0.content, "|start|middle|end");
    }

    #[test]
    fn split_escaped_positions_tracked() {
        let parts = split_escaped("ab|cd|ef", '|');
        let [p0, p1, p2] = parts.as_slice() else {
            panic!("expected 3 parts, got {}", parts.len());
        };
        assert_eq!(p0.start, 0);
        assert_eq!(p1.start, 3); // after "ab|"
        assert_eq!(p2.start, 6); // after "ab|cd|"
    }

    /// Trailing content after a completed row — no leading separator — is
    /// attached to the last cell as a continuation paragraph. The blank
    /// line between the row and the trailing text must survive into the
    /// cell's string content so downstream rendering produces a second
    /// paragraph (matching asciidoctor's `<p class="tableblock">...</p>`
    /// pair).
    #[test]
    fn trailing_text_becomes_continuation_paragraph_of_last_cell() {
        let input = "| A | B\n\nTrailing\n";
        let mut has_header = false;
        let rows = parse_rows(input, "|", &mut has_header, None);
        let [row] = rows.as_slice() else {
            panic!("expected 1 row, got {}", rows.len());
        };
        let [a, b] = row.as_slice() else {
            panic!("expected 2 cells, got {}", row.len());
        };
        assert_eq!(a.content, "A");
        // The blank line boundary must be preserved so the cell content,
        // when later parsed as blocks, yields a second paragraph rather
        // than a single joined line.
        assert_eq!(b.content, "B\n\nTrailing");
    }

    /// The outer parse must not collapse a blank line that lives *inside*
    /// an `a`-cell's content. If it did, a nested table's own trailing
    /// continuation paragraph would disappear when the cell is re-parsed
    /// as `AsciiDoc` blocks.
    #[test]
    fn a_cell_preserves_blank_line_inside_nested_table_content() {
        let input = "a|\n!===\n! Inner A ! Inner B\n\nTrailing in inner cell\n!===\n";
        let mut has_header = false;
        let rows = parse_rows(input, "|", &mut has_header, Some(1));
        let [row] = rows.as_slice() else {
            panic!("expected 1 row, got {}", rows.len());
        };
        let [cell] = row.as_slice() else {
            panic!("expected 1 cell, got {}", row.len());
        };
        assert_eq!(
            cell.content,
            "!===\n! Inner A ! Inner B\n\nTrailing in inner cell\n!===",
        );
    }

    /// A cell whose content continues on the next line (no separator on that
    /// line) belongs to the same cell — newlines do not delimit cells.
    #[test]
    fn multiline_cell_content_stays_in_one_cell() {
        let input = "| a | b\nstill b\n| c | d\n";
        let mut has_header = false;
        let rows = parse_rows(input, "|", &mut has_header, Some(2));
        let contents: Vec<Vec<&str>> = rows
            .iter()
            .map(|r| r.iter().map(|c| c.content.as_str()).collect())
            .collect();
        assert_eq!(contents, vec![vec!["a", "b\nstill b"], vec!["c", "d"]]);
    }

    /// A logical row split so later cells start with a delimiter on their own
    /// line still groups into one row by column count.
    #[test]
    fn row_split_across_lines_groups_by_column_count() {
        let input = "| a\n| b\n| c\n| d\n";
        let mut has_header = false;
        let rows = parse_rows(input, "|", &mut has_header, Some(2));
        let contents: Vec<Vec<&str>> = rows
            .iter()
            .map(|r| r.iter().map(|c| c.content.as_str()).collect())
            .collect();
        assert_eq!(contents, vec![vec!["a", "b"], vec!["c", "d"]]);
    }

    /// Rowspans reserve their column in following rows, so those rows need
    /// fewer new cells — the flat stream must group accordingly.
    #[test]
    fn rowspan_aware_grouping() {
        let input = ".2+| spans | b | c\n| e | f\n| g | h | i\n";
        let mut has_header = false;
        let rows = parse_rows(input, "|", &mut has_header, Some(3));
        let contents: Vec<Vec<&str>> = rows
            .iter()
            .map(|r| r.iter().map(|c| c.content.as_str()).collect())
            .collect();
        assert_eq!(
            contents,
            vec![vec!["spans", "b", "c"], vec!["e", "f"], vec!["g", "h", "i"]]
        );
        assert_eq!(rows[0][0].spec.rowspan, 2);
    }

    /// TSV fields use the same RFC 4180 quoting as CSV: a `"…"`-quoted value can
    /// span lines and the quotes are stripped (matching asciidoctor), rather
    /// than being split at the newline.
    #[test]
    fn tsv_quoted_field_spans_lines() {
        let input = "a\t\"line1\nline2\"\nb\tc\n";
        let mut has_header = false;
        let rows = parse_rows(input, "\t", &mut has_header, None);
        let contents: Vec<Vec<&str>> = rows
            .iter()
            .map(|r| r.iter().map(|c| c.content.as_str()).collect())
            .collect();
        assert_eq!(contents, vec![vec!["a", "line1\nline2"], vec!["b", "c"]]);
    }
}