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
use crate::internal::*;

impl<'bmp, 'src> Parser<'bmp, 'src> {
  pub(crate) fn parse_section(&mut self) -> Result<Option<Section<'bmp>>> {
    let Some(mut lines) = self.read_lines() else {
      return Ok(None);
    };

    let meta = self.parse_chunk_meta(&mut lines)?;
    let Some(line) = lines.current() else {
      self.restore_peeked_meta(meta);
      return Ok(None);
    };

    let Some(level) = line.heading_level() else {
      self.restore_peeked(lines, meta);
      return Ok(None);
    };

    if meta.attrs_has_str_positional("discrete") || meta.attrs_has_str_positional("float") {
      self.restore_peeked(lines, meta);
      return Ok(None);
    }

    let last_level = self.ctx.section_level;
    self.ctx.section_level = level;
    let mut heading_line = lines.consume_current().unwrap();
    let equals = heading_line.consume_current().unwrap();
    heading_line.discard_assert(TokenKind::Whitespace);
    let id = self.section_id(heading_line.src, meta.attrs.as_ref());

    let out_of_sequence = level > last_level && level - last_level > 1;
    if out_of_sequence {
      self.err_token_full(
        format!(
          "Section title out of sequence: expected level {} `{}`",
          last_level + 1,
          "=".repeat((last_level + 2) as usize)
        ),
        &equals,
      )?;
    }

    let heading = self.parse_inlines(&mut heading_line.into_lines_in(self.bump))?;
    if !out_of_sequence {
      self.push_toc_node(level, &heading, id.as_ref());
    }

    self.restore_lines(lines);
    let mut blocks = BumpVec::new_in(self.bump);
    while let Some(inner) = self.parse_block()? {
      blocks.push(inner);
    }

    self.ctx.section_level = last_level;
    Ok(Some(Section { meta, level, id, heading, blocks }))
  }

  pub fn push_toc_node(
    &mut self,
    level: u8,
    heading: &InlineNodes<'bmp>,
    as_ref: Option<&BumpString<'bmp>>,
  ) {
    let Some(toc) = self.document.toc.as_mut() else {
      return;
    };
    if level > self.ctx.attrs.u8_or("toclevels", 2) {
      return;
    }
    let mut depth = level;
    let mut nodes: &mut BumpVec<'_, TocNode<'_>> = toc.nodes.as_mut();
    while depth > 1 {
      // we don't push out of sequence sections, shouldn't panic
      nodes = nodes.last_mut().unwrap().children.as_mut();
      depth -= 1;
    }
    nodes.push(TocNode {
      level,
      title: heading.clone(),
      id: as_ref.cloned(),
      children: BumpVec::new_in(self.bump),
    });
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use test_utils::{assert_eq, *};

  #[test]
  fn test_parse_section() {
    assert_section!(
      adoc! {"
        == foo

        bar
      "},
      Section {
        meta: ChunkMeta::empty(0),
        level: 1,
        id: Some(bstr!("_foo")),
        heading: nodes![node!("foo"; 3..6)],
        blocks: vecb![Block {
          context: BlockContext::Paragraph,
          content: BlockContent::Simple(nodes![node!("bar"; 8..11)]),
          ..empty_block!(8..11)
        }]
      }
    );
  }

  #[test]
  fn test_parse_nested_section() {
    assert_section!(
      adoc! {"
        == one

        === two

        bar
      "},
      Section {
        meta: ChunkMeta::empty(0),
        level: 1,
        id: Some(bstr!("_one")),
        heading: nodes![node!("one"; 3..6)],
        blocks: vecb![Block {
          meta: ChunkMeta::empty(8),
          context: BlockContext::Section,
          content: BlockContent::Section(Section {
            meta: ChunkMeta::empty(8),
            level: 2,
            id: Some(bstr!("_two")),
            heading: nodes![node!("two"; 12..15)],
            blocks: vecb![Block {
              context: BlockContext::Paragraph,
              content: BlockContent::Simple(nodes![node!("bar"; 17..20)]),
              ..empty_block!(17..20)
            }]
          }),
          ..empty_block!(8..21)
        }]
      }
    );
  }

  #[test]
  fn test_parse_2_sections() {
    let input = adoc! {"
      == one

      foo

      == two

      bar
    "};
    let mut parser = Parser::new(leaked_bump(), input);
    let section = parser.parse_section().unwrap().unwrap();
    assert_eq!(
      section,
      Section {
        meta: ChunkMeta::empty(0),
        level: 1,
        id: Some(bstr!("_one")),
        heading: nodes![node!("one"; 3..6)],
        blocks: vecb![Block {
          context: BlockContext::Paragraph,
          content: BlockContent::Simple(nodes![node!("foo"; 8..11)]),
          ..empty_block!(8..11)
        }]
      }
    );
    let section = parser.parse_section().unwrap().unwrap();
    assert_eq!(
      section,
      Section {
        meta: ChunkMeta::empty(13),
        level: 1,
        id: Some(bstr!("_two")),
        heading: nodes![node!("two"; 16..19)],
        blocks: vecb![Block {
          context: BlockContext::Paragraph,
          content: BlockContent::Simple(nodes![node!("bar"; 21..24)]),
          ..empty_block!(21..24)
        }]
      }
    );
  }
}