mant-core 0.6.3

Structured manual and Markdown document engine used by ManT
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
//! Parses a conservative Markdown subset into the shared document contract.
//!
//! Supported syntax becomes semantic AST nodes. Recognized extensions outside
//! the subset remain visible as exact source text with an attached diagnostic.

mod blocks;
mod container;
mod inline;
mod layout;
mod options;
mod source;

#[cfg(test)]
mod tests;

pub use container::TldrDirectiveError;

use std::{
    collections::{BTreeMap, HashMap, HashSet},
    error::Error,
    fmt,
    ops::Range,
};

use mant_ast::{
    Block, Diagnostic, DiagnosticLevel, DocumentMeta, DocumentSchema, DocumentSource, Engine,
    Inline, MantDocument, Producer, Section, SourceFormat, TldrDocument, TldrOrigin,
};
use pulldown_cmark::{Event, HeadingLevel, Options, Parser, Tag, TagEnd};

use self::{
    blocks::parse_block,
    container::split_markdown,
    inline::{inline_text, parse_inlines},
    layout::normalize_markdown_layout,
    options::{extract_entry_directives, normalize_entry_lists},
    source::MarkdownSource,
};
use crate::text_safety::mask_terminal_controls;
use crate::{
    projection::DOCUMENT_ROOT_ID,
    tldr::{TldrPageLocation, TldrParseError, parse_tldr_page},
};

type SpannedEvent<'a> = (Event<'a>, Range<usize>);

/// Complete result of parsing one ManT-flavoured Markdown input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedMarkdown {
    pub document: MantDocument,
    pub tldr: Option<TldrDocument>,
}

/// Invalid structure in `ManT`'s optional top-level Markdown extension.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MarkdownParseError {
    TldrDirective(TldrDirectiveError),
    TldrPage(TldrParseError),
}

impl fmt::Display for MarkdownParseError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TldrDirective(error) => error.fmt(formatter),
            Self::TldrPage(error) => write!(formatter, "invalid embedded tldr page: {error}"),
        }
    }
}

impl Error for MarkdownParseError {}

/// Split `ManT`'s optional leading tldr preface from the Markdown document.
///
/// Invisible HTML comments delimit the preface so `CommonMark` renderers can
/// present the enclosed tldr-pages Markdown without leaking extension syntax.
/// It must be the first non-empty construct. The remaining source is parsed
/// independently, so its first H1 remains document metadata rather than part
/// of the preface.
///
/// # Errors
///
/// Returns [`MarkdownParseError`] for an unterminated preface or malformed
/// embedded tldr page.
pub fn parse_markdown(
    source_text: &str,
    source_path: Option<String>,
) -> Result<ParsedMarkdown, MarkdownParseError> {
    let mut sanitize_diagnostics = Vec::new();
    let sanitized = sanitize_source(source_text, &mut sanitize_diagnostics);
    let source_text = sanitized.as_deref().unwrap_or(source_text);
    let parts = split_markdown(source_text).map_err(MarkdownParseError::TldrDirective)?;
    let tldr = parts
        .tldr
        .map(|source| {
            parse_tldr_page(
                source,
                TldrPageLocation {
                    platform: "embedded".to_owned(),
                    language: "und".to_owned(),
                    source_path: source_path.clone().unwrap_or_else(|| "<stdin>".to_owned()),
                },
            )
            .map(|mut page| {
                page.origin = TldrOrigin::Embedded;
                page
            })
            .map_err(MarkdownParseError::TldrPage)
        })
        .transpose()?;
    let mut entry_diagnostics = Vec::new();
    let (masked_document, declarations) =
        extract_entry_directives(parts.document.as_ref(), &mut entry_diagnostics);
    let document_source = masked_document
        .as_deref()
        .unwrap_or_else(|| parts.document.as_ref());
    let mut document = parse_document_with_entries(
        document_source,
        source_path,
        declarations,
        &mut entry_diagnostics,
    );
    if !entry_diagnostics.is_empty() {
        entry_diagnostics.extend(std::mem::take(&mut document.diagnostics));
        document.diagnostics = entry_diagnostics;
    }
    if !sanitize_diagnostics.is_empty() {
        sanitize_diagnostics.extend(std::mem::take(&mut document.diagnostics));
        document.diagnostics = sanitize_diagnostics;
    }
    Ok(ParsedMarkdown { document, tldr })
}

