1mod 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#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct ParsedMarkdown {
52 pub document: Document,
54 pub tldr: Option<TldrDocument>,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum MarkdownParseError {
61 TldrDirective(TldrDirectiveError),
63 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
78pub 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
139fn 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#[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 §ions,
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
269fn 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 (mut children, end) = parse_inlines(
293 &mut cursor,
294 source,
295 &mut diagnostics,
296 TagEnd::Heading(level),
297 );
298 let explicit_id = explicit_id
304 .map(pulldown_cmark::CowStr::into_string)
305 .or_else(|| take_explicit_heading_id(&mut children));
306 let heading = inline_text(&children);
307 if heading.is_empty() {
308 diagnostics.push(Diagnostic {
309 level: DiagnosticLevel::Warning,
310 code: Some("markdown.empty-heading".to_owned()),
311 message: "ignored an empty Markdown heading".to_owned(),
312 source: Some(source.span(&(range.start..end))),
313 });
314 continue;
315 }
316 let is_document_title = !saw_heading && level == HeadingLevel::H1;
317 saw_heading = true;
318 if is_document_title {
319 title = Some(heading.clone());
320 }
321 let id = ids.allocate(&heading, explicit_id.as_deref());
322 if is_document_title {
323 document_title_id = Some(id.clone());
324 }
325 flat_sections.push(FlatSection {
326 level: heading_level(level),
327 is_document_title,
328 section: Section {
329 id: id.into(),
330 title: heading.clone(),
331 spacing_before_lines: u16::from(!flat_sections.is_empty()),
332 blocks: Vec::new(),
333 children: Vec::new(),
334 source: Some(source.span(&(range.start..end))),
335 },
336 });
337 continue;
338 }
339
340 let Some(block) = parse_block(&mut cursor, source, &mut diagnostics) else {
341 continue;
342 };
343 if let Some(current) = flat_sections.last_mut() {
344 current.section.blocks.push(block);
345 } else {
346 root_blocks.push(block);
347 }
348 }
349
350 ParsedDocumentStructure {
351 diagnostics,
352 root_blocks,
353 flat_sections,
354 ids,
355 title,
356 document_title_id,
357 }
358}
359
360fn markdown_parser() -> ParserInfo {
361 ParserInfo {
362 name: "pulldown-cmark".to_owned(),
363 version: "0.13".to_owned(),
364 }
365}
366
367fn normalize_section_entries(
368 sections: &mut [Section],
369 declarations: &mut BTreeMap<u32, options::EntryDeclaration>,
370 diagnostics: &mut Vec<Diagnostic>,
371) {
372 for section in sections {
373 normalize_entry_lists(&mut section.blocks, declarations, diagnostics);
374 normalize_section_entries(&mut section.children, declarations, diagnostics);
375 }
376}
377
378fn markdown_options() -> Options {
379 Options::ENABLE_TABLES
380 | Options::ENABLE_FOOTNOTES
381 | Options::ENABLE_STRIKETHROUGH
382 | Options::ENABLE_TASKLISTS
383 | Options::ENABLE_YAML_STYLE_METADATA_BLOCKS
384 | Options::ENABLE_PLUSES_DELIMITED_METADATA_BLOCKS
385 | Options::ENABLE_MATH
386 | Options::ENABLE_GFM
387 | Options::ENABLE_DEFINITION_LIST
388 | Options::ENABLE_SUPERSCRIPT
389 | Options::ENABLE_SUBSCRIPT
390 | Options::ENABLE_WIKILINKS
391}
392
393fn take_explicit_heading_id(children: &mut Vec<Inline>) -> Option<String> {
394 let (id, empty) = {
395 let Inline::Text { value } = children.last_mut()? else {
396 return None;
397 };
398 let trimmed = value.trim_end();
399 let opening = trimmed.rfind("{#")?;
400 if !trimmed.ends_with('}') {
401 return None;
402 }
403 if opening != 0
404 && !trimmed[..opening]
405 .chars()
406 .next_back()
407 .is_some_and(char::is_whitespace)
408 {
409 return None;
410 }
411 let id = trimmed
412 .get(opening + 2..trimmed.len().checked_sub(1)?)?
413 .to_owned();
414 if id.is_empty()
415 || id.bytes().any(|byte| {
416 byte.is_ascii_whitespace() || matches!(byte, b'{' | b'}' | b'\\' | b'<' | b'>')
417 })
418 {
419 return None;
420 }
421 let title_end = trimmed[..opening].trim_end().len();
422 value.truncate(title_end);
423 (id, value.is_empty())
424 };
425 if empty {
426 children.pop();
427 }
428 Some(id)
429}
430
431fn heading_level(level: HeadingLevel) -> u8 {
432 match level {
433 HeadingLevel::H1 => 1,
434 HeadingLevel::H2 => 2,
435 HeadingLevel::H3 => 3,
436 HeadingLevel::H4 => 4,
437 HeadingLevel::H5 => 5,
438 HeadingLevel::H6 => 6,
439 }
440}
441
442fn extract_document_title(
444 root_blocks: &mut Vec<Block>,
445 sections: &mut Vec<Section>,
446 document_title_id: Option<&str>,
447) -> bool {
448 let Some(document_title_id) = document_title_id else {
449 return false;
450 };
451 if sections.first().map(|section| section.id.as_str()) != Some(document_title_id) {
452 return false;
453 }
454 let title = sections.remove(0);
455 root_blocks.extend(title.blocks);
456 sections.splice(0..0, title.children);
457 true
458}
459
460struct FlatSection {
461 level: u8,
462 is_document_title: bool,
463 section: Section,
464}
465
466fn nest_sections(flat: Vec<FlatSection>) -> Vec<Section> {
467 let mut roots = Vec::new();
468 let mut stack: Vec<FlatSection> = Vec::new();
469
470 for next in flat {
471 while stack
472 .last()
473 .is_some_and(|current| current.is_document_title || current.level >= next.level)
474 {
475 attach_completed(&mut stack, &mut roots);
476 }
477 stack.push(next);
478 }
479 while !stack.is_empty() {
480 attach_completed(&mut stack, &mut roots);
481 }
482 roots
483}
484
485fn attach_completed(stack: &mut Vec<FlatSection>, roots: &mut Vec<Section>) {
486 let completed = stack.pop().expect("caller checks non-empty stack").section;
487 if let Some(parent) = stack.last_mut() {
488 parent.section.children.push(completed);
489 } else {
490 roots.push(completed);
491 }
492}
493
494#[derive(Default)]
495struct SectionIds {
496 counts: HashMap<String, usize>,
497 assigned: HashSet<String>,
498 targets: HashMap<String, String>,
499}
500
501impl SectionIds {
502 fn allocate(&mut self, title: &str, explicit: Option<&str>) -> String {
503 let explicit = explicit
504 .map(str::trim)
505 .filter(|value| !value.is_empty())
506 .map(ToOwned::to_owned);
507 let base = explicit.clone().unwrap_or_else(|| slug(title));
508 let base = if base.is_empty() {
509 "section".to_owned()
510 } else if crate::projection::is_reserved_selector(&base) {
511 format!("{base}-section")
514 } else {
515 base
516 };
517 let count = self.counts.entry(base.clone()).or_default();
522 let id = loop {
523 *count += 1;
524 let candidate = if *count == 1 {
525 base.clone()
526 } else {
527 format!("{base}-{}", *count)
528 };
529 if self.assigned.insert(candidate.clone()) {
530 break candidate;
531 }
532 };
533 self.targets
537 .entry(base.clone())
538 .or_insert_with(|| id.clone());
539 if let Some(explicit) = explicit {
543 self.targets.entry(explicit).or_insert_with(|| id.clone());
544 }
545 self.targets
546 .entry(slug(title))
547 .or_insert_with(|| id.clone());
548 self.targets.insert(id.clone(), id.clone());
549 id
550 }
551
552 fn remap_target(&mut self, current: Option<&str>, replacement: Option<&str>) {
553 let Some(current) = current else {
554 return;
555 };
556 if let Some(replacement) = replacement {
557 for target in self.targets.values_mut() {
558 if target == current {
559 replacement.clone_into(target);
560 }
561 }
562 } else {
563 self.targets.retain(|_, target| target != current);
564 }
565 }
566}
567
568fn slug(value: &str) -> String {
569 let mut output = String::new();
570 let mut separator = false;
571 for character in value.chars().flat_map(char::to_lowercase) {
572 if character.is_alphanumeric() || character == '_' {
573 if separator && !output.is_empty() {
574 output.push('-');
575 }
576 separator = false;
577 output.push(character);
578 } else {
579 separator = true;
580 }
581 }
582 output.trim_matches('-').to_owned()
583}
584
585struct LocalLinkResolver<'targets> {
586 targets: &'targets HashMap<String, String>,
587}
588
589impl<'targets> LocalLinkResolver<'targets> {
590 fn new(targets: &'targets HashMap<String, String>) -> Self {
591 Self { targets }
592 }
593}
594
595impl VisitMut for LocalLinkResolver<'_> {
596 fn visit_inline_mut(&mut self, inline: &mut Inline) {
597 if let Inline::Link {
598 target: mant_ir::LinkTarget::Section { id },
599 ..
600 } = inline
601 {
602 let lookup = id.trim().trim_start_matches('#');
603 if let Some(resolved) = self
604 .targets
605 .get(lookup)
606 .or_else(|| self.targets.get(&slug(lookup)))
607 {
608 *id = resolved.as_str().into();
609 }
610 }
611 visit::walk_inline_mut(self, inline);
612 }
613}
614
615pub(super) struct EventCursor<'a> {
616 events: Vec<SpannedEvent<'a>>,
617 position: usize,
618 depth: usize,
619}
620
621const MAX_NESTING_DEPTH: usize = 64;
627
628impl<'a> EventCursor<'a> {
629 fn new(events: Vec<SpannedEvent<'a>>) -> Self {
630 Self {
631 events,
632 position: 0,
633 depth: 0,
634 }
635 }
636
637 pub(super) fn try_descend(&mut self) -> bool {
639 if self.depth >= MAX_NESTING_DEPTH {
640 return false;
641 }
642 self.depth += 1;
643 true
644 }
645
646 pub(super) fn ascend(&mut self) {
647 self.depth = self.depth.saturating_sub(1);
648 }
649
650 pub(super) fn peek(&self) -> Option<&SpannedEvent<'a>> {
651 self.events.get(self.position)
652 }
653
654 pub(super) fn next(&mut self) -> Option<SpannedEvent<'a>> {
655 let event = self.events.get(self.position)?.clone();
656 self.position += 1;
657 Some(event)
658 }
659
660 pub(super) fn consume_balanced(&mut self, start: Range<usize>) -> Range<usize> {
662 let mut depth = 1usize;
663 let mut end = start.end;
664 while let Some((event, range)) = self.next() {
665 end = range.end;
666 match event {
667 Event::Start(_) => depth = depth.saturating_add(1),
668 Event::End(_) => {
669 depth = depth.saturating_sub(1);
670 if depth == 0 {
671 break;
672 }
673 }
674 _ => {}
675 }
676 }
677 start.start..end
678 }
679
680 pub(super) fn subtree_contains_task_marker(&self) -> bool {
681 let mut depth = 1usize;
682 for (event, _) in &self.events[self.position..] {
683 match event {
684 Event::TaskListMarker(_) => return true,
685 Event::Start(_) => depth = depth.saturating_add(1),
686 Event::End(_) => {
687 depth = depth.saturating_sub(1);
688 if depth == 0 {
689 return false;
690 }
691 }
692 _ => {}
693 }
694 }
695 false
696 }
697}