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
//! Table types for `AsciiDoc` documents.

use serde::Serialize;

use super::{
    AttributeName, AttributeValue, Block, BlockMetadata, DocumentAttributeAssignment,
    location::Location,
};

/// The outer border applied to a table.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TableFrame {
    /// Draw all four outer edges.
    #[default]
    All,
    /// Draw only the top and bottom edges.
    Ends,
    /// Draw only the left and right edges.
    Sides,
    /// Draw no outer edge.
    None,
}

/// The rules drawn between table cells.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TableGrid {
    /// Draw rules between rows and columns.
    #[default]
    All,
    /// Draw rules only between rows.
    Rows,
    /// Draw rules only between columns.
    Columns,
    /// Draw no rules between cells.
    None,
}

/// The body rows that receive a background fill.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TableStripes {
    /// Do not fill body rows.
    #[default]
    None,
    /// Fill every body row.
    All,
    /// Fill odd body rows.
    Odd,
    /// Fill even body rows.
    Even,
    /// Fill the body row under the pointer in interactive output.
    Hover,
}

/// Table decoration resolved from the attributes at the table's source position.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct TablePresentation {
    frame: TableFrame,
    grid: TableGrid,
    stripes: TableStripes,
}

impl TablePresentation {
    /// Resolve local table decoration and the document defaults in effect.
    #[must_use]
    pub fn from_attributes<'value>(
        metadata: &'value BlockMetadata<'_>,
        mut lookup: impl FnMut(&str) -> Option<&'value crate::DocumentAttributeValue<'value>>,
    ) -> Self {
        Self {
            frame: resolve_table_attribute(metadata, &mut lookup, "frame", "table-frame").map_or(
                TableFrame::All,
                |value| match value {
                    "all" => TableFrame::All,
                    "ends" | "topbot" => TableFrame::Ends,
                    "sides" => TableFrame::Sides,
                    _ => TableFrame::None,
                },
            ),
            grid: resolve_table_attribute(metadata, &mut lookup, "grid", "table-grid").map_or(
                TableGrid::All,
                |value| match value {
                    "all" => TableGrid::All,
                    "rows" => TableGrid::Rows,
                    "cols" => TableGrid::Columns,
                    _ => TableGrid::None,
                },
            ),
            stripes: resolve_table_attribute(metadata, &mut lookup, "stripes", "table-stripes")
                .map_or(TableStripes::None, |value| match value {
                    "all" => TableStripes::All,
                    "odd" => TableStripes::Odd,
                    "even" => TableStripes::Even,
                    "hover" => TableStripes::Hover,
                    _ => TableStripes::None,
                }),
        }
    }

    /// The outer border applied to the table.
    #[must_use]
    pub const fn frame(self) -> TableFrame {
        self.frame
    }

    /// The rules drawn between table cells.
    #[must_use]
    pub const fn grid(self) -> TableGrid {
        self.grid
    }

    /// The body rows that receive a background fill.
    #[must_use]
    pub const fn stripes(self) -> TableStripes {
        self.stripes
    }
}

fn resolve_table_attribute<'value>(
    metadata: &'value BlockMetadata<'_>,
    lookup: &mut impl FnMut(&str) -> Option<&'value crate::DocumentAttributeValue<'value>>,
    local_name: &str,
    document_name: &str,
) -> Option<&'value str> {
    if let Some(value) = metadata.attributes.get(local_name) {
        return match value {
            AttributeValue::String(value) => Some(value),
            AttributeValue::Bool(true) => Some(""),
            AttributeValue::Bool(false) | AttributeValue::None => None,
        };
    }
    let value = lookup(document_name)?;
    if value.is_presence() {
        Some("")
    } else {
        value.text()
    }
}

/// Horizontal alignment for table cells
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum HorizontalAlignment {
    #[default]
    Left,
    Center,
    Right,
}