/// Mask a leading BOM and terminal-unsafe control characters with spaces.
///
/// A BOM would hide the tldr opening marker and demote the first heading, while
/// raw control characters would pass escape sequences through to terminals.
/// Replacements keep every byte offset valid for source coordinates.
fn sanitize_source(source_text: &str, diagnostics: &mut Vec<Diagnostic>) -> Option<String> {
    let bom = source_text.starts_with('\u{feff}');
    let rest = if bom {
        &source_text['\u{feff}'.len_utf8()..]
    } else {
        source_text
    };
    let (masked, controls) = mask_terminal_controls(rest);
    if !bom && masked.is_none() {
        return None;
    }

    let mut sanitized = String::with_capacity(source_text.len());
    if bom {
        sanitized.push_str("   ");
    }
    sanitized.push_str(masked.as_deref().unwrap_or(rest));

    if bom {
        diagnostics.push(Diagnostic {
            level: DiagnosticLevel::Warning,
            code: Some("markdown.byte-order-mark".to_owned()),
            message: "masked a leading byte-order mark".to_owned(),
            source: None,
        });
    }
    if controls > 0 {
        diagnostics.push(Diagnostic {
            level: DiagnosticLevel::Warning,
            code: Some("markdown.control-characters".to_owned()),
            message: format!("masked {controls} terminal-unsafe control character(s)"),
            source: None,
        });
    }
    Some(sanitized)
}

/// Lower the ordinary document portion after extension extraction.
#[cfg(test)]
fn parse_document(source_text: &str, source_path: Option<String>) -> MantDocument {
    let mut diagnostics = Vec::new();
    parse_document_with_entries(source_text, source_path, BTreeMap::new(), &mut diagnostics)
}

fn parse_document_with_entries(
    source_text: &str,
    source_path: Option<String>,
    mut declarations: BTreeMap<u32, options::EntryDeclaration>,
    entry_diagnostics: &mut Vec<Diagnostic>,
) -> MantDocument {
    let source = MarkdownSource::new(source_text);
    let ParsedDocumentStructure {
        mut diagnostics,
        mut root_blocks,
        flat_sections,
        mut ids,
        title,
        document_title_id,
    } = lower_document_structure(source_text, &source);
    let mut sections = nest_sections(flat_sections);
    let extracted_title = extract_document_title(
        &mut root_blocks,
        &mut sections,
        document_title_id.as_deref(),
    );
    if extracted_title {
        let replacement = if root_blocks.is_empty() {
            sections.first().map(|section| section.id.as_str())
        } else {
            Some(DOCUMENT_ROOT_ID)
        };
        ids.remap_target(document_title_id.as_deref(), replacement);
    }
    normalize_markdown_layout(&source, &mut root_blocks, &mut sections);
    normalize_entry_lists(&mut root_blocks, &mut declarations, entry_diagnostics);
    normalize_section_entries(&mut sections, &mut declarations, entry_diagnostics);
    for declaration in declarations.into_values() {
        entry_diagnostics.push(Diagnostic {
            level: DiagnosticLevel::Warning,
            code: Some("markdown.semantic-entry-list".to_owned()),
            message: "semantic-entry directive did not resolve to a Markdown bullet list"
                .to_owned(),
            source: Some(declaration.source),
        });
    }
    let retained_targets = crate::definitions::identify_definitions(
        &mut root_blocks,
        &mut sections,
        &ids.targets.keys().cloned().collect(),
    );
    for target in retained_targets {
        ids.targets.insert(target.clone(), target);
    }
    resolve_local_links(
        &mut root_blocks,
        &mut sections,
        &ids.targets,
        &mut diagnostics,
    );

    MantDocument {
        schema: DocumentSchema::V6,
        producer: markdown_producer(),
        source: DocumentSource {
            format: SourceFormat::Markdown,
            path: source_path,
        },
        meta: DocumentMeta {
            title,
            ..DocumentMeta::default()
        },
        diagnostics,
        blocks: root_blocks,
        sections,
    }
}

struct ParsedDocumentStructure {
    diagnostics: Vec<Diagnostic>,
    root_blocks: Vec<Block>,
    flat_sections: Vec<FlatSection>,
    ids: SectionIds,
    title: Option<String>,
    document_title_id: Option<String>,
}

