adoctra-core 0.0.1

Core parser and document model for the adoctra AsciiDoc toolchain
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
//! Section kinds and numbering, like Ruby's `Parser.initialize_section`
//! (`sectname`, special sections and whether a section is numbered, decided
//! with the attributes while reading its title),
//! `AbstractBlock#assign_numeral` (numerals among numbered siblings, applied
//! when the hierarchy is built) and `Section#sectnum`. The displayed prefix is
//! produced during conversion with the attributes at the section (see
//! body_subs.rs), as the HTML converter's `convert_section` does.

use crate::Attributes;

/// What reading decided about a section title.
#[derive(Clone, Debug)]
pub(crate) struct Section {
    /// Ruby's `sectname`: `section`, `chapter` or `part` in a book, or the
    /// style of a special section.
    pub sectname: String,
    pub numbered: Numbered,
    pub book: bool,
    /// The section's level: a special section at level 0 and a book's
    /// abstract become level 1.
    pub level: u8,
    /// The level of the title line, which decides where the section nests.
    pub raw_level: u8,
    /// A special section (appendix, preface, glossary, …) or one nested in
    /// it (Ruby inherits `special` from the parent section).
    pub special: bool,
    /// A chapter's `chapter-number` or an appendix's `appendix-number`
    /// counter value, taken when reading closes it.
    pub numeral: Option<String>,
    /// An appendix caption (`Appendix A: `, or `A. ` without
    /// `appendix-caption`), fixed when reading closes it.
    pub caption: Option<Vec<crate::AttributePart>>,
    /// `Section#sectnum` components: the numerals from the outermost section
    /// the number continues through (an unnumbered one contributes an empty
    /// numeral, like Ruby's `nil`). Assigned when the hierarchy is built.
    pub path: Vec<String>,
    /// Where reading closed each section of `path`: Ruby assigns numerals
    /// only then, so a label produced while reading inside it sees none.
    pub closes: Vec<usize>,
    /// Where reading closed this section (`usize::MAX` at the end).
    pub closed_at: usize,
    /// The diagnostic stream when reading reached the title line: Ruby
    /// reports the section's level errors there.
    pub diagnostics_before: crate::context::Stamp,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Numbered {
    No,
    Yes,
    /// A special section numbered as a chapter (`sectnums=all` in a book).
    Chapter,
}

impl Section {
    /// Ruby's `initialize_section` for a title line at `raw_level` with block
    /// `style`, nested in `parent` (`None` for the document). `synopsis`
    /// marks a manual page's SYNOPSIS title, special without a style.
    pub fn read(
        style: Option<&str>,
        raw_level: u8,
        book: bool,
        synopsis: bool,
        attributes: &Attributes,
        parent: Option<&Section>,
    ) -> Self {
        let sectnums = attributes.get("sectnums");
        let mut level = raw_level;
        let (sectname, special) = match style {
            Some("abstract") if book => {
                level = 1;
                ("chapter".to_owned(), false)
            }
            Some(style) if is_level_style(style) => ("section".to_owned(), false),
            Some(style) => (style.to_owned(), true),
            None if book => (
                match level {
                    0 => "part",
                    1 => "chapter",
                    _ => "section",
                }
                .to_owned(),
                false,
            ),
            // A manual page's unstyled SYNOPSIS section.
            None if synopsis => ("synopsis".to_owned(), true),
            None => ("section".to_owned(), false),
        };
        if special && style.is_some() {
            level = level.max(1);
        }
        let inherited = parent.is_some_and(|parent| parent.special);
        let numbered = if special {
            match sectnums {
                _ if sectname == "appendix" => Numbered::Yes,
                Some("all") if book && level == 1 => Numbered::Chapter,
                Some("all") => Numbered::Yes,
                _ => Numbered::No,
            }
        } else if sectnums.is_some() && level > 0 {
            // A section nested in a special one is numbered with its parent.
            match parent {
                Some(parent) if inherited && !parent.is_numbered() => Numbered::No,
                _ => Numbered::Yes,
            }
        } else if book && level == 0 && attributes.get("partnums").is_some() {
            Numbered::Yes
        } else {
            Numbered::No
        };
        Self {
            sectname,
            numbered,
            book,
            level,
            raw_level,
            special: special || inherited,
            numeral: None,
            caption: None,
            path: Vec::new(),
            closes: Vec::new(),
            closed_at: usize::MAX,
            diagnostics_before: Default::default(),
        }
    }

    /// The section as a label produced while reading at `position` sees it:
    /// numerals of sections not closed yet are empty.
    pub fn at(&self, position: usize) -> Self {
        let mut section = self.clone();
        for (numeral, closed) in section.path.iter_mut().zip(&self.closes) {
            if *closed > position {
                numeral.clear();
            }
        }
        section
    }

    /// Whether closing this section advances the `appendix-number` counter.
    pub fn counts_appendix(&self) -> bool {
        self.is_numbered() && self.sectname == "appendix"
    }