/// Vertical alignment for table cells
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum VerticalAlignment {
    #[default]
    Top,
    Middle,
    Bottom,
}

/// Column width specification
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ColumnWidth {
    /// Proportional width (e.g., 1, 2, 3 - relative to other columns)
    Proportional(u32),
    /// Percentage width (e.g., 15%, 30%, 55%)
    Percentage(u32),
    /// Auto-width - content determines width (~)
    Auto,
}

impl Default for ColumnWidth {
    fn default() -> Self {
        ColumnWidth::Proportional(1)
    }
}

/// Column content style
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ColumnStyle {
    /// `AsciiDoc` block content (a) - supports lists, blocks, macros
    #[serde(rename = "asciidoc")]
    AsciiDoc,
    /// Default paragraph-level markup (d)
    #[default]
    Default,
    /// Emphasis/italic (e)
    Emphasis,
    /// Header styling (h)
    Header,
    /// Literal block text (l)
    Literal,
    /// Monospace font (m)
    Monospace,
    /// Strong/bold (s)
    Strong,
}

/// Column format specification for table formatting
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[non_exhaustive]
pub struct ColumnFormat {
    #[serde(default, skip_serializing_if = "is_default_halign")]
    pub halign: HorizontalAlignment,
    #[serde(default, skip_serializing_if = "is_default_valign")]
    pub valign: VerticalAlignment,
    #[serde(default, skip_serializing_if = "is_default_width")]
    pub width: ColumnWidth,
    #[serde(default, skip_serializing_if = "is_default_style")]
    pub style: ColumnStyle,
}

impl ColumnFormat {
    /// Create a new column format with default values.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the horizontal alignment.
    #[must_use]
    pub fn with_halign(mut self, halign: HorizontalAlignment) -> Self {
        self.halign = halign;
        self
    }

    /// Set the vertical alignment.
    #[must_use]
    pub fn with_valign(mut self, valign: VerticalAlignment) -> Self {
        self.valign = valign;
        self
    }

    /// Set the column width.
    #[must_use]
    pub fn with_width(mut self, width: ColumnWidth) -> Self {
        self.width = width;
        self
    }

