1use std::{collections::BTreeMap, ops::Range};
77
78use pulldown_cmark::{CodeBlockKind, Event, MetadataBlockKind, Options, Parser, Tag};
79
80use crate::document::{DocumentError, DocumentResult, Value};
81
82pub fn load(content: &str) -> DocumentResult<Value> {
89 reject_lone_carriage_return(content)?;
90 let events: Vec<SpannedEvent<'_>> = Parser::new_ext(content, options())
91 .into_offset_iter()
92 .collect();
93 reject_deep_nesting(&events)?;
94 let lines = LineIndex::new(content);
95 let mut cursor = 0;
96 Ok(fold_sections(read_blocks(&events, &lines, &mut cursor)))
97}
98
99type SpannedEvent<'a> = (Event<'a>, Range<usize>);
100
101struct LineIndex<'a> {
107 content: &'a str,
108 starts: Vec<usize>,
109}
110
111impl<'a> LineIndex<'a> {
112 fn new(content: &'a str) -> Self {
124 let mut starts = vec![0];
125 for (offset, byte) in content.bytes().enumerate() {
126 if byte == b'\n' {
127 starts.push(offset + 1);
128 }
129 }
130 Self { content, starts }
131 }
132
133 fn number_at(&self, offset: usize) -> i64 {
134 let line = self.starts.partition_point(|start| *start <= offset);
135 i64::try_from(line).unwrap_or(i64::MAX)
136 }
137
138 fn range(&self, source: &Range<usize>) -> SourceLines {
147 let content_end = self
148 .content
149 .get(..source.end)
150 .map_or(source.end, |head| head.trim_end().len())
151 .max(source.start);
152 let end_offset = content_end.saturating_sub(1).max(source.start);
153 SourceLines {
154 start: self.number_at(source.start),
155 end: self.number_at(end_offset),
156 }
157 }
158}
159
160#[derive(Clone, Copy)]
161struct SourceLines {
162 start: i64,
163 end: i64,
164}
165
166fn reject_lone_carriage_return(content: &str) -> DocumentResult<()> {
180 let bytes = content.as_bytes();
181 for (offset, byte) in bytes.iter().enumerate() {
182 if *byte == b'\r' && bytes.get(offset + 1) != Some(&b'\n') {
183 return Err(DocumentError::SourceRefused {
184 format: "Markdown".to_string(),
185 detail: format!(
186 "a bare carriage return at byte {offset} ends a line for CommonMark but not \
187 for the tools these line numbers are meant to feed; convert the file to LF \
188 or CRLF line endings"
189 ),
190 });
191 }
192 }
193 Ok(())
194}
195
196const MAX_BLOCK_DEPTH: usize = 48;
204
205fn reject_deep_nesting(events: &[SpannedEvent<'_>]) -> DocumentResult<()> {
209 let mut depth = 0usize;
210 for (event, _) in events {
211 match event {
212 Event::Start(_) => {
213 depth += 1;
214 if depth > MAX_BLOCK_DEPTH {
215 return Err(DocumentError::SourceRefused {
216 format: "Markdown".to_string(),
217 detail: format!(
218 "blocks and inline spans nest deeper than {MAX_BLOCK_DEPTH} levels"
219 ),
220 });
221 }
222 }
223 Event::End(_) => depth = depth.saturating_sub(1),
224 _ => {}
225 }
226 }
227 Ok(())
228}
229
230fn options() -> Options {
245 Options::ENABLE_YAML_STYLE_METADATA_BLOCKS | Options::ENABLE_PLUSES_DELIMITED_METADATA_BLOCKS
246}
247
248struct Section {
250 level: i64,
251 text: String,
252 inlines: Value,
253 heading_lines: SourceLines,
254 blocks: Vec<Value>,
255 children: Vec<Section>,
256}
257
258fn fold_sections(blocks: Vec<Value>) -> Value {
266 let mut preamble = Vec::new();
267 let mut roots: Vec<Section> = Vec::new();
268 let mut open: Vec<Section> = Vec::new();
269
270 for block in blocks {
271 let heading_level = (block.get("type").and_then(Value::as_str) == Some("heading"))
272 .then(|| block.get("level").and_then(Value::as_integer))
273 .flatten();
274 match heading_level {
275 Some(level) => {
276 while open.last().is_some_and(|section| section.level >= level) {
277 close_section(&mut open, &mut roots);
278 }
279 open.push(Section {
280 level,
281 text: block
282 .get("text")
283 .and_then(Value::as_str)
284 .unwrap_or_default()
285 .to_string(),
286 inlines: block
287 .get("inlines")
288 .cloned()
289 .unwrap_or_else(|| Value::Array(Vec::new())),
290 heading_lines: SourceLines {
291 start: block
292 .get("source_start_line")
293 .and_then(Value::as_integer)
294 .unwrap_or_default(),
295 end: block
296 .get("source_end_line")
297 .and_then(Value::as_integer)
298 .unwrap_or_default(),
299 },
300 blocks: Vec::new(),
301 children: Vec::new(),
302 });
303 }
304 None => match open.last_mut() {
309 Some(section) => section.blocks.push(block),
310 None => preamble.push(block),
311 },
312 }
313 }
314 while !open.is_empty() {
315 close_section(&mut open, &mut roots);
316 }
317
318 let mut root = BTreeMap::from([("preamble".to_string(), Value::Object(block_views(preamble)))]);
323 insert_sections(&mut root, roots);
324 Value::Object(root)
325}
326
327fn close_section(open: &mut Vec<Section>, roots: &mut Vec<Section>) {
330 let Some(done) = open.pop() else { return };
331 match open.last_mut() {
332 Some(parent) => parent.children.push(done),
333 None => roots.push(done),
334 }
335}
336
337fn insert_sections(target: &mut BTreeMap<String, Value>, sections: Vec<Section>) {
340 for section in sections {
341 let key = format!("h{}", section.level);
342 let group = target
343 .entry(key)
344 .or_insert_with(|| Value::Array(Vec::new()));
345 if let Some(items) = group.as_array_mut() {
346 items.push(section.into_value());
347 }
348 }
349}
350
351fn block_views(blocks: Vec<Value>) -> BTreeMap<String, Value> {
362 let of_kind = |kind: &str| {
363 Value::Array(
364 blocks
365 .iter()
366 .filter(|block| block.get("type").and_then(Value::as_str) == Some(kind))
367 .cloned()
368 .collect::<Vec<Value>>(),
369 )
370 };
371 let paragraph = of_kind("paragraph");
372 let blockquote = of_kind("blockquote");
373 BTreeMap::from([
374 ("paragraph".to_string(), paragraph),
375 ("blockquote".to_string(), blockquote),
376 ("blocks".to_string(), Value::Array(blocks)),
377 ])
378}
379
380impl Section {
381 fn into_value(self) -> Value {
382 let source_end_line = self.source_end_line();
383 let mut fields = block_views(self.blocks);
384 fields.insert("level".to_string(), Value::Integer(self.level));
385 fields.insert("text".to_string(), Value::String(self.text));
386 fields.insert("inlines".to_string(), self.inlines);
387 fields.insert(
388 "source_start_line".to_string(),
389 Value::Integer(self.heading_lines.start),
390 );
391 fields.insert(
392 "source_end_line".to_string(),
393 Value::Integer(source_end_line),
394 );
395 fields.insert(
396 "heading_end_line".to_string(),
397 Value::Integer(self.heading_lines.end),
398 );
399 insert_sections(&mut fields, self.children);
400 Value::Object(fields)
401 }
402
403 fn source_end_line(&self) -> i64 {
404 self.blocks
405 .iter()
406 .filter_map(|block| block.get("source_end_line"))
407 .filter_map(Value::as_integer)
408 .chain(self.children.iter().map(Section::source_end_line))
409 .max()
410 .unwrap_or(self.heading_lines.end)
411 }
412}
413
414fn read_blocks(
418 events: &[SpannedEvent<'_>],
419 lines: &LineIndex<'_>,
420 cursor: &mut usize,
421) -> Vec<Value> {
422 let mut blocks = Vec::new();
423 while let Some((event, source)) = events.get(*cursor) {
424 match event {
425 Event::End(_) => break,
426 Event::Rule => {
427 let source = source.clone();
428 *cursor += 1;
429 blocks.push(block("rule", String::new(), &source, lines, vec![]));
430 }
431 Event::Start(tag) if !is_inline_tag(tag) => {
432 let source = source.clone();
433 *cursor += 1;
434 blocks.extend(read_block(tag, &source, events, lines, cursor));
435 }
436 _ => {
441 let first = *cursor;
442 let (text, inlines) = read_loose_inline(events, cursor);
443 if !text.is_empty() {
444 let source = covered_range(events, first, *cursor);
445 blocks.push(block(
446 "paragraph",
447 text,
448 &source,
449 lines,
450 vec![("inlines", inlines)],
451 ));
452 }
453 }
454 }
455 }
456 blocks
457}
458
459fn is_inline_tag(tag: &Tag<'_>) -> bool {
461 matches!(
462 tag,
463 Tag::Emphasis
464 | Tag::Strong
465 | Tag::Strikethrough
466 | Tag::Superscript
467 | Tag::Subscript
468 | Tag::Link { .. }
469 | Tag::Image { .. }
470 )
471}
472
473fn read_block(
475 tag: &Tag<'_>,
476 source: &Range<usize>,
477 events: &[SpannedEvent<'_>],
478 lines: &LineIndex<'_>,
479 cursor: &mut usize,
480) -> Option<Value> {
481 match tag {
482 Tag::Paragraph => {
483 let (text, inlines) = read_inline(events, cursor);
484 Some(block(
485 "paragraph",
486 text,
487 source,
488 lines,
489 vec![("inlines", inlines)],
490 ))
491 }
492 Tag::Heading { level, .. } => {
493 let (text, inlines) = read_inline(events, cursor);
494 Some(block(
495 "heading",
496 text,
497 source,
498 lines,
499 vec![
500 ("level", Value::Integer(*level as i64)),
501 ("inlines", inlines),
502 ],
503 ))
504 }
505 Tag::CodeBlock(kind) => {
506 let info = match kind {
509 CodeBlockKind::Fenced(info) => info.trim().to_string(),
510 CodeBlockKind::Indented => String::new(),
511 };
512 Some(block(
513 "code",
514 read_verbatim(events, cursor),
515 source,
516 lines,
517 vec![("language", Value::String(info))],
524 ))
525 }
526 Tag::HtmlBlock => Some(block(
527 "html",
528 read_verbatim(events, cursor),
529 source,
530 lines,
531 vec![],
532 )),
533 Tag::MetadataBlock(kind) => {
540 skip_subtree(events, cursor);
544 Some(block(
545 "frontmatter",
546 String::new(),
547 source,
548 lines,
549 vec![(
550 "format",
551 Value::String(
552 match kind {
553 MetadataBlockKind::PlusesStyle => "toml",
554 MetadataBlockKind::YamlStyle => "yaml",
555 }
556 .to_string(),
557 ),
558 )],
559 ))
560 }
561 Tag::BlockQuote(_) => {
562 let (text, children) = read_container(events, lines, cursor);
563 Some(block(
564 "blockquote",
565 text,
566 source,
567 lines,
568 vec![("blocks", children)],
569 ))
570 }
571 Tag::List(first_number) => {
572 let (text, children) = read_container(events, lines, cursor);
573 Some(block(
574 "list",
575 text,
576 source,
577 lines,
578 vec![
579 ("ordered", Value::Bool(first_number.is_some())),
580 ("blocks", children),
581 ],
582 ))
583 }
584 Tag::Item => {
587 let (text, children) = read_container(events, lines, cursor);
588 Some(block(
589 "item",
590 text,
591 source,
592 lines,
593 vec![("blocks", children)],
594 ))
595 }
596 _ => {
601 skip_subtree(events, cursor);
602 None
603 }
604 }
605}
606
607fn read_container(
616 events: &[SpannedEvent<'_>],
617 lines: &LineIndex<'_>,
618 cursor: &mut usize,
619) -> (String, Value) {
620 let children = read_blocks(events, lines, cursor);
621 *cursor += 1;
623 let text = children
624 .iter()
625 .filter_map(|child| child.get("text").and_then(Value::as_str))
626 .filter(|text| !text.is_empty())
627 .collect::<Vec<_>>()
628 .join("\n");
629 (text, Value::Array(children))
630}
631
632fn read_inline(events: &[SpannedEvent<'_>], cursor: &mut usize) -> (String, Value) {
642 let read = read_loose_inline(events, cursor);
643 if matches!(events.get(*cursor), Some((Event::End(_), _))) {
644 *cursor += 1;
645 }
646 read
647}
648
649fn read_loose_inline(events: &[SpannedEvent<'_>], cursor: &mut usize) -> (String, Value) {
653 let mut reader = InlineReader::default();
654 let mut depth = 0usize;
655 while let Some((event, _)) = events.get(*cursor) {
656 match event {
657 Event::Start(tag) if depth == 0 && !is_inline_tag(tag) => break,
658 Event::End(_) if depth == 0 => break,
659 Event::Rule if depth == 0 => break,
660 Event::Start(tag) => {
661 depth += 1;
662 reader.open(tag);
663 }
664 Event::End(_) => {
665 depth -= 1;
666 reader.close();
667 }
668 Event::Text(chunk) => reader.text(chunk),
669 Event::Code(chunk) => reader.leaf("code", chunk, chunk),
670 Event::InlineHtml(chunk) | Event::Html(chunk) => reader.leaf("html", chunk, ""),
671 Event::SoftBreak => reader.text(" "),
672 Event::HardBreak => reader.leaf("line_break", "", " "),
673 _ => {}
674 }
675 *cursor += 1;
676 }
677 reader.finish()
678}
679
680struct Inline {
682 kind: &'static str,
683 text: String,
685 destination_url: Option<String>,
686 children: Option<Vec<Inline>>,
689}
690
691impl Inline {
692 fn into_value(self) -> Value {
693 let text = if self.children.is_some() || self.destination_url.is_some() {
696 self.text.trim().to_string()
697 } else {
698 self.text
699 };
700 let mut fields = BTreeMap::from([
701 ("type".to_string(), Value::String(self.kind.to_string())),
702 ("text".to_string(), Value::String(text)),
703 ]);
704 if let Some(url) = self.destination_url {
705 fields.insert("destination_url".to_string(), Value::String(url));
706 }
707 if let Some(children) = self.children {
708 fields.insert("inlines".to_string(), inline_values(children));
709 }
710 Value::Object(fields)
711 }
712}
713
714fn inline_values(inlines: Vec<Inline>) -> Value {
715 Value::Array(inlines.into_iter().map(Inline::into_value).collect())
716}
717
718#[derive(Default)]
727struct InlineReader {
728 text: String,
729 roots: Vec<Inline>,
730 open: Vec<Inline>,
731 opened: Vec<bool>,
733}
734
735impl InlineReader {
736 fn siblings(&mut self) -> &mut Vec<Inline> {
739 match self.open.last_mut() {
740 Some(span) => span.children.get_or_insert_with(Vec::new),
741 None => &mut self.roots,
742 }
743 }
744
745 fn flatten(&mut self, chunk: &str) {
746 self.text.push_str(chunk);
747 for span in &mut self.open {
748 span.text.push_str(chunk);
749 }
750 }
751
752 fn in_image(&self) -> bool {
753 self.open.iter().any(|span| span.kind == "image")
754 }
755
756 fn text(&mut self, chunk: &str) {
757 self.flatten(chunk);
758 if self.in_image() {
759 return;
760 }
761 let siblings = self.siblings();
762 match siblings.last_mut() {
763 Some(last) if last.kind == "text" => last.text.push_str(chunk),
764 _ => siblings.push(Inline {
765 kind: "text",
766 text: chunk.to_string(),
767 destination_url: None,
768 children: None,
769 }),
770 }
771 }
772
773 fn leaf(&mut self, kind: &'static str, node_text: &str, flat: &str) {
774 self.flatten(flat);
775 if self.in_image() {
776 return;
777 }
778 self.siblings().push(Inline {
779 kind,
780 text: node_text.to_string(),
781 destination_url: None,
782 children: None,
783 });
784 }
785
786 fn open(&mut self, tag: &Tag<'_>) {
787 let span = match tag {
788 Tag::Emphasis => Some(("emphasis", None, true)),
789 Tag::Strong => Some(("strong", None, true)),
790 Tag::Link { dest_url, .. } => Some(("link", Some(dest_url.to_string()), true)),
791 Tag::Image { dest_url, .. } => Some(("image", Some(dest_url.to_string()), false)),
792 _ => None,
793 };
794 let span = span.filter(|_| !self.in_image());
796 self.opened.push(span.is_some());
797 if let Some((kind, destination_url, structured)) = span {
798 self.open.push(Inline {
799 kind,
800 text: String::new(),
801 destination_url,
802 children: structured.then(Vec::new),
803 });
804 }
805 }
806
807 fn close(&mut self) {
808 if self.opened.pop() == Some(true)
809 && let Some(done) = self.open.pop()
810 {
811 self.siblings().push(done);
812 }
813 }
814
815 fn finish(mut self) -> (String, Value) {
816 while !self.open.is_empty() {
817 self.opened.push(true);
818 self.close();
819 }
820 (self.text.trim().to_string(), inline_values(self.roots))
821 }
822}
823
824fn read_verbatim(events: &[SpannedEvent<'_>], cursor: &mut usize) -> String {
830 let mut text = String::new();
831 while let Some((event, _)) = events.get(*cursor) {
832 *cursor += 1;
833 match event {
834 Event::End(_) => break,
835 Event::Text(chunk) | Event::Html(chunk) => text.push_str(chunk),
836 _ => {}
837 }
838 }
839 let unterminated = text.trim_suffix('\n');
840 unterminated.trim_suffix('\r').to_string()
841}
842
843fn skip_subtree(events: &[SpannedEvent<'_>], cursor: &mut usize) {
845 let mut depth = 0usize;
846 while let Some((event, _)) = events.get(*cursor) {
847 *cursor += 1;
848 match event {
849 Event::Start(_) => depth += 1,
850 Event::End(_) => {
851 if depth == 0 {
852 break;
853 }
854 depth -= 1;
855 }
856 _ => {}
857 }
858 }
859}
860
861fn covered_range(events: &[SpannedEvent<'_>], start: usize, end: usize) -> Range<usize> {
867 let mut covered = events
868 .get(start)
869 .map(|(_, source)| source.clone())
870 .unwrap_or(0..0);
871 for (_, source) in events.get(start..end).unwrap_or_default() {
872 covered.start = covered.start.min(source.start);
873 covered.end = covered.end.max(source.end);
874 }
875 covered
876}
877
878fn block(
881 kind: &str,
882 text: String,
883 source: &Range<usize>,
884 lines: &LineIndex<'_>,
885 extra: Vec<(&str, Value)>,
886) -> Value {
887 let source = lines.range(source);
888 let mut fields = BTreeMap::from([
889 ("type".to_string(), Value::String(kind.to_string())),
890 ("text".to_string(), Value::String(text)),
891 (
892 "source_start_line".to_string(),
893 Value::Integer(source.start),
894 ),
895 ("source_end_line".to_string(), Value::Integer(source.end)),
896 ]);
897 for (name, value) in extra {
898 fields.insert(name.to_string(), value);
899 }
900 Value::Object(fields)
901}
902
903#[cfg(test)]
904mod tests {
905 #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
906 use super::*;
907 use crate::document::{Addressing, Format, get_path};
908
909 fn at(source: &str, path: &str) -> DocumentResult<Value> {
912 get_path(
913 &load(source).unwrap(),
914 path,
915 Addressing::INDEX_ONLY.with_array_rule(Format::Markdown.array_rule()),
916 )
917 }
918
919 fn text(source: &str, path: &str) -> String {
920 at(source, path)
921 .unwrap_or_else(|error| panic!("{path}: {error}"))
922 .as_str()
923 .unwrap_or_else(|| panic!("{path} is not a string"))
924 .to_string()
925 }
926
927 fn integer(source: &str, path: &str) -> i64 {
928 at(source, path)
929 .unwrap_or_else(|error| panic!("{path}: {error}"))
930 .as_integer()
931 .unwrap_or_else(|| panic!("{path} is not an integer"))
932 }
933
934 fn shape(source: &str, path: &str) -> Vec<(String, String)> {
936 at(source, path)
937 .unwrap_or_else(|error| panic!("{path}: {error}"))
938 .as_array()
939 .unwrap_or_else(|| panic!("{path} is not an array"))
940 .iter()
941 .map(|block| {
942 let field = |name: &str| {
943 block
944 .get(name)
945 .and_then(Value::as_str)
946 .unwrap_or_default()
947 .to_string()
948 };
949 (field("type"), field("text"))
950 })
951 .collect()
952 }
953
954 fn types(source: &str, path: &str) -> Vec<String> {
955 shape(source, path).into_iter().map(|(k, _)| k).collect()
956 }
957
958 #[test]
965 fn probe_1_setext_heading_is_a_heading() {
966 let source = "Title\n=====\n\nThe lead.\n";
968 assert_eq!(text(source, "h1.0.text"), "Title");
969 assert_eq!(text(source, "h1.0.paragraph.0.text"), "The lead.");
970 }
971
972 #[test]
973 fn probe_2_html_comment_before_the_heading_is_its_own_block() {
974 let source = "<!-- generated -->\n\n# Real\n\nThe lead.\n";
977 assert_eq!(
978 shape(source, "preamble.blocks"),
979 [("html".to_string(), "<!-- generated -->".to_string())]
980 );
981 assert_eq!(text(source, "h1.0.text"), "Real");
982 }
983
984 #[test]
985 fn probe_3_badge_line_before_the_heading_is_a_paragraph() {
986 let source = "[](b)\n\n# Real\n\nThe lead.\n";
990 assert_eq!(
991 shape(source, "preamble.blocks"),
992 [("paragraph".to_string(), "CI".to_string())]
993 );
994 assert_eq!(text(source, "h1.0.text"), "Real");
995 assert_eq!(text(source, "h1.0.paragraph.0.text"), "The lead.");
996 }
997
998 #[test]
999 fn probe_4_fenced_code_in_the_lead_position_is_code() {
1000 let source = "# Real\n\n```bash\nafdata get x\n```\n";
1003 assert_eq!(
1004 shape(source, "h1.0.blocks"),
1005 [("code".to_string(), "afdata get x".to_string())]
1006 );
1007 assert_eq!(shape(source, "h1.0.paragraph"), []);
1008 assert_eq!(
1009 at(source, "h1.0.paragraph.0").unwrap_err().code(),
1010 "document_path_not_found"
1011 );
1012 assert_eq!(
1013 at(source, "h1.0.blocks.0.language").unwrap(),
1014 Value::String("bash".to_string())
1015 );
1016 }
1017
1018 #[test]
1019 fn probe_5_leading_fence_swallows_the_heading_inside_it() {
1020 let source = "```\n# Real\n```\n";
1023 assert_eq!(
1024 shape(source, "preamble.blocks"),
1025 [("code".to_string(), "# Real".to_string())]
1026 );
1027 assert_eq!(
1028 at(source, "h1.0").unwrap_err().code(),
1029 "document_path_not_found"
1030 );
1031 }
1032
1033 #[test]
1034 fn probe_6_atx_heading_interrupts_a_paragraph() {
1035 let source = "# Real\n\nThe lead.\n# looks like heading\nmore.\n";
1039 assert_eq!(text(source, "h1.0.text"), "Real");
1040 assert_eq!(
1041 shape(source, "h1.0.paragraph"),
1042 [("paragraph".to_string(), "The lead.".to_string())]
1043 );
1044 assert_eq!(text(source, "h1.1.text"), "looks like heading");
1045 assert_eq!(text(source, "h1.1.paragraph.0.text"), "more.");
1046 }
1047
1048 #[test]
1049 fn probe_7_four_space_indent_is_code_not_a_heading() {
1050 let source = " # Indented\n\nAfter.\n";
1053 assert_eq!(
1054 types(source, "preamble.blocks"),
1055 ["code".to_string(), "paragraph".to_string()]
1056 );
1057 assert_eq!(
1058 at(source, "h1.0").unwrap_err().code(),
1059 "document_path_not_found"
1060 );
1061 }
1062
1063 #[test]
1064 fn probe_8_whole_paragraph_emphasis_is_unwrapped() {
1065 assert_eq!(
1068 text("# Real\n\n**A bold tagline.**\n", "h1.0.paragraph.0.text"),
1069 "A bold tagline."
1070 );
1071 assert_eq!(
1074 text(
1075 "# T\n\nA **bold** `span` and a [link](https://example.com).\n",
1076 "h1.0.paragraph.0.text"
1077 ),
1078 "A bold span and a link."
1079 );
1080 }
1081
1082 #[test]
1085 fn headings_nest_by_level() {
1086 let source = "# A\n\na.\n\n## B\n\nb.\n\n### C\n\nc.\n\n## D\n\nd.\n\n# E\n";
1087 assert_eq!(text(source, "h1.0.text"), "A");
1088 assert_eq!(text(source, "h1.0.paragraph.0.text"), "a.");
1089 assert_eq!(text(source, "h1.0.h2.0.text"), "B");
1090 assert_eq!(text(source, "h1.0.h2.0.h3.0.text"), "C");
1091 assert_eq!(text(source, "h1.0.h2.0.h3.0.paragraph.0.text"), "c.");
1092 assert_eq!(text(source, "h1.0.h2.1.text"), "D");
1094 assert_eq!(
1095 at(source, "h1.0.h2.1.h3.0").unwrap_err().code(),
1096 "document_path_not_found"
1097 );
1098 assert_eq!(text(source, "h1.1.text"), "E");
1099 }
1100
1101 #[test]
1102 fn a_skipped_level_keeps_its_own_name() {
1103 let source = "# A\n\n### C\n\nc.\n";
1106 assert_eq!(text(source, "h1.0.h3.0.text"), "C");
1107 assert_eq!(
1108 at(source, "h1.0.h2.0").unwrap_err().code(),
1109 "document_path_not_found"
1110 );
1111 }
1112
1113 #[test]
1114 fn a_document_opening_below_h1_has_no_h1() {
1115 let source = "## Only\n\ntext.\n";
1118 assert_eq!(text(source, "h2.0.text"), "Only");
1119 assert_eq!(
1120 at(source, "h1.0").unwrap_err().code(),
1121 "document_path_not_found"
1122 );
1123 }
1124
1125 #[test]
1126 fn preamble_is_always_present_and_empty_for_a_clean_file() {
1127 assert_eq!(shape("# T\n\nlead\n", "preamble.blocks"), []);
1128 assert_eq!(shape("", "preamble.blocks"), []);
1129 }
1130
1131 #[test]
1134 fn a_section_is_addressable_by_a_word_of_its_heading() {
1135 let source = "# T\n\n## A Quick Look\n\ninside look.\n\n## Supported suffixes\n\ns.\n";
1136 assert_eq!(text(source, "h1.0.h2.look.text"), "A Quick Look");
1138 assert_eq!(
1139 text(source, "h1.0.h2.look.paragraph.0.text"),
1140 "inside look."
1141 );
1142 assert_eq!(text(source, "h1.0.h2.SUFFIX.text"), "Supported suffixes");
1143 assert_eq!(
1145 at(source, "h1.0.h2.look.text").unwrap(),
1146 at(source, "h1.0.h2.0.text").unwrap()
1147 );
1148 assert_eq!(
1151 at(source, "h1.0.h2.inside").unwrap_err().code(),
1152 "document_slug_not_found"
1153 );
1154 }
1155
1156 #[test]
1157 fn an_empty_segment_is_not_an_address() {
1158 let one = "# T\n\n## Only One\n\na\n";
1163 let two = "# T\n\n## A\n\na\n\n## B\n\nb\n";
1164 for source in [one, two] {
1165 assert_eq!(
1166 at(source, "h1.0.h2..text").unwrap_err().code(),
1167 "document_slug_not_found"
1168 );
1169 }
1170 assert_eq!(text(two, "h1.0.h2.A.text"), "A");
1172 }
1173
1174 #[test]
1175 fn a_word_matching_several_sections_is_refused() {
1176 let source = "# T\n\n## Quick look\n\na.\n\n## Another look\n\nb.\n";
1177 let error = at(source, "h1.0.h2.look").unwrap_err();
1178 assert_eq!(error.code(), "document_ambiguous_match");
1179 let message = error.to_string();
1181 assert!(message.contains("indices 0, 1"), "{message}");
1182 assert!(!message.contains("Quick look"), "{message}");
1183 assert!(!message.contains("Another look"), "{message}");
1184 assert_eq!(text(source, "h1.0.h2.Another.text"), "Another look");
1186 }
1187
1188 #[test]
1189 fn content_addressing_lowercases_unicode() {
1190 let source = "# T\n\n## Überblick\n\ninside.\n";
1191 assert_eq!(text(source, "h1.0.h2.ÜBER.text"), "Überblick");
1192 }
1193
1194 #[test]
1195 fn the_ask_prompt_blockquote_is_addressable_by_its_opening_words() {
1196 let source = "# T\n\nThe lead.\n\n> **Ask your agent:** \"Do the thing.\"\n";
1199 assert_eq!(
1200 text(source, "h1.0.blocks.Ask your agent.text"),
1201 "Ask your agent: \"Do the thing.\""
1202 );
1203 }
1204
1205 #[test]
1208 fn wrapped_paragraph_joins_onto_one_line() {
1209 assert_eq!(
1210 text("# T\n\nLead line one\nline two.\n", "h1.0.paragraph.0.text"),
1211 "Lead line one line two."
1212 );
1213 }
1214
1215 #[test]
1216 fn heading_level_is_reported_for_every_depth() {
1217 let source = "# a\n\n## b\n\n###### f\n";
1218 assert_eq!(at(source, "h1.0.level").unwrap(), Value::Integer(1));
1219 assert_eq!(at(source, "h1.0.h2.0.level").unwrap(), Value::Integer(2));
1220 assert_eq!(
1221 at(source, "h1.0.h2.0.h6.0.level").unwrap(),
1222 Value::Integer(6)
1223 );
1224 }
1225
1226 #[test]
1227 fn blockquote_flattens_its_paragraphs() {
1228 assert_eq!(
1230 shape(
1231 "> **Ask your agent:** \"Wrapped across\n> two lines.\"\n",
1232 "preamble.blocks"
1233 ),
1234 [(
1235 "blockquote".to_string(),
1236 "Ask your agent: \"Wrapped across two lines.\"".to_string()
1237 )]
1238 );
1239 assert_eq!(
1242 shape("> first\n>\n> second\n", "preamble.blocks"),
1243 [("blockquote".to_string(), "first\nsecond".to_string())]
1244 );
1245 }
1246
1247 #[test]
1248 fn list_reports_its_items_and_whether_it_is_ordered() {
1249 let bullet = at("- one\n- two\n", "preamble.blocks.0").unwrap();
1250 assert_eq!(bullet.get("text").and_then(Value::as_str), Some("one\ntwo"));
1251 assert_eq!(bullet.get("ordered"), Some(&Value::Bool(false)));
1252
1253 assert_eq!(
1254 at("1. one\n2. two\n", "preamble.blocks.0")
1255 .unwrap()
1256 .get("ordered"),
1257 Some(&Value::Bool(true))
1258 );
1259
1260 assert_eq!(
1264 at("- one\n\n- two\n", "preamble.blocks.0")
1265 .unwrap()
1266 .get("text")
1267 .and_then(Value::as_str),
1268 Some("one\ntwo")
1269 );
1270
1271 assert_eq!(
1273 at("- one\n - inner\n- two\n", "preamble.blocks.0")
1274 .unwrap()
1275 .get("text")
1276 .and_then(Value::as_str),
1277 Some("one\ninner\ntwo")
1278 );
1279 }
1280
1281 #[test]
1282 fn a_leading_metadata_block_is_its_own_kind() {
1283 let toml = "+++\ntitle = \"T\"\n\n[extra]\ntagline = \"x\"\n+++\n\n# Real\n\nThe lead.\n";
1287 assert_eq!(types(toml, "preamble.blocks"), ["frontmatter".to_string()]);
1288 assert_eq!(
1289 at(toml, "preamble.blocks.0.format").unwrap(),
1290 Value::String("toml".to_string())
1291 );
1292 assert_eq!(text(toml, "preamble.blocks.0.text"), "");
1296 assert_eq!(text(toml, "h1.0.text"), "Real");
1298 assert_eq!(text(toml, "h1.0.paragraph.0.text"), "The lead.");
1299
1300 let yaml = "---\ntitle: T\n---\n\n# Real\n";
1301 assert_eq!(types(yaml, "preamble.blocks"), ["frontmatter".to_string()]);
1302 assert_eq!(
1303 at(yaml, "preamble.blocks.0.format").unwrap(),
1304 Value::String("yaml".to_string())
1305 );
1306 assert_eq!(text(yaml, "h1.0.text"), "Real");
1307 }
1308
1309 #[test]
1310 fn dashes_away_from_the_start_keep_their_commonmark_meaning() {
1311 assert_eq!(text("Setext\n---\n\nbody\n", "h2.0.text"), "Setext");
1315 assert_eq!(
1316 types("# T\n\na\n\n---\n\nb\n", "h1.0.blocks"),
1317 [
1318 "paragraph".to_string(),
1319 "rule".to_string(),
1320 "paragraph".to_string()
1321 ]
1322 );
1323 }
1324
1325 #[test]
1326 fn a_source_range_stops_at_the_block_it_names() {
1327 let source = "- a\n - b\n\n\nAfter.\n";
1333 assert_eq!(
1334 at(source, "preamble.blocks.0.type").unwrap(),
1335 Value::String("list".to_string())
1336 );
1337 assert_eq!(
1338 at(source, "preamble.blocks.0.source_start_line").unwrap(),
1339 Value::Integer(1)
1340 );
1341 assert_eq!(
1342 at(source, "preamble.blocks.0.source_end_line").unwrap(),
1343 Value::Integer(2)
1344 );
1345 assert_eq!(
1346 at(source, "preamble.blocks.1.source_start_line").unwrap(),
1347 Value::Integer(5)
1348 );
1349
1350 let mixed = "# H\n\npara\n\n```\ncode\n```\n\n> quote\n\n---\n\ntail\n";
1353 for (address, start, end) in [
1354 ("h1.0.blocks.0", 3, 3),
1355 ("h1.0.blocks.1", 5, 7),
1356 ("h1.0.blocks.2", 9, 9),
1357 ("h1.0.blocks.3", 11, 11),
1358 ("h1.0.blocks.4", 13, 13),
1359 ] {
1360 assert_eq!(
1361 at(mixed, &format!("{address}.source_start_line")).unwrap(),
1362 Value::Integer(start),
1363 "{address} start"
1364 );
1365 assert_eq!(
1366 at(mixed, &format!("{address}.source_end_line")).unwrap(),
1367 Value::Integer(end),
1368 "{address} end"
1369 );
1370 }
1371 }
1372
1373 #[test]
1374 fn gfm_table_rows_are_a_paragraph() {
1375 assert_eq!(
1378 shape("| a | b |\n|---|---|\n| 1 | 2 |\n", "preamble.blocks"),
1379 [(
1380 "paragraph".to_string(),
1381 "| a | b | |---|---| | 1 | 2 |".to_string()
1382 )]
1383 );
1384 assert_eq!(
1385 shape("| a | b |\n|---|---|\n| 1 | 2 |\n", "preamble.paragraph"),
1386 [(
1387 "paragraph".to_string(),
1388 "| a | b | |---|---| | 1 | 2 |".to_string()
1389 )]
1390 );
1391 }
1392
1393 #[test]
1394 fn badge_syntax_remains_in_the_paragraph_view() {
1395 let source = "# T\n\n[](b)\n\nThe lead.\n";
1396 assert_eq!(
1397 shape(source, "h1.0.paragraph"),
1398 [
1399 ("paragraph".to_string(), "CI".to_string()),
1400 ("paragraph".to_string(), "The lead.".to_string()),
1401 ]
1402 );
1403 }
1404
1405 #[test]
1408 fn atx_heading_and_blocks_report_inclusive_source_lines() {
1409 let source = "# Title\n\nLead line one\nline two.\n\n```rs\nfn main() {}\n```\n";
1410 assert_eq!(integer(source, "h1.0.source_start_line"), 1);
1411 assert_eq!(integer(source, "h1.0.source_end_line"), 8);
1412 assert_eq!(integer(source, "h1.0.source_start_line"), 1);
1413 assert_eq!(integer(source, "h1.0.heading_end_line"), 1);
1414 assert_eq!(integer(source, "h1.0.paragraph.0.source_start_line"), 3);
1415 assert_eq!(integer(source, "h1.0.paragraph.0.source_end_line"), 4);
1416 assert_eq!(integer(source, "h1.0.blocks.1.source_start_line"), 6);
1417 assert_eq!(integer(source, "h1.0.blocks.1.source_end_line"), 8);
1418 }
1419
1420 #[test]
1421 fn setext_heading_range_includes_its_underline() {
1422 let source = "My Project\n==========\n\nThe synopsis.\n\n## Install\n";
1423 assert_eq!(integer(source, "h1.0.source_start_line"), 1);
1424 assert_eq!(integer(source, "h1.0.heading_end_line"), 2);
1425 assert_eq!(integer(source, "h1.0.source_end_line"), 6);
1426 assert_eq!(integer(source, "h1.0.h2.0.source_start_line"), 6);
1427 assert_eq!(integer(source, "h1.0.h2.0.source_end_line"), 6);
1428 assert_eq!(integer(source, "h1.0.paragraph.0.source_start_line"), 4);
1429 assert_eq!(integer(source, "h1.0.paragraph.0.source_end_line"), 4);
1430 }
1431
1432 #[test]
1433 fn line_ranges_are_utf8_safe_and_newline_style_independent() {
1434 let source = "# 中文标题\r\n\r\n这是首段,\r\n也是首段。\r\n\r\n## 安装";
1435 assert_eq!(integer(source, "h1.0.source_start_line"), 1);
1436 assert_eq!(integer(source, "h1.0.heading_end_line"), 1);
1437 assert_eq!(integer(source, "h1.0.paragraph.0.source_start_line"), 3);
1438 assert_eq!(integer(source, "h1.0.paragraph.0.source_end_line"), 4);
1439 assert_eq!(integer(source, "h1.0.h2.0.source_start_line"), 6);
1440 assert_eq!(integer(source, "h1.0.h2.0.heading_end_line"), 6);
1441 }
1442
1443 #[test]
1444 fn nesting_beyond_the_block_depth_is_refused_not_a_stack_overflow() {
1445 let nested = |depth: usize| format!("# T\n{}x\n", "> ".repeat(depth));
1446 assert_eq!(text(&nested(47), "h1.0.blockquote.0.text"), "x");
1448 for depth in [48, 100_000] {
1449 let error = load(&nested(depth)).unwrap_err();
1450 assert_eq!(error.code(), "document_source_refused");
1451 assert!(error.to_string().contains("48 levels"), "{error}");
1452 }
1453 let error = load(&format!("{}x\n", "- ".repeat(100_000))).unwrap_err();
1454 assert_eq!(error.code(), "document_source_refused");
1455 }
1456
1457 #[test]
1458 fn a_bare_carriage_return_is_refused_rather_than_numbered() {
1459 let error = load("# T\r\rLead\rcontinued\r\r## End").unwrap_err();
1465 assert_eq!(error.code(), "document_source_refused");
1469 assert!(error.to_string().contains("carriage return"), "{error}");
1470 assert!(
1474 error.redacted_message().contains("CRLF line endings"),
1475 "{}",
1476 error.redacted_message()
1477 );
1478
1479 let crlf = "# T\r\n\r\nLead\r\ncontinued\r\n\r\n## End\r\n";
1482 assert_eq!(integer(crlf, "h1.0.paragraph.0.source_start_line"), 3);
1483 assert_eq!(integer(crlf, "h1.0.paragraph.0.source_end_line"), 4);
1484 assert_eq!(integer(crlf, "h1.0.h2.0.source_start_line"), 6);
1485
1486 let bare = "# T\n\nLead";
1488 assert_eq!(integer(bare, "h1.0.paragraph.0.source_end_line"), 3);
1489 }
1490
1491 #[test]
1492 fn frontmatter_range_includes_both_delimiters() {
1493 let source = "---\ntitle: T\nnested:\n token_secret: hidden\n---\n\n# T\n";
1494 assert_eq!(integer(source, "preamble.blocks.0.source_start_line"), 1);
1495 assert_eq!(integer(source, "preamble.blocks.0.source_end_line"), 5);
1496 assert_eq!(text(source, "preamble.blocks.0.text"), "");
1497 }
1498
1499 #[test]
1500 fn thematic_break_is_a_block_with_no_text() {
1501 assert_eq!(
1502 shape("# T\n\na\n\n---\n\nb\n", "h1.0.blocks"),
1503 [
1504 ("paragraph".to_string(), "a".to_string()),
1505 ("rule".to_string(), String::new()),
1506 ("paragraph".to_string(), "b".to_string()),
1507 ]
1508 );
1509 assert_eq!(
1512 shape("# T\n\na\n\n---\n\nb\n", "h1.0.paragraph"),
1513 [
1514 ("paragraph".to_string(), "a".to_string()),
1515 ("paragraph".to_string(), "b".to_string()),
1516 ]
1517 );
1518 }
1519
1520 #[test]
1521 fn a_byte_order_mark_makes_the_first_block_a_paragraph() {
1522 assert_eq!(
1527 types("\u{feff}# Title\n\nlead\n", "preamble.blocks"),
1528 ["paragraph".to_string(), "paragraph".to_string()]
1529 );
1530 }
1531
1532 #[test]
1533 fn empty_document_has_no_blocks() {
1534 assert_eq!(shape("", "preamble.blocks"), []);
1535 assert_eq!(shape("\n\n \n", "preamble.blocks"), []);
1536 }
1537
1538 #[test]
1539 fn code_block_keeps_its_lines_and_drops_one_trailing_newline() {
1540 assert_eq!(
1541 shape("```\nline one\nline two\n```\n", "preamble.blocks"),
1542 [("code".to_string(), "line one\nline two".to_string())]
1543 );
1544 }
1545
1546 #[test]
1549 fn inlines_keep_what_text_flattens() {
1550 let source =
1551 "See [the **docs**](docs.md),  and `code` <b>b</b>\\\nend\n";
1552 assert_eq!(
1553 text(source, "preamble.paragraph.0.text"),
1554 "See the docs, alt x and code b end"
1555 );
1556 let kinds = |path: &str| -> Vec<(String, String)> {
1557 at(source, path)
1558 .unwrap()
1559 .as_array()
1560 .unwrap()
1561 .iter()
1562 .map(|node| {
1563 (
1564 node.get("type")
1565 .and_then(Value::as_str)
1566 .unwrap()
1567 .to_string(),
1568 node.get("text")
1569 .and_then(Value::as_str)
1570 .unwrap()
1571 .to_string(),
1572 )
1573 })
1574 .collect()
1575 };
1576 let pairs = |items: &[(&str, &str)]| -> Vec<(String, String)> {
1577 items
1578 .iter()
1579 .map(|(kind, text)| (kind.to_string(), text.to_string()))
1580 .collect()
1581 };
1582 assert_eq!(
1583 kinds("preamble.paragraph.0.inlines"),
1584 pairs(&[
1585 ("text", "See "),
1586 ("link", "the docs"),
1587 ("text", ", "),
1588 ("image", "alt x"),
1589 ("text", " and "),
1590 ("code", "code"),
1591 ("text", " "),
1592 ("html", "<b>"),
1593 ("text", "b"),
1594 ("html", "</b>"),
1595 ("line_break", ""),
1596 ("text", "end"),
1597 ])
1598 );
1599 assert_eq!(
1600 kinds("preamble.paragraph.0.inlines.docs.inlines"),
1601 pairs(&[("text", "the "), ("strong", "docs")])
1602 );
1603 assert_eq!(
1604 text(source, "preamble.paragraph.0.inlines.docs.destination_url"),
1605 "docs.md"
1606 );
1607 assert_eq!(
1608 text(source, "preamble.paragraph.0.inlines.3.destination_url"),
1609 "img.png"
1610 );
1611 assert!(
1613 at(source, "preamble.paragraph.0.inlines.3.inlines").is_err(),
1614 "an image reports flattened alt text only"
1615 );
1616 }
1617
1618 #[test]
1619 fn a_heading_and_its_section_report_inlines() {
1620 let source = "# Run `serve` now\n";
1621 assert_eq!(text(source, "h1.0.text"), "Run serve now");
1622 assert_eq!(text(source, "h1.0.inlines.1.type"), "code");
1623 assert_eq!(text(source, "h1.0.inlines.1.text"), "serve");
1624 }
1625
1626 #[test]
1629 fn a_soft_break_joins_adjacent_text() {
1630 assert_eq!(
1631 text("one\ntwo\n", "preamble.paragraph.0.inlines.0.text"),
1632 "one two"
1633 );
1634 assert!(at("one\ntwo\n", "preamble.paragraph.0.inlines.1").is_err());
1635 }
1636
1637 #[test]
1640 fn containers_report_their_child_blocks() {
1641 let source = "- item\n\n ```bash\n nested\n ```\n\n> ```json\n> {}\n> ```\n";
1642 assert_eq!(text(source, "preamble.blocks.0.blocks.0.type"), "item");
1643 assert_eq!(
1644 text(source, "preamble.blocks.0.blocks.0.blocks.1.type"),
1645 "code"
1646 );
1647 assert_eq!(
1648 text(source, "preamble.blocks.0.blocks.0.blocks.1.language"),
1649 "bash"
1650 );
1651 assert_eq!(
1652 text(source, "preamble.blocks.0.blocks.0.blocks.1.text"),
1653 "nested"
1654 );
1655 assert_eq!(
1656 integer(
1657 source,
1658 "preamble.blocks.0.blocks.0.blocks.1.source_start_line"
1659 ),
1660 3
1661 );
1662 assert_eq!(text(source, "preamble.blocks.1.blocks.0.type"), "code");
1663 assert_eq!(text(source, "preamble.blocks.1.blocks.0.language"), "json");
1664 assert_eq!(text(source, "preamble.blocks.1.blocks.0.text"), "{}");
1665 assert_eq!(text(source, "preamble.blocks.0.text"), "item\nnested");
1667 }
1668
1669 #[test]
1673 fn the_deepest_accepted_file_reports_a_tree_json_can_read_back() {
1674 fn depth(value: &Value) -> usize {
1675 match value {
1676 Value::Array(items) => 1 + items.iter().map(depth).max().unwrap_or(0),
1677 Value::Object(fields) => 1 + fields.values().map(depth).max().unwrap_or(0),
1678 _ => 0,
1679 }
1680 }
1681 let headings = "# a\n## b\n### c\n#### d\n##### e\n###### f\n";
1682 let deepest = [
1684 format!("{headings}{}x\n", "> ".repeat(MAX_BLOCK_DEPTH - 1)),
1685 format!("{headings}{}x\n", "- ".repeat((MAX_BLOCK_DEPTH - 1) / 2)),
1686 format!("{headings}{}*x*\n", "> ".repeat(MAX_BLOCK_DEPTH - 3)),
1687 ];
1688 for source in deepest {
1689 let tree = load(&source).unwrap();
1690 assert!(depth(&tree) <= 112, "{} levels", depth(&tree));
1691 let json = serde_json::to_string(&tree).unwrap();
1692 let enveloped = format!("{{\"kind\":\"result\",\"result\":{{\"value\":{json}}}}}");
1693 serde_json::from_str::<serde_json::Value>(&enveloped).unwrap();
1694 }
1695 }
1696
1697 #[test]
1698 fn inline_nesting_counts_toward_the_depth_limit() {
1699 let nested = |depth: usize| format!("{}x{}\n", "*".repeat(depth), "*".repeat(depth));
1700 assert!(load(&nested(8)).is_ok());
1701 let error = load(&nested(400)).unwrap_err();
1702 assert_eq!(error.code(), "document_source_refused");
1703 }
1704}