Skip to main content

mant_engine/markdown/
mod.rs

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