/// Lower the Markdown event stream without imposing final document layout.
fn lower_document_structure(
    source_text: &str,
    source: &MarkdownSource<'_>,
) -> ParsedDocumentStructure {
    let parser = Parser::new_ext(source_text, markdown_options());
    let mut cursor = EventCursor::new(parser.into_offset_iter().collect());
    let mut diagnostics = Vec::new();
    let mut root_blocks = Vec::new();
    let mut flat_sections = Vec::new();
    let mut ids = SectionIds::default();
    let mut title = None;
    let mut document_title_id = None;
    let mut saw_heading = false;

    while let Some((event, range)) = cursor.peek().cloned() {
        if let Event::Start(Tag::Heading {
            level,
            id: explicit_id,
            ..
        }) = event
        {
            let _ = cursor.next();
            let (children, end) = parse_inlines(
                &mut cursor,
                source,
                &mut diagnostics,
                TagEnd::Heading(level),
            );
            let heading = inline_text(&children);
            if heading.is_empty() {
                diagnostics.push(Diagnostic {
                    level: DiagnosticLevel::Warning,
                    code: Some("markdown.empty-heading".to_owned()),
                    message: "ignored an empty Markdown heading".to_owned(),
                    source: Some(source.span(&(range.start..end))),
                });
                continue;
            }
            let is_document_title = !saw_heading && level == HeadingLevel::H1;
            saw_heading = true;
            if is_document_title {
                title = Some(heading.clone());
            }
            let id = ids.allocate(&heading, explicit_id.as_deref());
            if is_document_title {
                document_title_id = Some(id.clone());
            }
            flat_sections.push(FlatSection {
                level: heading_level(level),
                is_document_title,
                section: Section {
                    id,
                    title: heading.clone(),
                    spacing_before_lines: u16::from(!flat_sections.is_empty()),
                    blocks: Vec::new(),
                    children: Vec::new(),
                    source: Some(source.span(&(range.start..end))),
                },
            });
            continue;
        }

        let Some(block) = parse_block(&mut cursor, source, &mut diagnostics) else {
            continue;
        };
        if let Some(current) = flat_sections.last_mut() {
            current.section.blocks.push(block);
        } else {
            root_blocks.push(block);
        }
    }

    ParsedDocumentStructure {
        diagnostics,
        root_blocks,
        flat_sections,
        ids,
        title,
        document_title_id,
    }
}

fn markdown_producer() -> Producer {
    Producer {
        name: "mant".to_owned(),
        version: env!("CARGO_PKG_VERSION").to_owned(),
        engine: Some(Engine {
            name: "pulldown-cmark".to_owned(),
            version: "0.13".to_owned(),
        }),
    }
}

fn normalize_section_entries(
    sections: &mut [Section],
    declarations: &mut BTreeMap<u32, options::EntryDeclaration>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for section in sections {
        normalize_entry_lists(&mut section.blocks, declarations, diagnostics);
        normalize_section_entries(&mut section.children, declarations, diagnostics);
    }
}

fn markdown_options() -> Options {
    Options::ENABLE_TABLES
        | Options::ENABLE_FOOTNOTES
        | Options::ENABLE_STRIKETHROUGH
        | Options::ENABLE_TASKLISTS
        | Options::ENABLE_HEADING_ATTRIBUTES
        | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS
        | Options::ENABLE_PLUSES_DELIMITED_METADATA_BLOCKS
        | Options::ENABLE_MATH
        | Options::ENABLE_GFM
        | Options::ENABLE_DEFINITION_LIST
        | Options::ENABLE_SUPERSCRIPT
        | Options::ENABLE_SUBSCRIPT
        | Options::ENABLE_WIKILINKS
}

fn heading_level(level: HeadingLevel) -> u8 {
    match level {
        HeadingLevel::H1 => 1,
        HeadingLevel::H2 => 2,
        HeadingLevel::H3 => 3,
        HeadingLevel::H4 => 4,
        HeadingLevel::H5 => 5,
        HeadingLevel::H6 => 6,
    }
}

/// A leading H1 names the document; it is metadata rather than manual content.
fn extract_document_title(
    root_blocks: &mut Vec<Block>,
    sections: &mut Vec<Section>,
    document_title_id: Option<&str>,
) -> bool {
    let Some(document_title_id) = document_title_id else {
        return false;
    };
    if sections.first().map(|section| section.id.as_str()) != Some(document_title_id) {
        return false;
    }
    let title = sections.remove(0);
    root_blocks.extend(title.blocks);
    sections.splice(0..0, title.children);
    true
}