    /// Set the column style.
    #[must_use]
    pub fn with_style(mut self, style: ColumnStyle) -> Self {
        self.style = style;
        self
    }
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_default_halign(h: &HorizontalAlignment) -> bool {
    *h == HorizontalAlignment::default()
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_default_valign(v: &VerticalAlignment) -> bool {
    *v == VerticalAlignment::default()
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_default_width(w: &ColumnWidth) -> bool {
    *w == ColumnWidth::default()
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_default_style(s: &ColumnStyle) -> bool {
    *s == ColumnStyle::default()
}

pub(crate) fn are_all_columns_default(specs: &[ColumnFormat]) -> bool {
    specs.iter().all(|s| *s == ColumnFormat::default())
}

/// A `Table` represents a table in a document.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct Table<'a> {
    pub header: Option<TableRow<'a>>,
    pub footer: Option<TableRow<'a>>,
    pub rows: Vec<TableRow<'a>>,
    /// Column format specification for each column (alignment, width, style)
    /// Skipped if all columns have default format
    #[serde(default, skip_serializing_if = "are_all_columns_default")]
    pub columns: Vec<ColumnFormat>,
    #[serde(skip)]
    presentation: Option<TablePresentation>,
    pub location: Location,
}

impl<'a> Table<'a> {
    /// Create a new table with the given rows and location.
    #[must_use]
    pub fn new(rows: Vec<TableRow<'a>>, location: Location) -> Self {
        Self {
            header: None,
            footer: None,
            rows,
            columns: Vec::new(),
            presentation: None,
            location,
        }
    }

    /// Set the header row.
    #[must_use]
    pub fn with_header(mut self, header: Option<TableRow<'a>>) -> Self {
        self.header = header;
        self
    }

    /// Set the footer row.
    #[must_use]
    pub fn with_footer(mut self, footer: Option<TableRow<'a>>) -> Self {
        self.footer = footer;
        self
    }

    /// Set the column format specifications.
    #[must_use]
    pub fn with_columns(mut self, columns: Vec<ColumnFormat>) -> Self {
        self.columns = columns;
        self
    }

    #[must_use]
    pub(crate) fn with_presentation(mut self, presentation: TablePresentation) -> Self {
        self.presentation = Some(presentation);
        self
    }

    /// Table decoration that overrides converter defaults, if present.
    #[must_use]
    pub const fn presentation(&self) -> Option<TablePresentation> {
        self.presentation
    }
}

/// A row in a table, containing one or more columns (cells).
///
/// # Note on Field Name
///
/// The field is named `columns` (not `cells`) to align with the column-oriented
/// table model. Each `TableColumn` represents one cell in this row.
///
/// ```
/// # use acdc_parser::{TableRow, TableColumn};
/// fn count_cells(row: &TableRow) -> usize {
///     row.columns.len()  // Access cells via .columns
/// }
/// ```
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct TableRow<'a> {
    /// The cells in this row (one per table column).
    pub columns: Vec<TableColumn<'a>>,
}

impl<'a> TableRow<'a> {
    /// Create a new table row with the given columns.
    #[must_use]
    pub fn new(columns: Vec<TableColumn<'a>>) -> Self {
        Self { columns }
    }
}

/// A `TableColumn` represents a column/cell in a table row.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[non_exhaustive]
pub struct TableColumn<'a> {
    #[serde(skip)]
    pub(crate) initial_attributes: Vec<(AttributeName<'a>, DocumentAttributeAssignment<'a>)>,
    pub content: Vec<Block<'a>>,
    /// Number of columns this cell spans (default 1).
    /// Specified in `AsciiDoc` with `n+|` syntax (e.g., `2+|` for colspan=2).
    #[serde(skip_serializing_if = "is_default_span")]
    pub colspan: usize,
    /// Number of rows this cell spans (default 1).
    /// Specified in `AsciiDoc` with `.n+|` syntax (e.g., `.2+|` for rowspan=2).
    #[serde(skip_serializing_if = "is_default_span")]
    pub rowspan: usize,
    /// Cell-level horizontal alignment override.
    /// Specified with `<`, `^`, or `>` in cell specifier (e.g., `^|` for center).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub halign: Option<HorizontalAlignment>,
    /// Cell-level vertical alignment override.
    /// Specified with `.<`, `.^`, or `.>` in cell specifier (e.g., `.>|` for bottom).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub valign: Option<VerticalAlignment>,
    /// Cell-level style override.
    /// Specified with style letter after operator (e.g., `s|` for strong/bold).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub style: Option<ColumnStyle>,
}

#[allow(clippy::trivially_copy_pass_by_ref)]
const fn is_default_span(span: &usize) -> bool {
    *span == 1
}

impl<'a> TableColumn<'a> {
    /// Attribute assignments applied before this `AsciiDoc` cell's content.
    ///
    /// These initialize the nested scope; they do not change the parent document.
    pub fn initial_attributes(
        &self,
    ) -> impl Iterator<Item = (&str, &DocumentAttributeAssignment<'a>)> {
        self.initial_attributes
            .iter()
            .map(|(name, assignment)| (name.as_ref(), assignment))
    }

    /// Create a new table column with full cell specifier options.
    #[must_use]
    pub(crate) fn with_format(
        content: Vec<Block<'a>>,
        colspan: usize,
        rowspan: usize,
        halign: Option<HorizontalAlignment>,
        valign: Option<VerticalAlignment>,
        style: Option<ColumnStyle>,
    ) -> Self {
        Self {
            initial_attributes: Vec::new(),
            content,
            colspan,
            rowspan,
            halign,
            valign,
            style,
        }
    }
}