1use std::{collections::BTreeMap, ops::Range};
78
79use pulldown_cmark::{CodeBlockKind, Event, MetadataBlockKind, Options, Parser, Tag};
80
81use crate::document::{DocumentError, DocumentResult, Value};
82
83use super::frontmatter::{self, Delimiter};
84
85pub fn load(content: &str) -> DocumentResult<Value> {
92 reject_lone_carriage_return(content)?;
93 let lines = LineIndex::new(content);
94 let mut blocks = Vec::new();
95 let mut markdown = Parser::new_ext(content, metadata_options())
96 .into_offset_iter()
97 .peekable();
98 let mut offset = 0;
99 if let Some((delimiter, parts)) = frontmatter::leading(content) {
100 let closing_line = parts.post.split_inclusive('\n').next().unwrap_or("");
101 let metadata_end = parts.pre.len() + parts.frontmatter.len() + closing_line.len();
102 if !matches!(
106 markdown.peek(),
107 Some((Event::Start(Tag::MetadataBlock(_)), range))
108 if range.start == 0 && range.end <= metadata_end
109 ) {
110 offset = metadata_end;
111 let format = match delimiter {
112 Delimiter::Plus => "toml",
113 Delimiter::Dash => "yaml",
114 };
115 blocks.push(metadata_block(format, &(0..offset), &lines));
116 markdown = Parser::new_ext(&content[offset..], metadata_options())
117 .into_offset_iter()
118 .peekable();
119 }
120 }
121 let events: Vec<SpannedEvent<'_>> = markdown
122 .map(|(event, range)| (event, range.start + offset..range.end + offset))
123 .collect();
124 reject_deep_nesting(&events)?;
125 let mut cursor = 0;
126 blocks.extend(read_blocks(&events, &lines, &mut cursor));
127 Ok(fold_sections(blocks))
128}
129
130type SpannedEvent<'a> = (Event<'a>, Range<usize>);
131
132struct LineIndex<'a> {
138 content: &'a str,
139 starts: Vec<usize>,
140}
141
142impl<'a> LineIndex<'a> {
143 fn new(content: &'a str) -> Self {
155 let mut starts = vec![0];
156 for (offset, byte) in content.bytes().enumerate() {
157 if byte == b'\n' {
158 starts.push(offset + 1);
159 }
160 }
161 Self { content, starts }
162 }
163
164 fn number_at(&self, offset: usize) -> i64 {
165 let line = self.starts.partition_point(|start| *start <= offset);
166 i64::try_from(line).unwrap_or(i64::MAX)
167 }
168
169 fn range(&self, source: &Range<usize>) -> SourceLines {
178 let content_end = self
179 .content
180 .get(..source.end)
181 .map_or(source.end, |head| head.trim_end().len())
182 .max(source.start);
183 let end_offset = content_end.saturating_sub(1).max(source.start);
184 SourceLines {
185 start: self.number_at(source.start),
186 end: self.number_at(end_offset),
187 }
188 }
189}
190
191#[derive(Clone, Copy)]
192struct SourceLines {
193 start: i64,
194 end: i64,
195}
196
197fn reject_lone_carriage_return(content: &str) -> DocumentResult<()> {
211 let bytes = content.as_bytes();
212 for (offset, byte) in bytes.iter().enumerate() {
213 if *byte == b'\r' && bytes.get(offset + 1) != Some(&b'\n') {
214 return Err(DocumentError::SourceRefused {
215 format: "Markdown".to_string(),
216 detail: format!(
217 "a bare carriage return at byte {offset} ends a line for CommonMark but not \
218 for the tools these line numbers are meant to feed; convert the file to LF \
219 or CRLF line endings"
220 ),
221 });
222 }
223 }
224 Ok(())
225}
226
227const MAX_BLOCK_DEPTH: usize = 48;
235
236fn reject_deep_nesting(events: &[SpannedEvent<'_>]) -> DocumentResult<()> {
240 let mut depth = 0usize;
241 for (event, _) in events {
242 match event {
243 Event::Start(_) => {
244 depth += 1;
245 if depth > MAX_BLOCK_DEPTH {
246 return Err(DocumentError::SourceRefused {
247 format: "Markdown".to_string(),
248 detail: format!(
249 "blocks and inline spans nest deeper than {MAX_BLOCK_DEPTH} levels"
250 ),
251 });
252 }
253 }
254 Event::End(_) => depth = depth.saturating_sub(1),
255 _ => {}
256 }
257 }
258 Ok(())
259}
260
261fn metadata_options() -> Options {
265 Options::ENABLE_YAML_STYLE_METADATA_BLOCKS | Options::ENABLE_PLUSES_DELIMITED_METADATA_BLOCKS
266}
267
268fn metadata_block(format: &str, source: &Range<usize>, lines: &LineIndex<'_>) -> Value {
269 block(
270 "frontmatter",
271 String::new(),
272 source,
273 lines,
274 vec![("format", Value::String(format.to_string()))],
275 )
276}
277
278struct Section {
280 level: i64,
281 text: String,
282 inlines: Value,
283 heading_lines: SourceLines,
284 blocks: Vec<Value>,
285 children: Vec<Section>,
286}
287
288fn fold_sections(blocks: Vec<Value>) -> Value {
296 let mut preamble = Vec::new();
297 let mut roots: Vec<Section> = Vec::new();
298 let mut open: Vec<Section> = Vec::new();
299
300 for block in blocks {
301 let heading_level = (block.get("type").and_then(Value::as_str) == Some("heading"))
302 .then(|| block.get("level").and_then(Value::as_integer))
303 .flatten();
304 match heading_level {
305 Some(level) => {
306 while open.last().is_some_and(|section| section.level >= level) {
307 close_section(&mut open, &mut roots);
308 }
309 open.push(Section {
310 level,
311 text: block
312 .get("text")
313 .and_then(Value::as_str)
314 .unwrap_or_default()
315 .to_string(),
316 inlines: block
317 .get("inlines")
318 .cloned()
319 .unwrap_or_else(|| Value::Array(Vec::new())),
320 heading_lines: SourceLines {
321 start: block
322 .get("source_start_line")
323 .and_then(Value::as_integer)
324 .unwrap_or_default(),
325 end: block
326 .get("source_end_line")
327 .and_then(Value::as_integer)
328 .unwrap_or_default(),
329 },
330 blocks: Vec::new(),
331 children: Vec::new(),
332 });
333 }
334 None => match open.last_mut() {
339 Some(section) => section.blocks.push(block),
340 None => preamble.push(block),
341 },
342 }
343 }
344 while !open.is_empty() {
345 close_section(&mut open, &mut roots);
346 }
347
348 let mut root = BTreeMap::from([("preamble".to_string(), Value::Object(block_views(preamble)))]);
353 insert_sections(&mut root, roots);
354 Value::Object(root)
355}
356
357fn close_section(open: &mut Vec<Section>, roots: &mut Vec<Section>) {
360 let Some(done) = open.pop() else { return };
361 match open.last_mut() {
362 Some(parent) => parent.children.push(done),
363 None => roots.push(done),
364 }
365}
366
367fn insert_sections(target: &mut BTreeMap<String, Value>, sections: Vec<Section>) {
370 for section in sections {
371 let key = format!("h{}", section.level);
372 let group = target
373 .entry(key)
374 .or_insert_with(|| Value::Array(Vec::new()));
375 if let Some(items) = group.as_array_mut() {
376 items.push(section.into_value());
377 }
378 }
379}
380
381fn block_views(blocks: Vec<Value>) -> BTreeMap<String, Value> {
392 let of_kind = |kind: &str| {
393 Value::Array(
394 blocks
395 .iter()
396 .filter(|block| block.get("type").and_then(Value::as_str) == Some(kind))
397 .cloned()
398 .collect::<Vec<Value>>(),
399 )
400 };
401 let paragraph = of_kind("paragraph");
402 let blockquote = of_kind("blockquote");
403 BTreeMap::from([
404 ("paragraph".to_string(), paragraph),
405 ("blockquote".to_string(), blockquote),
406 ("blocks".to_string(), Value::Array(blocks)),
407 ])
408}
409
410impl Section {
411 fn into_value(self) -> Value {
412 let source_end_line = self.source_end_line();
413 let mut fields = block_views(self.blocks);
414 fields.insert("level".to_string(), Value::Integer(self.level));
415 fields.insert("text".to_string(), Value::String(self.text));
416 fields.insert("inlines".to_string(), self.inlines);
417 fields.insert(
418 "source_start_line".to_string(),
419 Value::Integer(self.heading_lines.start),
420 );
421 fields.insert(
422 "source_end_line".to_string(),
423 Value::Integer(source_end_line),
424 );
425 fields.insert(
426 "heading_end_line".to_string(),
427 Value::Integer(self.heading_lines.end),
428 );
429 insert_sections(&mut fields, self.children);
430 Value::Object(fields)
431 }
432
433 fn source_end_line(&self) -> i64 {
434 self.blocks
435 .iter()
436 .filter_map(|block| block.get("source_end_line"))
437 .filter_map(Value::as_integer)
438 .chain(self.children.iter().map(Section::source_end_line))
439 .max()
440 .unwrap_or(self.heading_lines.end)
441 }
442}
443
444fn read_blocks(
448 events: &[SpannedEvent<'_>],
449 lines: &LineIndex<'_>,
450 cursor: &mut usize,
451) -> Vec<Value> {
452 let mut blocks = Vec::new();
453 while let Some((event, source)) = events.get(*cursor) {
454 match event {
455 Event::End(_) => break,
456 Event::Rule => {
457 let source = source.clone();
458 *cursor += 1;
459 blocks.push(block("rule", String::new(), &source, lines, vec![]));
460 }
461 Event::Start(tag) if !is_inline_tag(tag) => {
462 let source = source.clone();
463 *cursor += 1;
464 blocks.extend(read_block(tag, &source, events, lines, cursor));
465 }
466 _ => {
471 let first = *cursor;
472 let (text, inlines) = read_loose_inline(events, cursor);
473 if !text.is_empty() {
474 let source = covered_range(events, first, *cursor);
475 blocks.push(block(
476 "paragraph",
477 text,
478 &source,
479 lines,
480 vec![("inlines", inlines)],
481 ));
482 }
483 }
484 }
485 }
486 blocks
487}
488
489fn is_inline_tag(tag: &Tag<'_>) -> bool {
491 matches!(
492 tag,
493 Tag::Emphasis
494 | Tag::Strong
495 | Tag::Strikethrough
496 | Tag::Superscript
497 | Tag::Subscript
498 | Tag::Link { .. }
499 | Tag::Image { .. }
500 )
501}
502
503fn read_block(
505 tag: &Tag<'_>,
506 source: &Range<usize>,
507 events: &[SpannedEvent<'_>],
508 lines: &LineIndex<'_>,
509 cursor: &mut usize,
510) -> Option<Value> {
511 match tag {
512 Tag::Paragraph => {
513 let (text, inlines) = read_inline(events, cursor);
514 Some(block(
515 "paragraph",
516 text,
517 source,
518 lines,
519 vec![("inlines", inlines)],
520 ))
521 }
522 Tag::Heading { level, .. } => {
523 let (text, inlines) = read_inline(events, cursor);
524 Some(block(
525 "heading",
526 text,
527 source,
528 lines,
529 vec![
530 ("level", Value::Integer(*level as i64)),
531 ("inlines", inlines),
532 ],
533 ))
534 }
535 Tag::CodeBlock(kind) => {
536 let info = match kind {
539 CodeBlockKind::Fenced(info) => info.trim().to_string(),
540 CodeBlockKind::Indented => String::new(),
541 };
542 Some(block(
543 "code",
544 read_verbatim(events, cursor),
545 source,
546 lines,
547 vec![("language", Value::String(info))],
554 ))
555 }
556 Tag::HtmlBlock => Some(block(
557 "html",
558 read_verbatim(events, cursor),
559 source,
560 lines,
561 vec![],
562 )),
563 Tag::MetadataBlock(kind) => {
570 skip_subtree(events, cursor);
574 let format = match kind {
575 MetadataBlockKind::PlusesStyle => "toml",
576 MetadataBlockKind::YamlStyle => "yaml",
577 };
578 Some(metadata_block(format, source, lines))
579 }
580 Tag::BlockQuote(_) => {
581 let (text, children) = read_container(events, lines, cursor);
582 Some(block(
583 "blockquote",
584 text,
585 source,
586 lines,
587 vec![("blocks", children)],
588 ))
589 }
590 Tag::List(first_number) => {
591 let (text, children) = read_container(events, lines, cursor);
592 Some(block(
593 "list",
594 text,
595 source,
596 lines,
597 vec![
598 ("ordered", Value::Bool(first_number.is_some())),
599 ("blocks", children),
600 ],
601 ))
602 }
603 Tag::Item => {
606 let (text, children) = read_container(events, lines, cursor);
607 Some(block(
608 "item",
609 text,
610 source,
611 lines,
612 vec![("blocks", children)],
613 ))
614 }
615 _ => {
619 skip_subtree(events, cursor);
620 None
621 }
622 }
623}
624
625fn read_container(
634 events: &[SpannedEvent<'_>],
635 lines: &LineIndex<'_>,
636 cursor: &mut usize,
637) -> (String, Value) {
638 let children = read_blocks(events, lines, cursor);
639 *cursor += 1;
641 let text = children
642 .iter()
643 .filter_map(|child| child.get("text").and_then(Value::as_str))
644 .filter(|text| !text.is_empty())
645 .collect::<Vec<_>>()
646 .join("\n");
647 (text, Value::Array(children))
648}
649
650fn read_inline(events: &[SpannedEvent<'_>], cursor: &mut usize) -> (String, Value) {
660 let read = read_loose_inline(events, cursor);
661 if matches!(events.get(*cursor), Some((Event::End(_), _))) {
662 *cursor += 1;
663 }
664 read
665}
666
667fn read_loose_inline(events: &[SpannedEvent<'_>], cursor: &mut usize) -> (String, Value) {
671 let mut reader = InlineReader::default();
672 let mut depth = 0usize;
673 while let Some((event, _)) = events.get(*cursor) {
674 match event {
675 Event::Start(tag) if depth == 0 && !is_inline_tag(tag) => break,
676 Event::End(_) if depth == 0 => break,
677 Event::Rule if depth == 0 => break,
678 Event::Start(tag) => {
679 depth += 1;
680 reader.open(tag);
681 }
682 Event::End(_) => {
683 depth -= 1;
684 reader.close();
685 }
686 Event::Text(chunk) => reader.text(chunk),
687 Event::Code(chunk) => reader.leaf("code", chunk, chunk),
688 Event::InlineHtml(chunk) | Event::Html(chunk) => reader.leaf("html", chunk, ""),
689 Event::SoftBreak => reader.text(" "),
690 Event::HardBreak => reader.leaf("line_break", "", " "),
691 _ => {}
692 }
693 *cursor += 1;
694 }
695 reader.finish()
696}
697
698struct Inline {
700 kind: &'static str,
701 text: String,
703 destination_url: Option<String>,
704 children: Option<Vec<Inline>>,
707}
708
709impl Inline {
710 fn into_value(self) -> Value {
711 let text = if self.children.is_some() || self.destination_url.is_some() {
714 self.text.trim().to_string()
715 } else {
716 self.text
717 };
718 let mut fields = BTreeMap::from([
719 ("type".to_string(), Value::String(self.kind.to_string())),
720 ("text".to_string(), Value::String(text)),
721 ]);
722 if let Some(url) = self.destination_url {
723 fields.insert("destination_url".to_string(), Value::String(url));
724 }
725 if let Some(children) = self.children {
726 fields.insert("inlines".to_string(), inline_values(children));
727 }
728 Value::Object(fields)
729 }
730}
731
732fn inline_values(inlines: Vec<Inline>) -> Value {
733 Value::Array(inlines.into_iter().map(Inline::into_value).collect())
734}
735
736#[derive(Default)]
745struct InlineReader {
746 text: String,
747 roots: Vec<Inline>,
748 open: Vec<Inline>,
749 opened: Vec<bool>,
751}
752
753impl InlineReader {
754 fn siblings(&mut self) -> &mut Vec<Inline> {
757 match self.open.last_mut() {
758 Some(span) => span.children.get_or_insert_with(Vec::new),
759 None => &mut self.roots,
760 }
761 }
762
763 fn flatten(&mut self, chunk: &str) {
764 self.text.push_str(chunk);
765 for span in &mut self.open {
766 span.text.push_str(chunk);
767 }
768 }
769
770 fn in_image(&self) -> bool {
771 self.open.iter().any(|span| span.kind == "image")
772 }
773
774 fn text(&mut self, chunk: &str) {
775 self.flatten(chunk);
776 if self.in_image() {
777 return;
778 }
779 let siblings = self.siblings();
780 match siblings.last_mut() {
781 Some(last) if last.kind == "text" => last.text.push_str(chunk),
782 _ => siblings.push(Inline {
783 kind: "text",
784 text: chunk.to_string(),
785 destination_url: None,
786 children: None,
787 }),
788 }
789 }
790
791 fn leaf(&mut self, kind: &'static str, node_text: &str, flat: &str) {
792 self.flatten(flat);
793 if self.in_image() {
794 return;
795 }
796 self.siblings().push(Inline {
797 kind,
798 text: node_text.to_string(),
799 destination_url: None,
800 children: None,
801 });
802 }
803
804 fn open(&mut self, tag: &Tag<'_>) {
805 let span = match tag {
806 Tag::Emphasis => Some(("emphasis", None, true)),
807 Tag::Strong => Some(("strong", None, true)),
808 Tag::Link { dest_url, .. } => Some(("link", Some(dest_url.to_string()), true)),
809 Tag::Image { dest_url, .. } => Some(("image", Some(dest_url.to_string()), false)),
810 _ => None,
811 };
812 let span = span.filter(|_| !self.in_image());
814 self.opened.push(span.is_some());
815 if let Some((kind, destination_url, structured)) = span {
816 self.open.push(Inline {
817 kind,
818 text: String::new(),
819 destination_url,
820 children: structured.then(Vec::new),
821 });
822 }
823 }
824
825 fn close(&mut self) {
826 if self.opened.pop() == Some(true)
827 && let Some(done) = self.open.pop()
828 {
829 self.siblings().push(done);
830 }
831 }
832
833 fn finish(mut self) -> (String, Value) {
834 while !self.open.is_empty() {
835 self.opened.push(true);
836 self.close();
837 }
838 (self.text.trim().to_string(), inline_values(self.roots))
839 }
840}
841
842fn read_verbatim(events: &[SpannedEvent<'_>], cursor: &mut usize) -> String {
848 let mut text = String::new();
849 while let Some((event, _)) = events.get(*cursor) {
850 *cursor += 1;
851 match event {
852 Event::End(_) => break,
853 Event::Text(chunk) | Event::Html(chunk) => text.push_str(chunk),
854 _ => {}
855 }
856 }
857 let unterminated = text.trim_suffix('\n');
858 unterminated.trim_suffix('\r').to_string()
859}
860
861fn skip_subtree(events: &[SpannedEvent<'_>], cursor: &mut usize) {
863 let mut depth = 0usize;
864 while let Some((event, _)) = events.get(*cursor) {
865 *cursor += 1;
866 match event {
867 Event::Start(_) => depth += 1,
868 Event::End(_) => {
869 if depth == 0 {
870 break;
871 }
872 depth -= 1;
873 }
874 _ => {}
875 }
876 }
877}
878
879fn covered_range(events: &[SpannedEvent<'_>], start: usize, end: usize) -> Range<usize> {
885 let mut covered = events
886 .get(start)
887 .map(|(_, source)| source.clone())
888 .unwrap_or(0..0);
889 for (_, source) in events.get(start..end).unwrap_or_default() {
890 covered.start = covered.start.min(source.start);
891 covered.end = covered.end.max(source.end);
892 }
893 covered
894}
895
896fn block(
899 kind: &str,
900 text: String,
901 source: &Range<usize>,
902 lines: &LineIndex<'_>,
903 extra: Vec<(&str, Value)>,
904) -> Value {
905 let source = lines.range(source);
906 let mut fields = BTreeMap::from([
907 ("type".to_string(), Value::String(kind.to_string())),
908 ("text".to_string(), Value::String(text)),
909 (
910 "source_start_line".to_string(),
911 Value::Integer(source.start),
912 ),
913 ("source_end_line".to_string(), Value::Integer(source.end)),
914 ]);
915 for (name, value) in extra {
916 fields.insert(name.to_string(), value);
917 }
918 Value::Object(fields)
919}
920
921#[cfg(test)]
922mod tests {
923 #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
924 use super::*;
925 use crate::document::{Addressing, Format, get_path};
926
927 fn at(source: &str, path: &str) -> DocumentResult<Value> {
930 get_path(
931 &load(source).unwrap(),
932 path,
933 Addressing::INDEX_ONLY.with_array_rule(Format::Markdown.array_rule()),
934 )
935 }
936
937 fn text(source: &str, path: &str) -> String {
938 at(source, path)
939 .unwrap_or_else(|error| panic!("{path}: {error}"))
940 .as_str()
941 .unwrap_or_else(|| panic!("{path} is not a string"))
942 .to_string()
943 }
944
945 fn integer(source: &str, path: &str) -> i64 {
946 at(source, path)
947 .unwrap_or_else(|error| panic!("{path}: {error}"))
948 .as_integer()
949 .unwrap_or_else(|| panic!("{path} is not an integer"))
950 }
951
952 fn shape(source: &str, path: &str) -> Vec<(String, String)> {
954 at(source, path)
955 .unwrap_or_else(|error| panic!("{path}: {error}"))
956 .as_array()
957 .unwrap_or_else(|| panic!("{path} is not an array"))
958 .iter()
959 .map(|block| {
960 let field = |name: &str| {
961 block
962 .get(name)
963 .and_then(Value::as_str)
964 .unwrap_or_default()
965 .to_string()
966 };
967 (field("type"), field("text"))
968 })
969 .collect()
970 }
971
972 fn types(source: &str, path: &str) -> Vec<String> {
973 shape(source, path).into_iter().map(|(k, _)| k).collect()
974 }
975
976 #[test]
983 fn probe_1_setext_heading_is_a_heading() {
984 let source = "Title\n=====\n\nThe lead.\n";
986 assert_eq!(text(source, "h1.0.text"), "Title");
987 assert_eq!(text(source, "h1.0.paragraph.0.text"), "The lead.");
988 }
989
990 #[test]
991 fn probe_2_html_comment_before_the_heading_is_its_own_block() {
992 let source = "<!-- generated -->\n\n# Real\n\nThe lead.\n";
995 assert_eq!(
996 shape(source, "preamble.blocks"),
997 [("html".to_string(), "<!-- generated -->".to_string())]
998 );
999 assert_eq!(text(source, "h1.0.text"), "Real");
1000 }
1001
1002 #[test]
1003 fn probe_3_badge_line_before_the_heading_is_a_paragraph() {
1004 let source = "[](b)\n\n# Real\n\nThe lead.\n";
1008 assert_eq!(
1009 shape(source, "preamble.blocks"),
1010 [("paragraph".to_string(), "CI".to_string())]
1011 );
1012 assert_eq!(text(source, "h1.0.text"), "Real");
1013 assert_eq!(text(source, "h1.0.paragraph.0.text"), "The lead.");
1014 }
1015
1016 #[test]
1017 fn probe_4_fenced_code_in_the_lead_position_is_code() {
1018 let source = "# Real\n\n```bash\nafdata get x\n```\n";
1021 assert_eq!(
1022 shape(source, "h1.0.blocks"),
1023 [("code".to_string(), "afdata get x".to_string())]
1024 );
1025 assert_eq!(shape(source, "h1.0.paragraph"), []);
1026 assert_eq!(
1027 at(source, "h1.0.paragraph.0").unwrap_err().code(),
1028 "document_path_not_found"
1029 );
1030 assert_eq!(
1031 at(source, "h1.0.blocks.0.language").unwrap(),
1032 Value::String("bash".to_string())
1033 );
1034 }
1035
1036 #[test]
1037 fn probe_5_leading_fence_swallows_the_heading_inside_it() {
1038 let source = "```\n# Real\n```\n";
1041 assert_eq!(
1042 shape(source, "preamble.blocks"),
1043 [("code".to_string(), "# Real".to_string())]
1044 );
1045 assert_eq!(
1046 at(source, "h1.0").unwrap_err().code(),
1047 "document_path_not_found"
1048 );
1049 }
1050
1051 #[test]
1052 fn probe_6_atx_heading_interrupts_a_paragraph() {
1053 let source = "# Real\n\nThe lead.\n# looks like heading\nmore.\n";
1057 assert_eq!(text(source, "h1.0.text"), "Real");
1058 assert_eq!(
1059 shape(source, "h1.0.paragraph"),
1060 [("paragraph".to_string(), "The lead.".to_string())]
1061 );
1062 assert_eq!(text(source, "h1.1.text"), "looks like heading");
1063 assert_eq!(text(source, "h1.1.paragraph.0.text"), "more.");
1064 }
1065
1066 #[test]
1067 fn probe_7_four_space_indent_is_code_not_a_heading() {
1068 let source = " # Indented\n\nAfter.\n";
1071 assert_eq!(
1072 types(source, "preamble.blocks"),
1073 ["code".to_string(), "paragraph".to_string()]
1074 );
1075 assert_eq!(
1076 at(source, "h1.0").unwrap_err().code(),
1077 "document_path_not_found"
1078 );
1079 }
1080
1081 #[test]
1082 fn probe_8_whole_paragraph_emphasis_is_unwrapped() {
1083 assert_eq!(
1086 text("# Real\n\n**A bold tagline.**\n", "h1.0.paragraph.0.text"),
1087 "A bold tagline."
1088 );
1089 assert_eq!(
1092 text(
1093 "# T\n\nA **bold** `span` and a [link](https://example.com).\n",
1094 "h1.0.paragraph.0.text"
1095 ),
1096 "A bold span and a link."
1097 );
1098 }
1099
1100 #[test]
1103 fn headings_nest_by_level() {
1104 let source = "# A\n\na.\n\n## B\n\nb.\n\n### C\n\nc.\n\n## D\n\nd.\n\n# E\n";
1105 assert_eq!(text(source, "h1.0.text"), "A");
1106 assert_eq!(text(source, "h1.0.paragraph.0.text"), "a.");
1107 assert_eq!(text(source, "h1.0.h2.0.text"), "B");
1108 assert_eq!(text(source, "h1.0.h2.0.h3.0.text"), "C");
1109 assert_eq!(text(source, "h1.0.h2.0.h3.0.paragraph.0.text"), "c.");
1110 assert_eq!(text(source, "h1.0.h2.1.text"), "D");
1112 assert_eq!(
1113 at(source, "h1.0.h2.1.h3.0").unwrap_err().code(),
1114 "document_path_not_found"
1115 );
1116 assert_eq!(text(source, "h1.1.text"), "E");
1117 }
1118
1119 #[test]
1120 fn a_skipped_level_keeps_its_own_name() {
1121 let source = "# A\n\n### C\n\nc.\n";
1124 assert_eq!(text(source, "h1.0.h3.0.text"), "C");
1125 assert_eq!(
1126 at(source, "h1.0.h2.0").unwrap_err().code(),
1127 "document_path_not_found"
1128 );
1129 }
1130
1131 #[test]
1132 fn a_document_opening_below_h1_has_no_h1() {
1133 let source = "## Only\n\ntext.\n";
1136 assert_eq!(text(source, "h2.0.text"), "Only");
1137 assert_eq!(
1138 at(source, "h1.0").unwrap_err().code(),
1139 "document_path_not_found"
1140 );
1141 }
1142
1143 #[test]
1144 fn preamble_is_always_present_and_empty_for_a_clean_file() {
1145 assert_eq!(shape("# T\n\nlead\n", "preamble.blocks"), []);
1146 assert_eq!(shape("", "preamble.blocks"), []);
1147 }
1148
1149 #[test]
1152 fn a_section_is_addressable_by_a_word_of_its_heading() {
1153 let source = "# T\n\n## A Quick Look\n\ninside look.\n\n## Supported suffixes\n\ns.\n";
1154 assert_eq!(text(source, "h1.0.h2.look.text"), "A Quick Look");
1156 assert_eq!(
1157 text(source, "h1.0.h2.look.paragraph.0.text"),
1158 "inside look."
1159 );
1160 assert_eq!(text(source, "h1.0.h2.SUFFIX.text"), "Supported suffixes");
1161 assert_eq!(
1163 at(source, "h1.0.h2.look.text").unwrap(),
1164 at(source, "h1.0.h2.0.text").unwrap()
1165 );
1166 assert_eq!(
1169 at(source, "h1.0.h2.inside").unwrap_err().code(),
1170 "document_slug_not_found"
1171 );
1172 }
1173
1174 #[test]
1175 fn an_empty_segment_is_not_an_address() {
1176 let one = "# T\n\n## Only One\n\na\n";
1181 let two = "# T\n\n## A\n\na\n\n## B\n\nb\n";
1182 for source in [one, two] {
1183 assert_eq!(
1184 at(source, "h1.0.h2..text").unwrap_err().code(),
1185 "document_slug_not_found"
1186 );
1187 }
1188 assert_eq!(text(two, "h1.0.h2.A.text"), "A");
1190 }
1191
1192 #[test]
1193 fn a_word_matching_several_sections_is_refused() {
1194 let source = "# T\n\n## Quick look\n\na.\n\n## Another look\n\nb.\n";
1195 let error = at(source, "h1.0.h2.look").unwrap_err();
1196 assert_eq!(error.code(), "document_ambiguous_match");
1197 let message = error.to_string();
1199 assert!(message.contains("indices 0, 1"), "{message}");
1200 assert!(!message.contains("Quick look"), "{message}");
1201 assert!(!message.contains("Another look"), "{message}");
1202 assert_eq!(text(source, "h1.0.h2.Another.text"), "Another look");
1204 }
1205
1206 #[test]
1207 fn content_addressing_lowercases_unicode() {
1208 let source = "# T\n\n## Überblick\n\ninside.\n";
1209 assert_eq!(text(source, "h1.0.h2.ÜBER.text"), "Überblick");
1210 }
1211
1212 #[test]
1213 fn the_ask_prompt_blockquote_is_addressable_by_its_opening_words() {
1214 let source = "# T\n\nThe lead.\n\n> **Ask your agent:** \"Do the thing.\"\n";
1217 assert_eq!(
1218 text(source, "h1.0.blocks.Ask your agent.text"),
1219 "Ask your agent: \"Do the thing.\""
1220 );
1221 }
1222
1223 #[test]
1226 fn wrapped_paragraph_joins_onto_one_line() {
1227 assert_eq!(
1228 text("# T\n\nLead line one\nline two.\n", "h1.0.paragraph.0.text"),
1229 "Lead line one line two."
1230 );
1231 }
1232
1233 #[test]
1234 fn heading_level_is_reported_for_every_depth() {
1235 let source = "# a\n\n## b\n\n###### f\n";
1236 assert_eq!(at(source, "h1.0.level").unwrap(), Value::Integer(1));
1237 assert_eq!(at(source, "h1.0.h2.0.level").unwrap(), Value::Integer(2));
1238 assert_eq!(
1239 at(source, "h1.0.h2.0.h6.0.level").unwrap(),
1240 Value::Integer(6)
1241 );
1242 }
1243
1244 #[test]
1245 fn blockquote_flattens_its_paragraphs() {
1246 assert_eq!(
1248 shape(
1249 "> **Ask your agent:** \"Wrapped across\n> two lines.\"\n",
1250 "preamble.blocks"
1251 ),
1252 [(
1253 "blockquote".to_string(),
1254 "Ask your agent: \"Wrapped across two lines.\"".to_string()
1255 )]
1256 );
1257 assert_eq!(
1260 shape("> first\n>\n> second\n", "preamble.blocks"),
1261 [("blockquote".to_string(), "first\nsecond".to_string())]
1262 );
1263 }
1264
1265 #[test]
1266 fn list_reports_its_items_and_whether_it_is_ordered() {
1267 let bullet = at("- one\n- two\n", "preamble.blocks.0").unwrap();
1268 assert_eq!(bullet.get("text").and_then(Value::as_str), Some("one\ntwo"));
1269 assert_eq!(bullet.get("ordered"), Some(&Value::Bool(false)));
1270
1271 assert_eq!(
1272 at("1. one\n2. two\n", "preamble.blocks.0")
1273 .unwrap()
1274 .get("ordered"),
1275 Some(&Value::Bool(true))
1276 );
1277
1278 assert_eq!(
1282 at("- one\n\n- two\n", "preamble.blocks.0")
1283 .unwrap()
1284 .get("text")
1285 .and_then(Value::as_str),
1286 Some("one\ntwo")
1287 );
1288
1289 assert_eq!(
1291 at("- one\n - inner\n- two\n", "preamble.blocks.0")
1292 .unwrap()
1293 .get("text")
1294 .and_then(Value::as_str),
1295 Some("one\ninner\ntwo")
1296 );
1297 }
1298
1299 #[test]
1300 fn a_leading_metadata_block_is_its_own_kind() {
1301 let toml = "+++\ntitle = \"T\"\n\n[extra]\ntagline = \"x\"\n+++\n\n# Real\n\nThe lead.\n";
1305 assert_eq!(types(toml, "preamble.blocks"), ["frontmatter".to_string()]);
1306 assert_eq!(
1307 at(toml, "preamble.blocks.0.format").unwrap(),
1308 Value::String("toml".to_string())
1309 );
1310 assert_eq!(text(toml, "preamble.blocks.0.text"), "");
1314 assert_eq!(text(toml, "h1.0.text"), "Real");
1316 assert_eq!(text(toml, "h1.0.paragraph.0.text"), "The lead.");
1317
1318 let yaml = "---\ntitle: T\n---\n\n# Real\n";
1319 assert_eq!(types(yaml, "preamble.blocks"), ["frontmatter".to_string()]);
1320 assert_eq!(
1321 at(yaml, "preamble.blocks.0.format").unwrap(),
1322 Value::String("yaml".to_string())
1323 );
1324 assert_eq!(text(yaml, "h1.0.text"), "Real");
1325 }
1326
1327 #[test]
1328 fn dashes_away_from_the_start_keep_their_commonmark_meaning() {
1329 assert_eq!(text("Setext\n---\n\nbody\n", "h2.0.text"), "Setext");
1332 assert_eq!(
1333 types("# T\n\na\n\n---\n\nb\n", "h1.0.blocks"),
1334 [
1335 "paragraph".to_string(),
1336 "rule".to_string(),
1337 "paragraph".to_string()
1338 ]
1339 );
1340 }
1341
1342 #[test]
1343 fn a_source_range_stops_at_the_block_it_names() {
1344 let source = "- a\n - b\n\n\nAfter.\n";
1350 assert_eq!(
1351 at(source, "preamble.blocks.0.type").unwrap(),
1352 Value::String("list".to_string())
1353 );
1354 assert_eq!(
1355 at(source, "preamble.blocks.0.source_start_line").unwrap(),
1356 Value::Integer(1)
1357 );
1358 assert_eq!(
1359 at(source, "preamble.blocks.0.source_end_line").unwrap(),
1360 Value::Integer(2)
1361 );
1362 assert_eq!(
1363 at(source, "preamble.blocks.1.source_start_line").unwrap(),
1364 Value::Integer(5)
1365 );
1366
1367 let mixed = "# H\n\npara\n\n```\ncode\n```\n\n> quote\n\n---\n\ntail\n";
1370 for (address, start, end) in [
1371 ("h1.0.blocks.0", 3, 3),
1372 ("h1.0.blocks.1", 5, 7),
1373 ("h1.0.blocks.2", 9, 9),
1374 ("h1.0.blocks.3", 11, 11),
1375 ("h1.0.blocks.4", 13, 13),
1376 ] {
1377 assert_eq!(
1378 at(mixed, &format!("{address}.source_start_line")).unwrap(),
1379 Value::Integer(start),
1380 "{address} start"
1381 );
1382 assert_eq!(
1383 at(mixed, &format!("{address}.source_end_line")).unwrap(),
1384 Value::Integer(end),
1385 "{address} end"
1386 );
1387 }
1388 }
1389
1390 #[test]
1391 fn gfm_table_rows_are_a_paragraph() {
1392 assert_eq!(
1395 shape("| a | b |\n|---|---|\n| 1 | 2 |\n", "preamble.blocks"),
1396 [(
1397 "paragraph".to_string(),
1398 "| a | b | |---|---| | 1 | 2 |".to_string()
1399 )]
1400 );
1401 assert_eq!(
1402 shape("| a | b |\n|---|---|\n| 1 | 2 |\n", "preamble.paragraph"),
1403 [(
1404 "paragraph".to_string(),
1405 "| a | b | |---|---| | 1 | 2 |".to_string()
1406 )]
1407 );
1408 }
1409
1410 #[test]
1411 fn badge_syntax_remains_in_the_paragraph_view() {
1412 let source = "# T\n\n[](b)\n\nThe lead.\n";
1413 assert_eq!(
1414 shape(source, "h1.0.paragraph"),
1415 [
1416 ("paragraph".to_string(), "CI".to_string()),
1417 ("paragraph".to_string(), "The lead.".to_string()),
1418 ]
1419 );
1420 }
1421
1422 #[test]
1425 fn atx_heading_and_blocks_report_inclusive_source_lines() {
1426 let source = "# Title\n\nLead line one\nline two.\n\n```rs\nfn main() {}\n```\n";
1427 assert_eq!(integer(source, "h1.0.source_start_line"), 1);
1428 assert_eq!(integer(source, "h1.0.source_end_line"), 8);
1429 assert_eq!(integer(source, "h1.0.source_start_line"), 1);
1430 assert_eq!(integer(source, "h1.0.heading_end_line"), 1);
1431 assert_eq!(integer(source, "h1.0.paragraph.0.source_start_line"), 3);
1432 assert_eq!(integer(source, "h1.0.paragraph.0.source_end_line"), 4);
1433 assert_eq!(integer(source, "h1.0.blocks.1.source_start_line"), 6);
1434 assert_eq!(integer(source, "h1.0.blocks.1.source_end_line"), 8);
1435 }
1436
1437 #[test]
1438 fn setext_heading_range_includes_its_underline() {
1439 let source = "My Project\n==========\n\nThe synopsis.\n\n## Install\n";
1440 assert_eq!(integer(source, "h1.0.source_start_line"), 1);
1441 assert_eq!(integer(source, "h1.0.heading_end_line"), 2);
1442 assert_eq!(integer(source, "h1.0.source_end_line"), 6);
1443 assert_eq!(integer(source, "h1.0.h2.0.source_start_line"), 6);
1444 assert_eq!(integer(source, "h1.0.h2.0.source_end_line"), 6);
1445 assert_eq!(integer(source, "h1.0.paragraph.0.source_start_line"), 4);
1446 assert_eq!(integer(source, "h1.0.paragraph.0.source_end_line"), 4);
1447 }
1448
1449 #[test]
1450 fn line_ranges_are_utf8_safe_and_newline_style_independent() {
1451 let source = "# 中文标题\r\n\r\n这是首段,\r\n也是首段。\r\n\r\n## 安装";
1452 assert_eq!(integer(source, "h1.0.source_start_line"), 1);
1453 assert_eq!(integer(source, "h1.0.heading_end_line"), 1);
1454 assert_eq!(integer(source, "h1.0.paragraph.0.source_start_line"), 3);
1455 assert_eq!(integer(source, "h1.0.paragraph.0.source_end_line"), 4);
1456 assert_eq!(integer(source, "h1.0.h2.0.source_start_line"), 6);
1457 assert_eq!(integer(source, "h1.0.h2.0.heading_end_line"), 6);
1458 }
1459
1460 #[test]
1461 fn nesting_beyond_the_block_depth_is_refused_not_a_stack_overflow() {
1462 let nested = |depth: usize| format!("# T\n{}x\n", "> ".repeat(depth));
1463 assert_eq!(text(&nested(47), "h1.0.blockquote.0.text"), "x");
1465 for depth in [48, 100_000] {
1466 let error = load(&nested(depth)).unwrap_err();
1467 assert_eq!(error.code(), "document_source_refused");
1468 assert!(error.to_string().contains("48 levels"), "{error}");
1469 }
1470 let error = load(&format!("{}x\n", "- ".repeat(100_000))).unwrap_err();
1471 assert_eq!(error.code(), "document_source_refused");
1472 }
1473
1474 #[test]
1475 fn a_bare_carriage_return_is_refused_rather_than_numbered() {
1476 let error = load("# T\r\rLead\rcontinued\r\r## End").unwrap_err();
1482 assert_eq!(error.code(), "document_source_refused");
1486 assert!(error.to_string().contains("carriage return"), "{error}");
1487 assert!(
1491 error.redacted_message().contains("CRLF line endings"),
1492 "{}",
1493 error.redacted_message()
1494 );
1495
1496 let crlf = "# T\r\n\r\nLead\r\ncontinued\r\n\r\n## End\r\n";
1499 assert_eq!(integer(crlf, "h1.0.paragraph.0.source_start_line"), 3);
1500 assert_eq!(integer(crlf, "h1.0.paragraph.0.source_end_line"), 4);
1501 assert_eq!(integer(crlf, "h1.0.h2.0.source_start_line"), 6);
1502
1503 let bare = "# T\n\nLead";
1505 assert_eq!(integer(bare, "h1.0.paragraph.0.source_end_line"), 3);
1506 }
1507
1508 #[test]
1509 fn frontmatter_range_includes_both_delimiters() {
1510 let source = "---\ntitle: T\nnested:\n token_secret: hidden\n---\n\n# T\n";
1511 assert_eq!(integer(source, "preamble.blocks.0.source_start_line"), 1);
1512 assert_eq!(integer(source, "preamble.blocks.0.source_end_line"), 5);
1513 assert_eq!(text(source, "preamble.blocks.0.text"), "");
1514
1515 let source = "+++\r\n\r\ntoken_secret = \"canary\"\r\n+++\t\r\nTitle\r\n=====\r\n";
1516 assert_eq!(integer(source, "preamble.blocks.0.source_start_line"), 1);
1517 assert_eq!(integer(source, "preamble.blocks.0.source_end_line"), 4);
1518 assert_eq!(text(source, "preamble.blocks.0.text"), "");
1519 assert_eq!(integer(source, "h1.0.source_start_line"), 5);
1520 assert_eq!(integer(source, "h1.0.heading_end_line"), 6);
1521 assert_eq!(text(source, "h1.0.text"), "Title");
1522
1523 let source = "---\n---\n---\n\n# T";
1524 assert_eq!(types(source, "preamble.blocks"), ["frontmatter", "rule"]);
1525 assert_eq!(integer(source, "h1.0.source_start_line"), 5);
1526
1527 let source = "---\ntitle: T\n...\n\n# T\n\n---\n";
1528 assert_eq!(integer(source, "preamble.blocks.0.source_end_line"), 3);
1529 assert_eq!(integer(source, "h1.0.source_start_line"), 5);
1530 assert_eq!(types(source, "h1.0.blocks"), ["rule"]);
1531
1532 let source = "---\n\n# Body\n";
1533 assert_eq!(types(source, "preamble.blocks"), ["rule"]);
1534 assert_eq!(text(source, "h1.0.text"), "Body");
1535
1536 let source = "---\n\n# Inside the fences\n\n---\n\n# Body\n";
1537 assert_eq!(types(source, "preamble.blocks"), ["frontmatter"]);
1538 assert_eq!(text(source, "h1.0.text"), "Body");
1539 }
1540
1541 #[test]
1542 fn thematic_break_is_a_block_with_no_text() {
1543 assert_eq!(
1544 shape("# T\n\na\n\n---\n\nb\n", "h1.0.blocks"),
1545 [
1546 ("paragraph".to_string(), "a".to_string()),
1547 ("rule".to_string(), String::new()),
1548 ("paragraph".to_string(), "b".to_string()),
1549 ]
1550 );
1551 assert_eq!(
1554 shape("# T\n\na\n\n---\n\nb\n", "h1.0.paragraph"),
1555 [
1556 ("paragraph".to_string(), "a".to_string()),
1557 ("paragraph".to_string(), "b".to_string()),
1558 ]
1559 );
1560 }
1561
1562 #[test]
1563 fn a_byte_order_mark_makes_the_first_block_a_paragraph() {
1564 assert_eq!(
1569 types("\u{feff}# Title\n\nlead\n", "preamble.blocks"),
1570 ["paragraph".to_string(), "paragraph".to_string()]
1571 );
1572 }
1573
1574 #[test]
1575 fn empty_document_has_no_blocks() {
1576 assert_eq!(shape("", "preamble.blocks"), []);
1577 assert_eq!(shape("\n\n \n", "preamble.blocks"), []);
1578 }
1579
1580 #[test]
1581 fn code_block_keeps_its_lines_and_drops_one_trailing_newline() {
1582 assert_eq!(
1583 shape("```\nline one\nline two\n```\n", "preamble.blocks"),
1584 [("code".to_string(), "line one\nline two".to_string())]
1585 );
1586 }
1587
1588 #[test]
1591 fn inlines_keep_what_text_flattens() {
1592 let source =
1593 "See [the **docs**](docs.md),  and `code` <b>b</b>\\\nend\n";
1594 assert_eq!(
1595 text(source, "preamble.paragraph.0.text"),
1596 "See the docs, alt x and code b end"
1597 );
1598 let kinds = |path: &str| -> Vec<(String, String)> {
1599 at(source, path)
1600 .unwrap()
1601 .as_array()
1602 .unwrap()
1603 .iter()
1604 .map(|node| {
1605 (
1606 node.get("type")
1607 .and_then(Value::as_str)
1608 .unwrap()
1609 .to_string(),
1610 node.get("text")
1611 .and_then(Value::as_str)
1612 .unwrap()
1613 .to_string(),
1614 )
1615 })
1616 .collect()
1617 };
1618 let pairs = |items: &[(&str, &str)]| -> Vec<(String, String)> {
1619 items
1620 .iter()
1621 .map(|(kind, text)| (kind.to_string(), text.to_string()))
1622 .collect()
1623 };
1624 assert_eq!(
1625 kinds("preamble.paragraph.0.inlines"),
1626 pairs(&[
1627 ("text", "See "),
1628 ("link", "the docs"),
1629 ("text", ", "),
1630 ("image", "alt x"),
1631 ("text", " and "),
1632 ("code", "code"),
1633 ("text", " "),
1634 ("html", "<b>"),
1635 ("text", "b"),
1636 ("html", "</b>"),
1637 ("line_break", ""),
1638 ("text", "end"),
1639 ])
1640 );
1641 assert_eq!(
1642 kinds("preamble.paragraph.0.inlines.docs.inlines"),
1643 pairs(&[("text", "the "), ("strong", "docs")])
1644 );
1645 assert_eq!(
1646 text(source, "preamble.paragraph.0.inlines.docs.destination_url"),
1647 "docs.md"
1648 );
1649 assert_eq!(
1650 text(source, "preamble.paragraph.0.inlines.3.destination_url"),
1651 "img.png"
1652 );
1653 assert!(
1655 at(source, "preamble.paragraph.0.inlines.3.inlines").is_err(),
1656 "an image reports flattened alt text only"
1657 );
1658 }
1659
1660 #[test]
1661 fn a_heading_and_its_section_report_inlines() {
1662 let source = "# Run `serve` now\n";
1663 assert_eq!(text(source, "h1.0.text"), "Run serve now");
1664 assert_eq!(text(source, "h1.0.inlines.1.type"), "code");
1665 assert_eq!(text(source, "h1.0.inlines.1.text"), "serve");
1666 }
1667
1668 #[test]
1671 fn a_soft_break_joins_adjacent_text() {
1672 assert_eq!(
1673 text("one\ntwo\n", "preamble.paragraph.0.inlines.0.text"),
1674 "one two"
1675 );
1676 assert!(at("one\ntwo\n", "preamble.paragraph.0.inlines.1").is_err());
1677 }
1678
1679 #[test]
1682 fn containers_report_their_child_blocks() {
1683 let source = "- item\n\n ```bash\n nested\n ```\n\n> ```json\n> {}\n> ```\n";
1684 assert_eq!(text(source, "preamble.blocks.0.blocks.0.type"), "item");
1685 assert_eq!(
1686 text(source, "preamble.blocks.0.blocks.0.blocks.1.type"),
1687 "code"
1688 );
1689 assert_eq!(
1690 text(source, "preamble.blocks.0.blocks.0.blocks.1.language"),
1691 "bash"
1692 );
1693 assert_eq!(
1694 text(source, "preamble.blocks.0.blocks.0.blocks.1.text"),
1695 "nested"
1696 );
1697 assert_eq!(
1698 integer(
1699 source,
1700 "preamble.blocks.0.blocks.0.blocks.1.source_start_line"
1701 ),
1702 3
1703 );
1704 assert_eq!(text(source, "preamble.blocks.1.blocks.0.type"), "code");
1705 assert_eq!(text(source, "preamble.blocks.1.blocks.0.language"), "json");
1706 assert_eq!(text(source, "preamble.blocks.1.blocks.0.text"), "{}");
1707 assert_eq!(text(source, "preamble.blocks.0.text"), "item\nnested");
1709 }
1710
1711 #[test]
1715 fn the_deepest_accepted_file_reports_a_tree_json_can_read_back() {
1716 fn depth(value: &Value) -> usize {
1717 match value {
1718 Value::Array(items) => 1 + items.iter().map(depth).max().unwrap_or(0),
1719 Value::Object(fields) => 1 + fields.values().map(depth).max().unwrap_or(0),
1720 _ => 0,
1721 }
1722 }
1723 let headings = "# a\n## b\n### c\n#### d\n##### e\n###### f\n";
1724 let deepest = [
1726 format!("{headings}{}x\n", "> ".repeat(MAX_BLOCK_DEPTH - 1)),
1727 format!("{headings}{}x\n", "- ".repeat((MAX_BLOCK_DEPTH - 1) / 2)),
1728 format!("{headings}{}*x*\n", "> ".repeat(MAX_BLOCK_DEPTH - 3)),
1729 ];
1730 for source in deepest {
1731 let tree = load(&source).unwrap();
1732 assert!(depth(&tree) <= 112, "{} levels", depth(&tree));
1733 let json = serde_json::to_string(&tree).unwrap();
1734 let enveloped = format!("{{\"kind\":\"result\",\"result\":{{\"value\":{json}}}}}");
1735 serde_json::from_str::<serde_json::Value>(&enveloped).unwrap();
1736 }
1737 }
1738
1739 #[test]
1740 fn inline_nesting_counts_toward_the_depth_limit() {
1741 let nested = |depth: usize| format!("{}x{}\n", "*".repeat(depth), "*".repeat(depth));
1742 assert!(load(&nested(8)).is_ok());
1743 let error = load(&nested(400)).unwrap_err();
1744 assert_eq!(error.code(), "document_source_refused");
1745 }
1746}