    /// Ruby's `next_section` lets only appendices, prefaces and abstracts
    /// among level-1 special sections contain sections.
    pub fn allows_nesting(&self) -> bool {
        !(self.level == 1
            && self.special
            && !matches!(self.sectname.as_str(), "appendix" | "preface" | "abstract"))
    }

    /// Whether closing this section advances the `chapter-number` counter.
    pub fn counts_chapter(&self) -> bool {
        !self.counts_appendix()
            && (self.numbered == Numbered::Chapter
                || (self.numbered == Numbered::Yes && self.sectname == "chapter"))
    }

    pub fn is_numbered(&self) -> bool {
        self.numbered != Numbered::No
    }

    /// Ruby's `sectnum(delimiter, append)`.
    pub fn sectnum(&self, delimiter: &str, append: &str) -> String {
        format!("{}{append}", self.path.join(delimiter))
    }

    /// Chapters and appendices are emphasized in cross-reference labels.
    pub fn emphasized(&self) -> bool {
        matches!(self.sectname.as_str(), "chapter" | "appendix")
    }

    /// The title prefix `convert_section` renders (with its trailing space),
    /// using the attributes at the section; `None` beyond `sectnumlevels`.
    pub fn caption(&self, attributes: &Attributes) -> Option<Vec<crate::AttributePart>> {
        if self.caption.is_some() {
            return self.caption.clone();
        }
        if !self.is_numbered() {
            return None;
        }
        let levels = attributes
            .get("sectnumlevels")
            .map_or(3, crate::include_selection::integer_prefix);
        if i128::from(self.level) > levels {
            return None;
        }
        // Ruby inserts the signifier's stored value.
        let signified = |name: &str, number: String| {
            let mut parts = attributes.value_parts(name).unwrap_or_default();
            if !parts.is_empty() {
                crate::attributes::push_part(&mut parts, " ", false);
            }
            crate::attributes::push_part(&mut parts, &format!("{number} "), false);
            parts
        };
        Some(match self.sectname.as_str() {
            "chapter" if self.level < 2 && self.book => {
                signified("chapter-signifier", self.sectnum(".", "."))
            }
            "part" if self.level < 2 && self.book => {
                signified("part-signifier", self.sectnum("", ":"))
            }
            _ => vec![crate::AttributePart::Text(format!(
                "{} ",
                self.sectnum(".", ".")
            ))],
        })
    }
}

/// Ruby's `SectionLevelStyleRx` (`sect` and one digit).
fn is_level_style(style: &str) -> bool {
    style
        .strip_prefix("sect")
        .is_some_and(|rest| rest.len() == 1 && rest.as_bytes()[0].is_ascii_digit())
}

/// Numerals of numbered sections within one parent (Ruby's
/// `@next_section_ordinal`).
#[derive(Default)]
pub(crate) struct Ordinals {
    next: u32,
}

impl Ordinals {
    /// Ruby's `assign_numeral`: chapters and appendices take their counter
    /// value, parts a Roman ordinal, other sections the next ordinal among
    /// their numbered siblings. `None` for an unnumbered section.
    pub fn assign(&mut self, section: &Section) -> Option<String> {
        if !section.is_numbered() {
            return None;
        }
        if section.counts_chapter() || section.counts_appendix() {
            return section.numeral.clone();
        }
        self.next += 1;
        Some(if section.sectname == "part" {
            roman(self.next)
        } else {
            self.next.to_string()
        })
    }
}

/// Ruby's `Helpers.int_to_roman`.
fn roman(mut value: u32) -> String {
    const NUMERALS: [(&str, u32); 13] = [
        ("M", 1000),
        ("CM", 900),
        ("D", 500),
        ("CD", 400),
        ("C", 100),
        ("XC", 90),
        ("L", 50),
        ("XL", 40),
        ("X", 10),
        ("IX", 9),
        ("V", 5),
        ("IV", 4),
        ("I", 1),
    ];
    let mut result = String::new();
    for (letters, amount) in NUMERALS {
        while value >= amount {
            result.push_str(letters);
            value -= amount;
        }
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;

    fn attributes(pairs: &[(&str, &str)]) -> Attributes {
        let mut attributes = Attributes::new();
        for (key, value) in pairs {
            attributes.set(*key, *value);
        }
        attributes
    }

    #[test]
    fn roman_numerals_match_ruby() {
        let values: Vec<_> = [1, 4, 9, 14, 40, 90, 400, 1994].map(roman).into();
        assert_eq!(
            values,
            ["I", "IV", "IX", "XIV", "XL", "XC", "CD", "MCMXCIV"]
        );
    }

    #[test]
    fn reading_decides_names_and_numbering() {
        let on = attributes(&[("sectnums", "")]);
        let all = attributes(&[("sectnums", "all"), ("partnums", "")]);
        let read = |style, level, book, attrs: &Attributes| {
            let section = Section::read(style, level, book, false, attrs, None);
            (section.sectname, section.numbered)
        };
        assert_eq!(read(None, 1, false, &on), ("section".into(), Numbered::Yes));
        assert_eq!(read(None, 0, false, &on), ("section".into(), Numbered::No));
        assert_eq!(read(None, 1, true, &on), ("chapter".into(), Numbered::Yes));
        assert_eq!(read(None, 0, true, &on), ("part".into(), Numbered::No));
        assert_eq!(read(None, 0, true, &all), ("part".into(), Numbered::Yes));
        assert_eq!(
            read(Some("sect1"), 1, true, &on),
            ("section".into(), Numbered::Yes)
        );
        assert_eq!(
            read(Some("abstract"), 1, true, &on),
            ("chapter".into(), Numbered::Yes)
        );
        assert_eq!(
            read(Some("preface"), 1, false, &on),
            ("preface".into(), Numbered::No)
        );
        assert_eq!(
            read(Some("preface"), 1, true, &all),
            ("preface".into(), Numbered::Chapter)
        );
        assert_eq!(
            read(Some("glossary"), 2, true, &all),
            ("glossary".into(), Numbered::Yes)
        );
        assert_eq!(
            read(None, 1, false, &Attributes::new()),
            ("section".into(), Numbered::No)
        );
    }

    #[test]
    fn special_sections_adjust_levels_and_pass_specialness_to_children() {
        let on = attributes(&[("sectnums", "")]);
        let appendix = Section::read(Some("appendix"), 0, false, false, &Attributes::new(), None);
        assert_eq!((appendix.level, appendix.raw_level), (1, 0));
        assert!(appendix.special && appendix.counts_appendix());
        assert!(!appendix.counts_chapter());
        let abstract_ = Section::read(Some("abstract"), 3, true, false, &on, None);
        assert_eq!(
            (abstract_.level, abstract_.sectname.as_str()),
            (1, "chapter")
        );
        assert!(!abstract_.special && abstract_.counts_chapter());
        // A child of a special section is special; it is numbered only when
        // its parent is.
        let child = Section::read(None, 2, false, false, &on, Some(&appendix));
        assert!(child.special && child.is_numbered());
        let preface = Section::read(Some("preface"), 1, true, false, &on, None);
        let child = Section::read(None, 2, true, false, &on, Some(&preface));
        assert!(child.special && !child.is_numbered());
        // Only appendices, prefaces and abstracts contain sections.
        assert!(preface.allows_nesting() && appendix.allows_nesting());
        assert!(!Section::read(Some("glossary"), 1, false, false, &on, None).allows_nesting());
        assert!(Section::read(Some("glossary"), 2, false, false, &on, None).allows_nesting());
    }

    #[test]
    fn labels_while_reading_see_only_closed_sections() {
        let mut section = Section::read(
            None,
            2,
            false,
            false,
            &attributes(&[("sectnums", "")]),
            None,
        );
        section.path = vec!["1".into(), "2".into()];
        section.closes = vec![50, 20];
        assert_eq!(section.at(30).sectnum(".", ""), ".2");
        assert_eq!(section.at(10).sectnum(".", ""), ".");
        assert_eq!(section.at(50).sectnum(".", ""), "1.2");
    }

    fn text(parts: Option<Vec<crate::AttributePart>>) -> Option<String> {
        parts.as_deref().map(crate::attributes::parts_text)
    }

    #[test]
    fn captions_follow_levels_and_signifiers() {
        let mut section = Section::read(
            None,
            2,
            false,
            false,
            &attributes(&[("sectnums", "")]),
            None,
        );
        section.path = vec!["1".into(), "2".into()];
        assert_eq!(
            text(section.caption(&Attributes::new())),
            Some("1.2. ".into())
        );
        let one = attributes(&[("sectnumlevels", "1")]);
        assert_eq!(section.caption(&one), None);
        assert_eq!(section.sectnum(".", ","), "1.2,");
        let mut chapter =
            Section::read(None, 1, true, false, &attributes(&[("sectnums", "")]), None);
        chapter.path = vec!["3".into()];
        let signifier = attributes(&[("chapter-signifier", "Chapter")]);
        assert_eq!(
            text(chapter.caption(&signifier)),
            Some("Chapter 3. ".into())
        );
        let mut part = Section::read(None, 0, true, false, &attributes(&[("partnums", "")]), None);
        part.path = vec!["II".into()];
        assert_eq!(text(part.caption(&Attributes::new())), Some("II: ".into()));
        // An appendix caption is fixed at closing, beyond sectnumlevels.
        let mut appendix =
            Section::read(Some("appendix"), 1, false, false, &Attributes::new(), None);
        appendix.caption = Some(vec![crate::AttributePart::Text("Приложение A: ".into())]);
        let none = attributes(&[("sectnumlevels", "0")]);
        assert_eq!(text(appendix.caption(&none)), Some("Приложение A: ".into()));
    }
}