struct FlatSection {
    level: u8,
    is_document_title: bool,
    section: Section,
}

fn nest_sections(flat: Vec<FlatSection>) -> Vec<Section> {
    let mut roots = Vec::new();
    let mut stack: Vec<FlatSection> = Vec::new();

    for next in flat {
        while stack
            .last()
            .is_some_and(|current| current.is_document_title || current.level >= next.level)
        {
            attach_completed(&mut stack, &mut roots);
        }
        stack.push(next);
    }
    while !stack.is_empty() {
        attach_completed(&mut stack, &mut roots);
    }
    roots
}

fn attach_completed(stack: &mut Vec<FlatSection>, roots: &mut Vec<Section>) {
    let completed = stack.pop().expect("caller checks non-empty stack").section;
    if let Some(parent) = stack.last_mut() {
        parent.section.children.push(completed);
    } else {
        roots.push(completed);
    }
}

#[derive(Default)]
struct SectionIds {
    counts: HashMap<String, usize>,
    assigned: HashSet<String>,
    targets: HashMap<String, String>,
}

impl SectionIds {
    fn allocate(&mut self, title: &str, explicit: Option<&str>) -> String {
        let explicit = explicit
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .map(ToOwned::to_owned);
        let base = explicit.clone().unwrap_or_else(|| slug(title));
        let base = if base.is_empty() {
            "section".to_owned()
        } else if crate::projection::is_reserved_selector(&base) {
            // Reserved selectors and bare tree paths would shadow this
            // heading in excerpt selection; keep it addressable instead.
            format!("{base}-section")
        } else {
            base
        };
        // Disambiguate on the final id, not the per-base count: `# Foo 2`
        // slugs to base `foo-2`, which collides with the `foo-2` a second
        // `# Foo` produces. Counting per base alone would hand both the same
        // id, silently misattributing search ownership between them.
        let count = self.counts.entry(base.clone()).or_default();
        let id = loop {
            *count += 1;
            let candidate = if *count == 1 {
                base.clone()
            } else {
                format!("{base}-{}", *count)
            };
            if self.assigned.insert(candidate.clone()) {
                break candidate;
            }
        };
        // Ambiguous human-facing keys resolve to the first section that
        // claimed them, matching the bare slug this heading renders as its
        // anchor. A later duplicate owns only its own disambiguated id.
        self.targets
            .entry(base.clone())
            .or_insert_with(|| id.clone());
        // Heading attributes are source-level link aliases. Preserve the
        // original alias even when its final section ID had to move out of the
        // selector namespace (`{#root}`, `{#2.1}`, or `{#2.1/o3}`).
        if let Some(explicit) = explicit {
            self.targets.entry(explicit).or_insert_with(|| id.clone());
        }
        self.targets
            .entry(slug(title))
            .or_insert_with(|| id.clone());
        self.targets.insert(id.clone(), id.clone());
        id
    }

    fn remap_target(&mut self, current: Option<&str>, replacement: Option<&str>) {
        let Some(current) = current else {
            return;
        };
        if let Some(replacement) = replacement {
            for target in self.targets.values_mut() {
                if target == current {
                    replacement.clone_into(target);
                }
            }
        } else {
            self.targets.retain(|_, target| target != current);
        }
    }
}

fn slug(value: &str) -> String {
    let mut output = String::new();
    let mut separator = false;
    for character in value.chars().flat_map(char::to_lowercase) {
        if character.is_alphanumeric() || character == '_' {
            if separator && !output.is_empty() {
                output.push('-');
            }
            separator = false;
            output.push(character);
        } else {
            separator = true;
        }
    }
    output.trim_matches('-').to_owned()
}

fn resolve_local_links(
    root_blocks: &mut [Block],
    sections: &mut [Section],
    targets: &HashMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    resolve_blocks(root_blocks, targets, diagnostics);
    for section in sections {
        resolve_blocks(&mut section.blocks, targets, diagnostics);
        resolve_local_links(&mut [], &mut section.children, targets, diagnostics);
    }
}

