Skip to main content

mant_core/markdown/
mod.rs

1//! Parses a conservative Markdown subset into the shared document contract.
2//!
3//! Supported syntax becomes semantic AST nodes. Recognized extensions outside
4//! the subset remain visible as exact source text with an attached diagnostic.
5
6mod blocks;
7mod container;
8mod inline;
9mod layout;
10mod options;
11mod source;
12
13#[cfg(test)]
14mod tests;
15
16pub use container::TldrDirectiveError;
17
18use std::{
19    collections::{BTreeMap, HashMap, HashSet},
20    error::Error,
21    fmt,
22    ops::Range,
23};
24
25use mant_ast::{
26    Block, Diagnostic, DiagnosticLevel, DocumentMeta, DocumentSchema, DocumentSource, Engine,
27    Inline, MantDocument, Producer, Section, SourceFormat, TldrDocument, TldrOrigin,
28};
29use pulldown_cmark::{Event, HeadingLevel, Options, Parser, Tag, TagEnd};
30
31use self::{
32    blocks::parse_block,
33    container::split_markdown,
34    inline::{inline_text, parse_inlines},
35    layout::normalize_markdown_layout,
36    options::{extract_entry_directives, normalize_entry_lists},
37    source::MarkdownSource,
38};
39use crate::text_safety::mask_terminal_controls;
40use crate::{
41    projection::DOCUMENT_ROOT_ID,
42    tldr::{TldrPageLocation, TldrParseError, parse_tldr_page},
43};
44
45type SpannedEvent<'a> = (Event<'a>, Range<usize>);
46
47/// Complete result of parsing one ManT-flavoured Markdown input.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct ParsedMarkdown {
50    pub document: MantDocument,
51    pub tldr: Option<TldrDocument>,
52}
53
54/// Invalid structure in `ManT`'s optional top-level Markdown extension.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum MarkdownParseError {
57    TldrDirective(TldrDirectiveError),
58    TldrPage(TldrParseError),
59}
60
61impl fmt::Display for MarkdownParseError {
62    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
63        match self {
64            Self::TldrDirective(error) => error.fmt(formatter),
65            Self::TldrPage(error) => write!(formatter, "invalid embedded tldr page: {error}"),
66        }
67    }
68}
69
70impl Error for MarkdownParseError {}
71
72/// Split `ManT`'s optional leading tldr preface from the Markdown document.
73///
74/// Invisible HTML comments delimit the preface so `CommonMark` renderers can
75/// present the enclosed tldr-pages Markdown without leaking extension syntax.
76/// It must be the first non-empty construct. The remaining source is parsed
77/// independently, so its first H1 remains document metadata rather than part
78/// of the preface.
79///
80/// # Errors
81///
82/// Returns [`MarkdownParseError`] for an unterminated preface or malformed
83/// embedded tldr page.
84pub fn parse_markdown(
85    source_text: &str,
86    source_path: Option<String>,
87) -> Result<ParsedMarkdown, MarkdownParseError> {
88    let mut sanitize_diagnostics = Vec::new();
89    let sanitized = sanitize_source(source_text, &mut sanitize_diagnostics);
90    let source_text = sanitized.as_deref().unwrap_or(source_text);
91    let parts = split_markdown(source_text).map_err(MarkdownParseError::TldrDirective)?;
92    let tldr = parts
93        .tldr
94        .map(|source| {
95            parse_tldr_page(
96                source,
97                TldrPageLocation {
98                    platform: "embedded".to_owned(),
99                    language: "und".to_owned(),
100                    source_path: source_path.clone().unwrap_or_else(|| "<stdin>".to_owned()),
101                },
102            )
103            .map(|mut page| {
104                page.origin = TldrOrigin::Embedded;
105                page
106            })
107            .map_err(MarkdownParseError::TldrPage)
108        })
109        .transpose()?;
110    let mut entry_diagnostics = Vec::new();
111    let (masked_document, declarations) =
112        extract_entry_directives(parts.document.as_ref(), &mut entry_diagnostics);
113    let document_source = masked_document
114        .as_deref()
115        .unwrap_or_else(|| parts.document.as_ref());
116    let mut document = parse_document_with_entries(
117        document_source,
118        source_path,
119        declarations,
120        &mut entry_diagnostics,
121    );
122    if !entry_diagnostics.is_empty() {
123        entry_diagnostics.extend(std::mem::take(&mut document.diagnostics));
124        document.diagnostics = entry_diagnostics;
125    }
126    if !sanitize_diagnostics.is_empty() {
127        sanitize_diagnostics.extend(std::mem::take(&mut document.diagnostics));
128        document.diagnostics = sanitize_diagnostics;
129    }
130    Ok(ParsedMarkdown { document, tldr })
131}
132
133/// Mask a leading BOM and terminal-unsafe control characters with spaces.
134///
135/// A BOM would hide the tldr opening marker and demote the first heading, while
136/// raw control characters would pass escape sequences through to terminals.
137/// Replacements keep every byte offset valid for source coordinates.
138fn sanitize_source(source_text: &str, diagnostics: &mut Vec<Diagnostic>) -> Option<String> {
139    let bom = source_text.starts_with('\u{feff}');
140    let rest = if bom {
141        &source_text['\u{feff}'.len_utf8()..]
142    } else {
143        source_text
144    };
145    let (masked, controls) = mask_terminal_controls(rest);
146    if !bom && masked.is_none() {
147        return None;
148    }
149
150    let mut sanitized = String::with_capacity(source_text.len());
151    if bom {
152        sanitized.push_str("   ");
153    }
154    sanitized.push_str(masked.as_deref().unwrap_or(rest));
155
156    if bom {
157        diagnostics.push(Diagnostic {
158            level: DiagnosticLevel::Warning,
159            code: Some("markdown.byte-order-mark".to_owned()),
160            message: "masked a leading byte-order mark".to_owned(),
161            source: None,
162        });
163    }
164    if controls > 0 {
165        diagnostics.push(Diagnostic {
166            level: DiagnosticLevel::Warning,
167            code: Some("markdown.control-characters".to_owned()),
168            message: format!("masked {controls} terminal-unsafe control character(s)"),
169            source: None,
170        });
171    }
172    Some(sanitized)
173}
174
175/// Lower the ordinary document portion after extension extraction.
176#[cfg(test)]
177fn parse_document(source_text: &str, source_path: Option<String>) -> MantDocument {
178    let mut diagnostics = Vec::new();
179    parse_document_with_entries(source_text, source_path, BTreeMap::new(), &mut diagnostics)
180}
181
182fn parse_document_with_entries(
183    source_text: &str,
184    source_path: Option<String>,
185    mut declarations: BTreeMap<u32, options::EntryDeclaration>,
186    entry_diagnostics: &mut Vec<Diagnostic>,
187) -> MantDocument {
188    let source = MarkdownSource::new(source_text);
189    let ParsedDocumentStructure {
190        mut diagnostics,
191        mut root_blocks,
192        flat_sections,
193        mut ids,
194        title,
195        document_title_id,
196    } = lower_document_structure(source_text, &source);
197    let mut sections = nest_sections(flat_sections);
198    let extracted_title = extract_document_title(
199        &mut root_blocks,
200        &mut sections,
201        document_title_id.as_deref(),
202    );
203    if extracted_title {
204        let replacement = if root_blocks.is_empty() {
205            sections.first().map(|section| section.id.as_str())
206        } else {
207            Some(DOCUMENT_ROOT_ID)
208        };
209        ids.remap_target(document_title_id.as_deref(), replacement);
210    }
211    normalize_markdown_layout(&source, &mut root_blocks, &mut sections);
212    normalize_entry_lists(&mut root_blocks, &mut declarations, entry_diagnostics);
213    normalize_section_entries(&mut sections, &mut declarations, entry_diagnostics);
214    for declaration in declarations.into_values() {
215        entry_diagnostics.push(Diagnostic {
216            level: DiagnosticLevel::Warning,
217            code: Some("markdown.semantic-entry-list".to_owned()),
218            message: "semantic-entry directive did not resolve to a Markdown bullet list"
219                .to_owned(),
220            source: Some(declaration.source),
221        });
222    }
223    let retained_targets = crate::definitions::identify_definitions(
224        &mut root_blocks,
225        &mut sections,
226        &ids.targets.keys().cloned().collect(),
227    );
228    for target in retained_targets {
229        ids.targets.insert(target.clone(), target);
230    }
231    resolve_local_links(
232        &mut root_blocks,
233        &mut sections,
234        &ids.targets,
235        &mut diagnostics,
236    );
237
238    MantDocument {
239        schema: DocumentSchema::V6,
240        producer: markdown_producer(),
241        source: DocumentSource {
242            format: SourceFormat::Markdown,
243            path: source_path,
244        },
245        meta: DocumentMeta {
246            title,
247            ..DocumentMeta::default()
248        },
249        diagnostics,
250        blocks: root_blocks,
251        sections,
252    }
253}
254
255struct ParsedDocumentStructure {
256    diagnostics: Vec<Diagnostic>,
257    root_blocks: Vec<Block>,
258    flat_sections: Vec<FlatSection>,
259    ids: SectionIds,
260    title: Option<String>,
261    document_title_id: Option<String>,
262}
263
264/// Lower the Markdown event stream without imposing final document layout.
265fn lower_document_structure(
266    source_text: &str,
267    source: &MarkdownSource<'_>,
268) -> ParsedDocumentStructure {
269    let parser = Parser::new_ext(source_text, markdown_options());
270    let mut cursor = EventCursor::new(parser.into_offset_iter().collect());
271    let mut diagnostics = Vec::new();
272    let mut root_blocks = Vec::new();
273    let mut flat_sections = Vec::new();
274    let mut ids = SectionIds::default();
275    let mut title = None;
276    let mut document_title_id = None;
277    let mut saw_heading = false;
278
279    while let Some((event, range)) = cursor.peek().cloned() {
280        if let Event::Start(Tag::Heading {
281            level,
282            id: explicit_id,
283            ..
284        }) = event
285        {
286            let _ = cursor.next();
287            let (children, end) = parse_inlines(
288                &mut cursor,
289                source,
290                &mut diagnostics,
291                TagEnd::Heading(level),
292            );
293            let heading = inline_text(&children);
294            if heading.is_empty() {
295                diagnostics.push(Diagnostic {
296                    level: DiagnosticLevel::Warning,
297                    code: Some("markdown.empty-heading".to_owned()),
298                    message: "ignored an empty Markdown heading".to_owned(),
299                    source: Some(source.span(&(range.start..end))),
300                });
301                continue;
302            }
303            let is_document_title = !saw_heading && level == HeadingLevel::H1;
304            saw_heading = true;
305            if is_document_title {
306                title = Some(heading.clone());
307            }
308            let id = ids.allocate(&heading, explicit_id.as_deref());
309            if is_document_title {
310                document_title_id = Some(id.clone());
311            }
312            flat_sections.push(FlatSection {
313                level: heading_level(level),
314                is_document_title,
315                section: Section {
316                    id,
317                    title: heading.clone(),
318                    spacing_before_lines: u16::from(!flat_sections.is_empty()),
319                    blocks: Vec::new(),
320                    children: Vec::new(),
321                    source: Some(source.span(&(range.start..end))),
322                },
323            });
324            continue;
325        }
326
327        let Some(block) = parse_block(&mut cursor, source, &mut diagnostics) else {
328            continue;
329        };
330        if let Some(current) = flat_sections.last_mut() {
331            current.section.blocks.push(block);
332        } else {
333            root_blocks.push(block);
334        }
335    }
336
337    ParsedDocumentStructure {
338        diagnostics,
339        root_blocks,
340        flat_sections,
341        ids,
342        title,
343        document_title_id,
344    }
345}
346
347fn markdown_producer() -> Producer {
348    Producer {
349        name: "mant".to_owned(),
350        version: env!("CARGO_PKG_VERSION").to_owned(),
351        engine: Some(Engine {
352            name: "pulldown-cmark".to_owned(),
353            version: "0.13".to_owned(),
354        }),
355    }
356}
357
358fn normalize_section_entries(
359    sections: &mut [Section],
360    declarations: &mut BTreeMap<u32, options::EntryDeclaration>,
361    diagnostics: &mut Vec<Diagnostic>,
362) {
363    for section in sections {
364        normalize_entry_lists(&mut section.blocks, declarations, diagnostics);
365        normalize_section_entries(&mut section.children, declarations, diagnostics);
366    }
367}
368
369fn markdown_options() -> Options {
370    Options::ENABLE_TABLES
371        | Options::ENABLE_FOOTNOTES
372        | Options::ENABLE_STRIKETHROUGH
373        | Options::ENABLE_TASKLISTS
374        | Options::ENABLE_HEADING_ATTRIBUTES
375        | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS
376        | Options::ENABLE_PLUSES_DELIMITED_METADATA_BLOCKS
377        | Options::ENABLE_MATH
378        | Options::ENABLE_GFM
379        | Options::ENABLE_DEFINITION_LIST
380        | Options::ENABLE_SUPERSCRIPT
381        | Options::ENABLE_SUBSCRIPT
382        | Options::ENABLE_WIKILINKS
383}
384
385fn heading_level(level: HeadingLevel) -> u8 {
386    match level {
387        HeadingLevel::H1 => 1,
388        HeadingLevel::H2 => 2,
389        HeadingLevel::H3 => 3,
390        HeadingLevel::H4 => 4,
391        HeadingLevel::H5 => 5,
392        HeadingLevel::H6 => 6,
393    }
394}
395
396/// A leading H1 names the document; it is metadata rather than manual content.
397fn extract_document_title(
398    root_blocks: &mut Vec<Block>,
399    sections: &mut Vec<Section>,
400    document_title_id: Option<&str>,
401) -> bool {
402    let Some(document_title_id) = document_title_id else {
403        return false;
404    };
405    if sections.first().map(|section| section.id.as_str()) != Some(document_title_id) {
406        return false;
407    }
408    let title = sections.remove(0);
409    root_blocks.extend(title.blocks);
410    sections.splice(0..0, title.children);
411    true
412}
413
414struct FlatSection {
415    level: u8,
416    is_document_title: bool,
417    section: Section,
418}
419
420fn nest_sections(flat: Vec<FlatSection>) -> Vec<Section> {
421    let mut roots = Vec::new();
422    let mut stack: Vec<FlatSection> = Vec::new();
423
424    for next in flat {
425        while stack
426            .last()
427            .is_some_and(|current| current.is_document_title || current.level >= next.level)
428        {
429            attach_completed(&mut stack, &mut roots);
430        }
431        stack.push(next);
432    }
433    while !stack.is_empty() {
434        attach_completed(&mut stack, &mut roots);
435    }
436    roots
437}
438
439fn attach_completed(stack: &mut Vec<FlatSection>, roots: &mut Vec<Section>) {
440    let completed = stack.pop().expect("caller checks non-empty stack").section;
441    if let Some(parent) = stack.last_mut() {
442        parent.section.children.push(completed);
443    } else {
444        roots.push(completed);
445    }
446}
447
448#[derive(Default)]
449struct SectionIds {
450    counts: HashMap<String, usize>,
451    assigned: HashSet<String>,
452    targets: HashMap<String, String>,
453}
454
455impl SectionIds {
456    fn allocate(&mut self, title: &str, explicit: Option<&str>) -> String {
457        let explicit = explicit
458            .map(str::trim)
459            .filter(|value| !value.is_empty())
460            .map(ToOwned::to_owned);
461        let base = explicit.clone().unwrap_or_else(|| slug(title));
462        let base = if base.is_empty() {
463            "section".to_owned()
464        } else if crate::projection::is_reserved_selector(&base) {
465            // Reserved selectors and bare tree paths would shadow this
466            // heading in excerpt selection; keep it addressable instead.
467            format!("{base}-section")
468        } else {
469            base
470        };
471        // Disambiguate on the final id, not the per-base count: `# Foo 2`
472        // slugs to base `foo-2`, which collides with the `foo-2` a second
473        // `# Foo` produces. Counting per base alone would hand both the same
474        // id, silently misattributing search ownership between them.
475        let count = self.counts.entry(base.clone()).or_default();
476        let id = loop {
477            *count += 1;
478            let candidate = if *count == 1 {
479                base.clone()
480            } else {
481                format!("{base}-{}", *count)
482            };
483            if self.assigned.insert(candidate.clone()) {
484                break candidate;
485            }
486        };
487        // Ambiguous human-facing keys resolve to the first section that
488        // claimed them, matching the bare slug this heading renders as its
489        // anchor. A later duplicate owns only its own disambiguated id.
490        self.targets
491            .entry(base.clone())
492            .or_insert_with(|| id.clone());
493        // Heading attributes are source-level link aliases. Preserve the
494        // original alias even when its final section ID had to move out of the
495        // selector namespace (`{#root}`, `{#2.1}`, or `{#2.1/o3}`).
496        if let Some(explicit) = explicit {
497            self.targets.entry(explicit).or_insert_with(|| id.clone());
498        }
499        self.targets
500            .entry(slug(title))
501            .or_insert_with(|| id.clone());
502        self.targets.insert(id.clone(), id.clone());
503        id
504    }
505
506    fn remap_target(&mut self, current: Option<&str>, replacement: Option<&str>) {
507        let Some(current) = current else {
508            return;
509        };
510        if let Some(replacement) = replacement {
511            for target in self.targets.values_mut() {
512                if target == current {
513                    replacement.clone_into(target);
514                }
515            }
516        } else {
517            self.targets.retain(|_, target| target != current);
518        }
519    }
520}
521
522fn slug(value: &str) -> String {
523    let mut output = String::new();
524    let mut separator = false;
525    for character in value.chars().flat_map(char::to_lowercase) {
526        if character.is_alphanumeric() || character == '_' {
527            if separator && !output.is_empty() {
528                output.push('-');
529            }
530            separator = false;
531            output.push(character);
532        } else {
533            separator = true;
534        }
535    }
536    output.trim_matches('-').to_owned()
537}
538
539fn resolve_local_links(
540    root_blocks: &mut [Block],
541    sections: &mut [Section],
542    targets: &HashMap<String, String>,
543    diagnostics: &mut Vec<Diagnostic>,
544) {
545    resolve_blocks(root_blocks, targets, diagnostics);
546    for section in sections {
547        resolve_blocks(&mut section.blocks, targets, diagnostics);
548        resolve_local_links(&mut [], &mut section.children, targets, diagnostics);
549    }
550}
551
552fn resolve_blocks(
553    blocks: &mut [Block],
554    targets: &HashMap<String, String>,
555    diagnostics: &mut Vec<Diagnostic>,
556) {
557    for block in blocks {
558        match block {
559            Block::Paragraph { children, .. } | Block::Preformatted { children, .. } => {
560                resolve_inlines(children, targets, diagnostics);
561            }
562            Block::List { items, .. } => {
563                for item in items {
564                    resolve_blocks(&mut item.blocks, targets, diagnostics);
565                }
566            }
567            Block::DefinitionList { items, .. } => {
568                for item in items {
569                    for term in &mut item.terms {
570                        resolve_inlines(term, targets, diagnostics);
571                    }
572                    resolve_blocks(&mut item.description, targets, diagnostics);
573                }
574            }
575            Block::Table { rows, .. } => {
576                for row in rows {
577                    for cell in &mut row.cells {
578                        resolve_blocks(&mut cell.blocks, targets, diagnostics);
579                    }
580                }
581            }
582            Block::Equation { .. }
583            | Block::VerticalSpace { .. }
584            | Block::ThematicBreak { .. }
585            | Block::Unsupported { .. } => {}
586        }
587    }
588}
589
590fn resolve_inlines(
591    inlines: &mut [Inline],
592    targets: &HashMap<String, String>,
593    diagnostics: &mut Vec<Diagnostic>,
594) {
595    for inline in inlines {
596        match inline {
597            Inline::SectionReference { target, children } => {
598                let lookup = target.trim().trim_start_matches('#');
599                if let Some(id) = targets.get(lookup).or_else(|| targets.get(&slug(lookup))) {
600                    *target = id.clone();
601                } else {
602                    diagnostics.push(Diagnostic {
603                        level: DiagnosticLevel::Warning,
604                        code: Some("markdown.unresolved-reference".to_owned()),
605                        message: format!("unresolved Markdown document link '#{lookup}'"),
606                        source: None,
607                    });
608                }
609                resolve_inlines(children, targets, diagnostics);
610            }
611            Inline::Strong { children }
612            | Inline::Emphasis { children }
613            | Inline::ExternalLink { children, .. }
614            | Inline::EmailLink { children, .. }
615            | Inline::ManualReference { children, .. } => {
616                resolve_inlines(children, targets, diagnostics);
617            }
618            Inline::Text { .. }
619            | Inline::Code { .. }
620            | Inline::Anchor { .. }
621            | Inline::LineBreak => {}
622        }
623    }
624}
625
626pub(super) struct EventCursor<'a> {
627    events: Vec<SpannedEvent<'a>>,
628    position: usize,
629    depth: usize,
630}
631
632/// Recursion budget shared by nested block containers and inline spans.
633///
634/// Parsing recurses once per nesting level, so unbounded input depth would
635/// overflow the stack before any allocation limit applies. Subtrees beyond
636/// this depth are preserved as unsupported source text with a diagnostic.
637const MAX_NESTING_DEPTH: usize = 64;
638
639impl<'a> EventCursor<'a> {
640    fn new(events: Vec<SpannedEvent<'a>>) -> Self {
641        Self {
642            events,
643            position: 0,
644            depth: 0,
645        }
646    }
647
648    /// Reserve one nesting level; callers must pair with [`Self::ascend`].
649    pub(super) fn try_descend(&mut self) -> bool {
650        if self.depth >= MAX_NESTING_DEPTH {
651            return false;
652        }
653        self.depth += 1;
654        true
655    }
656
657    pub(super) fn ascend(&mut self) {
658        self.depth = self.depth.saturating_sub(1);
659    }
660
661    pub(super) fn peek(&self) -> Option<&SpannedEvent<'a>> {
662        self.events.get(self.position)
663    }
664
665    pub(super) fn next(&mut self) -> Option<SpannedEvent<'a>> {
666        let event = self.events.get(self.position)?.clone();
667        self.position += 1;
668        Some(event)
669    }
670
671    /// Consume the remainder of a just-opened tag, including nested tags.
672    pub(super) fn consume_balanced(&mut self, start: Range<usize>) -> Range<usize> {
673        let mut depth = 1usize;
674        let mut end = start.end;
675        while let Some((event, range)) = self.next() {
676            end = range.end;
677            match event {
678                Event::Start(_) => depth = depth.saturating_add(1),
679                Event::End(_) => {
680                    depth = depth.saturating_sub(1);
681                    if depth == 0 {
682                        break;
683                    }
684                }
685                _ => {}
686            }
687        }
688        start.start..end
689    }
690
691    pub(super) fn subtree_contains_task_marker(&self) -> bool {
692        let mut depth = 1usize;
693        for (event, _) in &self.events[self.position..] {
694            match event {
695                Event::TaskListMarker(_) => return true,
696                Event::Start(_) => depth = depth.saturating_add(1),
697                Event::End(_) => {
698                    depth = depth.saturating_sub(1);
699                    if depth == 0 {
700                        return false;
701                    }
702                }
703                _ => {}
704            }
705        }
706        false
707    }
708}