fn resolve_blocks(
    blocks: &mut [Block],
    targets: &HashMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for block in blocks {
        match block {
            Block::Paragraph { children, .. } | Block::Preformatted { children, .. } => {
                resolve_inlines(children, targets, diagnostics);
            }
            Block::List { items, .. } => {
                for item in items {
                    resolve_blocks(&mut item.blocks, targets, diagnostics);
                }
            }
            Block::DefinitionList { items, .. } => {
                for item in items {
                    for term in &mut item.terms {
                        resolve_inlines(term, targets, diagnostics);
                    }
                    resolve_blocks(&mut item.description, targets, diagnostics);
                }
            }
            Block::Table { rows, .. } => {
                for row in rows {
                    for cell in &mut row.cells {
                        resolve_blocks(&mut cell.blocks, targets, diagnostics);
                    }
                }
            }
            Block::Equation { .. }
            | Block::VerticalSpace { .. }
            | Block::ThematicBreak { .. }
            | Block::Unsupported { .. } => {}
        }
    }
}

fn resolve_inlines(
    inlines: &mut [Inline],
    targets: &HashMap<String, String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    for inline in inlines {
        match inline {
            Inline::SectionReference { target, children } => {
                let lookup = target.trim().trim_start_matches('#');
                if let Some(id) = targets.get(lookup).or_else(|| targets.get(&slug(lookup))) {
                    *target = id.clone();
                } else {
                    diagnostics.push(Diagnostic {
                        level: DiagnosticLevel::Warning,
                        code: Some("markdown.unresolved-reference".to_owned()),
                        message: format!("unresolved Markdown document link '#{lookup}'"),
                        source: None,
                    });
                }
                resolve_inlines(children, targets, diagnostics);
            }
            Inline::Strong { children }
            | Inline::Emphasis { children }
            | Inline::ExternalLink { children, .. }
            | Inline::EmailLink { children, .. }
            | Inline::ManualReference { children, .. } => {
                resolve_inlines(children, targets, diagnostics);
            }
            Inline::Text { .. }
            | Inline::Code { .. }
            | Inline::Anchor { .. }
            | Inline::LineBreak => {}
        }
    }
}

pub(super) struct EventCursor<'a> {
    events: Vec<SpannedEvent<'a>>,
    position: usize,
    depth: usize,
}

/// Recursion budget shared by nested block containers and inline spans.
///
/// Parsing recurses once per nesting level, so unbounded input depth would
/// overflow the stack before any allocation limit applies. Subtrees beyond
/// this depth are preserved as unsupported source text with a diagnostic.
const MAX_NESTING_DEPTH: usize = 64;

impl<'a> EventCursor<'a> {
    fn new(events: Vec<SpannedEvent<'a>>) -> Self {
        Self {
            events,
            position: 0,
            depth: 0,
        }
    }

    /// Reserve one nesting level; callers must pair with [`Self::ascend`].
    pub(super) fn try_descend(&mut self) -> bool {
        if self.depth >= MAX_NESTING_DEPTH {
            return false;
        }
        self.depth += 1;
        true
    }

    pub(super) fn ascend(&mut self) {
        self.depth = self.depth.saturating_sub(1);
    }

    pub(super) fn peek(&self) -> Option<&SpannedEvent<'a>> {
        self.events.get(self.position)
    }

    pub(super) fn next(&mut self) -> Option<SpannedEvent<'a>> {
        let event = self.events.get(self.position)?.clone();
        self.position += 1;
        Some(event)
    }

    /// Consume the remainder of a just-opened tag, including nested tags.
    pub(super) fn consume_balanced(&mut self, start: Range<usize>) -> Range<usize> {
        let mut depth = 1usize;
        let mut end = start.end;
        while let Some((event, range)) = self.next() {
            end = range.end;
            match event {
                Event::Start(_) => depth = depth.saturating_add(1),
                Event::End(_) => {
                    depth = depth.saturating_sub(1);
                    if depth == 0 {
                        break;
                    }
                }
                _ => {}
            }
        }
        start.start..end
    }

    pub(super) fn subtree_contains_task_marker(&self) -> bool {
        let mut depth = 1usize;
        for (event, _) in &self.events[self.position..] {
            match event {
                Event::TaskListMarker(_) => return true,
                Event::Start(_) => depth = depth.saturating_add(1),
                Event::End(_) => {
                    depth = depth.saturating_sub(1);
                    if depth == 0 {
                        return false;
                    }
                }
                _ => {}
            }
        }
        false
    }
}