- add the process boundary for the core CLI: explicit MARQDO_BIN/--marqdo-bin only (never PATH), argv-only invocation of check ENTRY --emit, bounded timeout, private temp artifact, exit checks and absolute-path sanitisation - deserialize every Analysis record with closed serde shapes and validate semantic invariants that JSON Schema cannot express: identities, source digests, UTF-8 spans, unit tree/order/mode ancestry, anchors, functions and signatures, references states, calls, resources, diagnostics and budgets - validate statement/expression trees structurally with depth and span checks - convert accepted modules into DocumentFacts, preserving honest upstream reference states and one node per Exec unit/function - merge modules across entry contexts only when identity and source agree, otherwise report knowledge.analysis_context_conflict - add the real rc.4 Analysis positive fixture (with provenance and regeneration script), tamper negative tests and optional real-binary integration tests
962 lines
34 KiB
Rust
962 lines
34 KiB
Rust
//! Plain CommonMark/GFM projection for `.md` documents.
|
|
//!
|
|
//! The parser is pinned (`comrak = 1.0.0`) with fixed options and its
|
|
//! line/column source positions are converted to exact half-open UTF-8 byte
|
|
//! spans. This projection is only responsible for narrative structure, links,
|
|
//! metadata and searchable blocks. `@exec` text in a plain `.md` document is
|
|
//! never executable and never creates a function.
|
|
//!
|
|
//! Entity escapes and code whitespace may be normalised inside literals; spans
|
|
//! always point at the original source. Search snippets therefore use exact
|
|
//! source slices, never reconstructed text.
|
|
|
|
use super::ast::{Alignment, AstKind, AstNode};
|
|
use super::{
|
|
AnalysisFacts, AnchorFact, BlockFact, BlockKind, DocumentFacts, DocumentFormat,
|
|
FrontMatterFact, ReferenceFact, SourceFile, UnitFact, UnitKind,
|
|
};
|
|
use crate::diagnostic::{code, Diagnostic, DiagnosticSet};
|
|
use crate::model::{sha256_prefixed, Span};
|
|
use comrak::nodes::{AstNode as ComrakNode, NodeValue, Sourcepos, TableAlignment};
|
|
use comrak::{parse_document, Arena, Options};
|
|
use std::collections::HashMap;
|
|
|
|
/// Bounded front-matter YAML size (the enclosing document limit still applies).
|
|
const FRONT_MATTER_LIMIT: usize = 64 * 1024;
|
|
const YAML_MAX_DEPTH: usize = 32;
|
|
const YAML_MAX_NODES: usize = 10_000;
|
|
|
|
/// Parse one plain Markdown document into normalized facts.
|
|
pub fn parse_plain(file: &SourceFile) -> DocumentFacts {
|
|
let source = file.text.as_str();
|
|
let mut diagnostics = DiagnosticSet::new();
|
|
|
|
let arena = Arena::new();
|
|
let options = plain_options();
|
|
let root = parse_document(&arena, source, &options);
|
|
|
|
let mut context = ConvertContext {
|
|
source,
|
|
len: source.len() as u64,
|
|
line_starts: line_starts(source),
|
|
max_depth: super::MAX_AST_DEPTH,
|
|
diagnostics: &mut diagnostics,
|
|
};
|
|
let mut ast = context.convert(root, 0);
|
|
ast.span = Span::new(0, source.len() as u64);
|
|
if let Err(message) = ast.validate(source.as_bytes(), super::MAX_AST_DEPTH) {
|
|
diagnostics
|
|
.push(Diagnostic::error(code::MARKDOWN_INVALID, message).with_path(&file.rel_path));
|
|
}
|
|
|
|
let front_matter = front_matter_fact(&ast, &mut diagnostics, &file.rel_path);
|
|
let mut units = build_units(&ast, file);
|
|
fix_unit_spans(&mut units, source.len() as u64);
|
|
let anchors = build_anchors(&units);
|
|
let title = document_title(&units, &file.rel_path);
|
|
|
|
let references = extract_references(&ast, &units);
|
|
let blocks = searchable_blocks(&ast, &units);
|
|
|
|
DocumentFacts {
|
|
rel_path: file.rel_path.clone(),
|
|
format: DocumentFormat::PlainMarkdown,
|
|
source_digest: sha256_prefixed(source.as_bytes()),
|
|
document_title: title,
|
|
ast,
|
|
units,
|
|
anchors,
|
|
functions: Vec::new(),
|
|
imports: Vec::new(),
|
|
references,
|
|
calls: Vec::new(),
|
|
resources: Vec::new(),
|
|
blocks,
|
|
front_matter,
|
|
analysis: None::<AnalysisFacts>,
|
|
diagnostics,
|
|
}
|
|
}
|
|
|
|
fn plain_options() -> Options<'static> {
|
|
let mut options = Options::default();
|
|
// Fixed plain-Markdown profile. This is not the Marqdo language profile.
|
|
options.extension.table = true;
|
|
options.extension.strikethrough = true;
|
|
options.extension.tasklist = true;
|
|
options.extension.autolink = true;
|
|
options.extension.footnotes = true;
|
|
options.extension.math_dollars = true;
|
|
options.extension.math_dollars_block = true;
|
|
options.extension.math_latex = false;
|
|
options.extension.math_code = false;
|
|
options.extension.front_matter_delimiter = Some("---".to_string());
|
|
options
|
|
}
|
|
|
|
fn line_starts(source: &str) -> Vec<usize> {
|
|
let mut starts = vec![0usize];
|
|
for (index, byte) in source.bytes().enumerate() {
|
|
if byte == b'\n' {
|
|
starts.push(index + 1);
|
|
}
|
|
}
|
|
starts
|
|
}
|
|
|
|
struct ConvertContext<'a> {
|
|
source: &'a str,
|
|
len: u64,
|
|
line_starts: Vec<usize>,
|
|
max_depth: usize,
|
|
diagnostics: &'a mut DiagnosticSet,
|
|
}
|
|
|
|
impl<'a> ConvertContext<'a> {
|
|
fn convert(&mut self, node: &'a ComrakNode<'a>, depth: usize) -> AstNode {
|
|
let data = node.data.borrow();
|
|
let span = self.span_of(&data.sourcepos);
|
|
let value = &data.value;
|
|
let mut out = match value {
|
|
NodeValue::Document => AstNode {
|
|
span: Span::new(0, self.len),
|
|
..AstNode::new(AstKind::Document, Span::new(0, self.len))
|
|
},
|
|
NodeValue::FrontMatter(literal) => {
|
|
AstNode::new(AstKind::FrontMatter, span).with_literal(literal.clone())
|
|
}
|
|
NodeValue::BlockQuote => AstNode::new(AstKind::BlockQuote, span),
|
|
NodeValue::List(list) => {
|
|
let mut out = AstNode::new(AstKind::List, span);
|
|
let ordered = matches!(list.list_type, comrak::nodes::ListType::Ordered);
|
|
out.ordered = Some(ordered);
|
|
out.tight = Some(list.tight);
|
|
out.start = ordered.then_some(list.start as u64);
|
|
out
|
|
}
|
|
NodeValue::Item(_) => AstNode::new(AstKind::Item, span),
|
|
NodeValue::TaskItem(task) => {
|
|
let mut out = AstNode::new(AstKind::Item, span);
|
|
out.task = Some(task.symbol.is_some());
|
|
out
|
|
}
|
|
NodeValue::Heading(heading) => {
|
|
let mut out = AstNode::new(AstKind::Heading, span);
|
|
out.level = Some(heading.level);
|
|
out.setext = Some(heading.setext);
|
|
out
|
|
}
|
|
NodeValue::Paragraph => AstNode::new(AstKind::Paragraph, span),
|
|
NodeValue::Text(literal) => {
|
|
AstNode::new(AstKind::Text, span).with_literal(literal.clone())
|
|
}
|
|
NodeValue::Emph(_) => AstNode::new(AstKind::Emph, span),
|
|
NodeValue::Strong(_) => AstNode::new(AstKind::Strong, span),
|
|
NodeValue::Strikethrough(_) => AstNode::new(AstKind::Strikethrough, span),
|
|
NodeValue::Code(node_code) => {
|
|
let mut out =
|
|
AstNode::new(AstKind::Code, span).with_literal(node_code.literal.clone());
|
|
out.ticks = Some(node_code.num_backticks as u32);
|
|
out
|
|
}
|
|
NodeValue::CodeBlock(block) => {
|
|
let mut out =
|
|
AstNode::new(AstKind::CodeBlock, span).with_literal(block.literal.clone());
|
|
out.fenced = Some(block.fenced);
|
|
out.info = Some(block.info.clone());
|
|
out
|
|
}
|
|
NodeValue::HtmlBlock(block) => {
|
|
AstNode::new(AstKind::HtmlBlock, span).with_literal(block.literal.clone())
|
|
}
|
|
NodeValue::SoftBreak => AstNode::new(AstKind::SoftBreak, span),
|
|
NodeValue::LineBreak => AstNode::new(AstKind::LineBreak, span),
|
|
NodeValue::Link(link) => {
|
|
let mut out = AstNode::new(AstKind::Link, span);
|
|
out.url = Some(link.url.clone());
|
|
out.title = Some(link.title.clone());
|
|
out
|
|
}
|
|
NodeValue::Image(link) => {
|
|
let mut out = AstNode::new(AstKind::Image, span);
|
|
out.url = Some(link.url.clone());
|
|
out.title = Some(link.title.clone());
|
|
out
|
|
}
|
|
NodeValue::Table(table) => {
|
|
let mut out = AstNode::new(AstKind::Table, span);
|
|
out.alignments = Some(
|
|
table
|
|
.alignments
|
|
.iter()
|
|
.map(|alignment| match alignment {
|
|
TableAlignment::None => Alignment::None,
|
|
TableAlignment::Left => Alignment::Left,
|
|
TableAlignment::Center => Alignment::Center,
|
|
TableAlignment::Right => Alignment::Right,
|
|
})
|
|
.collect(),
|
|
);
|
|
out
|
|
}
|
|
NodeValue::TableRow(row) => {
|
|
let mut out = AstNode::new(AstKind::TableRow, span);
|
|
out.header = Some(row.header);
|
|
out
|
|
}
|
|
NodeValue::TableCell => AstNode::new(AstKind::TableCell, span),
|
|
NodeValue::ThematicBreak(_) => AstNode::new(AstKind::ThematicBreak, span),
|
|
NodeValue::Math(math) => {
|
|
let mut out = AstNode::new(AstKind::Math, span).with_literal(math.literal.clone());
|
|
out.display = Some(math.display_math);
|
|
out
|
|
}
|
|
NodeValue::MathBlock(math) => {
|
|
AstNode::new(AstKind::MathBlock, span).with_literal(math.literal.clone())
|
|
}
|
|
NodeValue::HtmlInline(literal) => {
|
|
AstNode::new(AstKind::HtmlInline, span).with_literal(literal.clone())
|
|
}
|
|
other => {
|
|
let mut out = AstNode::new(AstKind::Other, span);
|
|
out.tag = Some(other.xml_node_name().to_string());
|
|
if let NodeValue::Raw(literal) = other {
|
|
out.literal = Some(literal.clone());
|
|
}
|
|
if let NodeValue::FootnoteDefinition(definition) = other {
|
|
out.tag = Some(format!("footnote_definition:{}", definition.name));
|
|
}
|
|
out
|
|
}
|
|
};
|
|
drop(data);
|
|
|
|
if depth >= self.max_depth {
|
|
self.diagnostics.push(Diagnostic::error(
|
|
code::MARKDOWN_INVALID,
|
|
format!(
|
|
"document AST depth exceeds the {} level budget; the subtree was truncated",
|
|
self.max_depth
|
|
),
|
|
));
|
|
return out;
|
|
}
|
|
let children: Vec<AstNode> = node
|
|
.children()
|
|
.map(|child| self.convert(child, depth + 1))
|
|
.collect();
|
|
out.children = children;
|
|
out
|
|
}
|
|
|
|
/// Convert comrak's 1-based inclusive byte columns into half-open byte
|
|
/// spans. Invalid positions are reported once and degrade to an empty span.
|
|
fn span_of(&mut self, position: &Sourcepos) -> Span {
|
|
let span = self.try_span_of(position);
|
|
if span.is_none() {
|
|
self.diagnostics.push(Diagnostic::warning(
|
|
code::MARKDOWN_INVALID,
|
|
"parser produced a source position outside the document; span was clamped",
|
|
));
|
|
}
|
|
span.unwrap_or_else(|| Span::new(0, 0))
|
|
}
|
|
|
|
fn try_span_of(&self, position: &Sourcepos) -> Option<Span> {
|
|
let start = self.line_start(position.start.line)? + position.start.column.checked_sub(1)?;
|
|
let end = self.line_start(position.end.line)? + position.end.column;
|
|
if start > end || end > self.len as usize {
|
|
return None;
|
|
}
|
|
let span = Span::new(start as u64, end as u64);
|
|
if !span.on_utf8_boundaries(self.source.as_bytes()) {
|
|
return None;
|
|
}
|
|
Some(span)
|
|
}
|
|
|
|
fn line_start(&self, line: usize) -> Option<usize> {
|
|
match line {
|
|
0 => Some(0),
|
|
_ => self.line_starts.get(line - 1).copied(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Build the heading units. Only top-level document headings declare units;
|
|
/// headings inside lists, quotes or fences do not.
|
|
fn build_units(ast: &AstNode, file: &SourceFile) -> Vec<UnitFact> {
|
|
let mut units = vec![UnitFact {
|
|
path: Vec::new(),
|
|
kind: UnitKind::Root,
|
|
name: String::new(),
|
|
level: 0,
|
|
span: Span::new(0, file.text.len() as u64),
|
|
heading_span: None,
|
|
parent: None,
|
|
function_id: None,
|
|
unit_id: None,
|
|
mode: "knowledge".to_string(),
|
|
occurrence: 0,
|
|
}];
|
|
let mut stack: Vec<usize> = vec![0];
|
|
let mut seen_paths: HashMap<Vec<String>, usize> = HashMap::new();
|
|
for child in &ast.children {
|
|
if child.kind != AstKind::Heading {
|
|
continue;
|
|
}
|
|
let level = child.level.unwrap_or(1);
|
|
let name = child.normalized_name();
|
|
while stack.len() > 1 {
|
|
let top = units[*stack.last().expect("root present")].level;
|
|
if top >= level {
|
|
stack.pop();
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
let parent = *stack.last().unwrap_or(&0);
|
|
let mut path = units[parent].path.clone();
|
|
path.push(name.clone());
|
|
let occurrence = {
|
|
let counter = seen_paths.entry(path.clone()).or_insert(0);
|
|
let value = *counter;
|
|
*counter += 1;
|
|
value as u32
|
|
};
|
|
let fact = UnitFact {
|
|
path,
|
|
kind: if level == 1 {
|
|
UnitKind::Namespace
|
|
} else {
|
|
UnitKind::Section
|
|
},
|
|
name,
|
|
level,
|
|
span: child.span,
|
|
heading_span: Some(child.span),
|
|
parent: Some(parent),
|
|
function_id: None,
|
|
unit_id: None,
|
|
mode: "knowledge".to_string(),
|
|
occurrence,
|
|
};
|
|
let index = units.len();
|
|
units.push(fact);
|
|
stack.push(index);
|
|
}
|
|
units
|
|
}
|
|
|
|
/// Compute complete section ranges: heading start to the next heading of the
|
|
/// same or higher level, or EOF.
|
|
fn fix_unit_spans(units: &mut [UnitFact], source_len: u64) {
|
|
for index in 1..units.len() {
|
|
let level = units[index].level;
|
|
let start = units[index]
|
|
.heading_span
|
|
.map(|span| span.start)
|
|
.unwrap_or(units[index].span.start);
|
|
let mut end = source_len;
|
|
for later in units.iter().skip(index + 1) {
|
|
if later.level <= level {
|
|
end = later
|
|
.heading_span
|
|
.map(|span| span.start)
|
|
.unwrap_or(later.span.start);
|
|
break;
|
|
}
|
|
}
|
|
units[index].span = Span::new(start, end);
|
|
}
|
|
if let Some(root) = units.first_mut() {
|
|
root.span = Span::new(0, source_len);
|
|
}
|
|
}
|
|
|
|
/// Fixed renderer anchor rules: NFC, ASCII lowercase, whitespace runs to `-`,
|
|
/// keep Unicode alphanumerics, `-` and `_`, drop other punctuation; duplicate
|
|
/// anchors get `-1`, `-2`, ... suffixes in document order.
|
|
pub fn slugify(name: &str) -> String {
|
|
let normalized = super::ast::normalize_heading_name(name);
|
|
let mut slug = String::new();
|
|
let mut pending_dash = false;
|
|
for ch in normalized.chars() {
|
|
if ch.is_whitespace() {
|
|
pending_dash = !slug.is_empty();
|
|
continue;
|
|
}
|
|
if ch.is_alphanumeric() || ch == '_' || ch == '-' {
|
|
if pending_dash {
|
|
slug.push('-');
|
|
pending_dash = false;
|
|
}
|
|
if ch.is_ascii_uppercase() {
|
|
slug.push(ch.to_ascii_lowercase());
|
|
} else {
|
|
slug.push(ch);
|
|
}
|
|
}
|
|
}
|
|
while slug.ends_with('-') {
|
|
slug.pop();
|
|
}
|
|
slug
|
|
}
|
|
|
|
fn build_anchors(units: &[UnitFact]) -> Vec<AnchorFact> {
|
|
let mut anchors = Vec::new();
|
|
let mut used: HashMap<String, usize> = HashMap::new();
|
|
for (index, unit) in units.iter().enumerate() {
|
|
if index == 0 || unit.name.is_empty() {
|
|
continue;
|
|
}
|
|
let base = slugify(&unit.name);
|
|
if base.is_empty() {
|
|
continue;
|
|
}
|
|
let count = used.entry(base.clone()).or_insert(0);
|
|
let anchor = if *count == 0 {
|
|
base.clone()
|
|
} else {
|
|
format!("{base}-{count}")
|
|
};
|
|
*count += 1;
|
|
anchors.push(AnchorFact {
|
|
anchor,
|
|
unit: index,
|
|
});
|
|
}
|
|
anchors
|
|
}
|
|
|
|
fn document_title(units: &[UnitFact], rel_path: &str) -> String {
|
|
if let Some(h1) = units
|
|
.iter()
|
|
.find(|unit| unit.kind == UnitKind::Namespace && !unit.name.is_empty())
|
|
{
|
|
return h1.name.clone();
|
|
}
|
|
let file = rel_path.rsplit('/').next().unwrap_or(rel_path);
|
|
for suffix in [".mq.md", ".md"] {
|
|
if let Some(stem) = file.strip_suffix(suffix) {
|
|
return stem.to_string();
|
|
}
|
|
}
|
|
file.to_string()
|
|
}
|
|
|
|
pub(crate) fn front_matter_fact(
|
|
ast: &AstNode,
|
|
diagnostics: &mut DiagnosticSet,
|
|
rel_path: &str,
|
|
) -> Option<FrontMatterFact> {
|
|
let node = ast
|
|
.children
|
|
.iter()
|
|
.find(|child| child.kind == AstKind::FrontMatter)?;
|
|
let literal = node.literal.clone().unwrap_or_default();
|
|
let mut fact = FrontMatterFact {
|
|
span: node.span,
|
|
literal: literal.clone(),
|
|
value: None,
|
|
error: None,
|
|
};
|
|
let yaml = match front_matter_yaml(&literal) {
|
|
Some(yaml) => yaml,
|
|
None => {
|
|
fact.error = Some("front matter delimiters are incomplete".to_string());
|
|
diagnostics.push(
|
|
Diagnostic::warning(
|
|
code::UNKNOWN_FRONT_MATTER,
|
|
"front matter could not be delimited; raw text was preserved",
|
|
)
|
|
.with_path(rel_path)
|
|
.with_span(node.span),
|
|
);
|
|
return Some(fact);
|
|
}
|
|
};
|
|
if yaml.len() > FRONT_MATTER_LIMIT {
|
|
fact.error = Some("front matter exceeds the 64 KiB limit".to_string());
|
|
diagnostics.push(
|
|
Diagnostic::warning(
|
|
code::UNKNOWN_FRONT_MATTER,
|
|
"front matter exceeds the 64 KiB limit; raw text was preserved",
|
|
)
|
|
.with_path(rel_path)
|
|
.with_span(node.span),
|
|
);
|
|
return Some(fact);
|
|
}
|
|
if yaml.contains('&') || yaml.contains('*') {
|
|
fact.error = Some("YAML anchors and aliases are not accepted".to_string());
|
|
diagnostics.push(
|
|
Diagnostic::warning(
|
|
code::UNKNOWN_FRONT_MATTER,
|
|
"YAML anchors/aliases are not accepted; metadata was not interpreted",
|
|
)
|
|
.with_path(rel_path)
|
|
.with_span(node.span),
|
|
);
|
|
return Some(fact);
|
|
}
|
|
match serde_yaml::from_str::<serde_yaml::Value>(&yaml) {
|
|
Ok(value) => {
|
|
match yaml_to_json(&value, 0, &mut 0) {
|
|
Ok(json) => fact.value = Some(json),
|
|
Err(message) => {
|
|
fact.error = Some(message.clone());
|
|
diagnostics.push(
|
|
Diagnostic::warning(
|
|
code::UNKNOWN_FRONT_MATTER,
|
|
format!("front matter metadata was preserved but not interpreted: {message}"),
|
|
)
|
|
.with_path(rel_path)
|
|
.with_span(node.span),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
Err(error) => {
|
|
fact.error = Some(error.to_string());
|
|
diagnostics.push(
|
|
Diagnostic::warning(
|
|
code::UNKNOWN_FRONT_MATTER,
|
|
"front matter is not valid YAML; raw text was preserved",
|
|
)
|
|
.with_path(rel_path)
|
|
.with_span(node.span),
|
|
);
|
|
}
|
|
}
|
|
Some(fact)
|
|
}
|
|
|
|
/// Extract the YAML body between the opening and closing delimiter lines.
|
|
fn front_matter_yaml(literal: &str) -> Option<String> {
|
|
let normalised = literal.replace("\r\n", "\n");
|
|
let mut lines = normalised.split_inclusive('\n');
|
|
let first = lines.next()?;
|
|
if first.trim_end_matches('\n') != "---" {
|
|
return None;
|
|
}
|
|
let mut body = String::new();
|
|
let mut closed = false;
|
|
for line in lines {
|
|
let trimmed = line.trim_end_matches('\n');
|
|
if trimmed == "---" {
|
|
closed = true;
|
|
break;
|
|
}
|
|
body.push_str(line);
|
|
}
|
|
if !closed {
|
|
return None;
|
|
}
|
|
Some(body.trim_end_matches('\n').to_string())
|
|
}
|
|
|
|
fn yaml_to_json(
|
|
value: &serde_yaml::Value,
|
|
depth: usize,
|
|
nodes: &mut usize,
|
|
) -> Result<serde_json::Value, String> {
|
|
if depth > YAML_MAX_DEPTH {
|
|
return Err(format!(
|
|
"front matter nesting exceeds {YAML_MAX_DEPTH} levels"
|
|
));
|
|
}
|
|
*nodes += 1;
|
|
if *nodes > YAML_MAX_NODES {
|
|
return Err("front matter contains too many nodes".to_string());
|
|
}
|
|
use serde_yaml::Value as Yaml;
|
|
Ok(match value {
|
|
Yaml::Null => serde_json::Value::Null,
|
|
Yaml::Bool(value) => serde_json::Value::Bool(*value),
|
|
Yaml::Number(number) => {
|
|
if let Some(value) = number.as_i64() {
|
|
serde_json::Value::Number(value.into())
|
|
} else if let Some(value) = number.as_u64() {
|
|
serde_json::Value::Number(value.into())
|
|
} else if let Some(value) = number.as_f64() {
|
|
serde_json::Number::from_f64(value)
|
|
.map(serde_json::Value::Number)
|
|
.unwrap_or(serde_json::Value::Null)
|
|
} else {
|
|
serde_json::Value::String(number.to_string())
|
|
}
|
|
}
|
|
Yaml::String(value) => serde_json::Value::String(value.clone()),
|
|
Yaml::Sequence(items) => serde_json::Value::Array(
|
|
items
|
|
.iter()
|
|
.map(|item| yaml_to_json(item, depth + 1, nodes))
|
|
.collect::<Result<Vec<_>, _>>()?,
|
|
),
|
|
Yaml::Mapping(map) => {
|
|
let mut object = serde_json::Map::new();
|
|
for (key, value) in map {
|
|
let key = match key {
|
|
Yaml::String(key) => key.clone(),
|
|
other => {
|
|
return Err(format!(
|
|
"front matter mapping key {:?} is not a string",
|
|
other
|
|
))
|
|
}
|
|
};
|
|
object.insert(key, yaml_to_json(value, depth + 1, nodes)?);
|
|
}
|
|
serde_json::Value::Object(object)
|
|
}
|
|
Yaml::Tagged(tagged) => yaml_to_json(&tagged.value, depth + 1, nodes)?,
|
|
})
|
|
}
|
|
|
|
fn extract_references(ast: &AstNode, units: &[UnitFact]) -> Vec<ReferenceFact> {
|
|
let mut references = Vec::new();
|
|
for (url, span, title, is_image) in ast.links() {
|
|
let unit = innermost_unit(units, span);
|
|
references.push(ReferenceFact {
|
|
url: url.to_string(),
|
|
span,
|
|
unit,
|
|
is_image,
|
|
title: title.map(str::to_string),
|
|
analysis: None,
|
|
});
|
|
}
|
|
references
|
|
}
|
|
|
|
pub(crate) fn innermost_unit(units: &[UnitFact], span: Span) -> usize {
|
|
let mut best = 0usize;
|
|
let mut best_level = 0u8;
|
|
for (index, unit) in units.iter().enumerate() {
|
|
if index == 0 {
|
|
continue;
|
|
}
|
|
if unit.span.contains(span) && unit.level >= best_level {
|
|
best = index;
|
|
best_level = unit.level;
|
|
}
|
|
}
|
|
best
|
|
}
|
|
|
|
pub(crate) fn searchable_blocks(ast: &AstNode, units: &[UnitFact]) -> Vec<BlockFact> {
|
|
let mut blocks = Vec::new();
|
|
for child in &ast.children {
|
|
if child.kind == AstKind::FrontMatter || child.kind == AstKind::Heading {
|
|
continue;
|
|
}
|
|
collect_blocks(child, units, &mut blocks, 0);
|
|
}
|
|
blocks.sort_by(|a, b| {
|
|
a.span
|
|
.start
|
|
.cmp(&b.span.start)
|
|
.then(a.span.end.cmp(&b.span.end))
|
|
});
|
|
blocks
|
|
}
|
|
|
|
fn collect_blocks(node: &AstNode, units: &[UnitFact], blocks: &mut Vec<BlockFact>, depth: usize) {
|
|
if depth > super::MAX_AST_DEPTH {
|
|
return;
|
|
}
|
|
let unit = innermost_unit(units, node.span);
|
|
match node.kind {
|
|
AstKind::Paragraph | AstKind::HtmlBlock => {
|
|
let mut block = block_shell(node, unit, BlockKind::Paragraph);
|
|
if node.kind == AstKind::HtmlBlock {
|
|
block.kind = BlockKind::Html;
|
|
}
|
|
fill_inline_fields(node, &mut block);
|
|
blocks.push(block);
|
|
}
|
|
AstKind::MathBlock => {
|
|
let mut block = block_shell(node, unit, BlockKind::Formula);
|
|
block.formula = node.literal.clone().unwrap_or_default();
|
|
blocks.push(block);
|
|
}
|
|
AstKind::CodeBlock => {
|
|
let mut block = block_shell(node, unit, BlockKind::Code);
|
|
let literal = node.literal.clone().unwrap_or_default();
|
|
block.text = literal.clone();
|
|
block.code = literal;
|
|
blocks.push(block);
|
|
}
|
|
AstKind::Table => {
|
|
let mut block = block_shell(node, unit, BlockKind::Table);
|
|
block.table = table_text(node);
|
|
block.text = block.table.clone();
|
|
block.links = links_text(node);
|
|
blocks.push(block);
|
|
}
|
|
AstKind::List | AstKind::Item | AstKind::BlockQuote | AstKind::Other => {
|
|
let before = blocks.len();
|
|
for child in &node.children {
|
|
collect_blocks(child, units, blocks, depth + 1);
|
|
}
|
|
if blocks.len() == before {
|
|
// Tight lists and similar containers can hold inline content
|
|
// without a paragraph block. Preserve it as one readable block.
|
|
let mut block = block_shell(node, unit, BlockKind::List);
|
|
if node.kind == AstKind::BlockQuote {
|
|
block.kind = BlockKind::Quote;
|
|
}
|
|
fill_inline_fields(node, &mut block);
|
|
if !block.text.is_empty() || !block.formula.is_empty() {
|
|
blocks.push(block);
|
|
}
|
|
}
|
|
}
|
|
_ => {
|
|
for child in &node.children {
|
|
collect_blocks(child, units, blocks, depth + 1);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn block_shell(node: &AstNode, unit: usize, kind: BlockKind) -> BlockFact {
|
|
BlockFact {
|
|
kind,
|
|
span: node.span,
|
|
unit,
|
|
text: String::new(),
|
|
formula: String::new(),
|
|
table: String::new(),
|
|
links: String::new(),
|
|
code: String::new(),
|
|
}
|
|
}
|
|
|
|
fn fill_inline_fields(node: &AstNode, block: &mut BlockFact) {
|
|
node.inline_text(&mut block.text);
|
|
collect_formula(node, &mut block.formula);
|
|
collect_link_text(node, &mut block.links);
|
|
}
|
|
|
|
fn collect_formula(node: &AstNode, out: &mut String) {
|
|
if matches!(node.kind, AstKind::Math) {
|
|
if let Some(literal) = &node.literal {
|
|
push_line(out, literal);
|
|
}
|
|
}
|
|
for child in &node.children {
|
|
collect_formula(child, out);
|
|
}
|
|
}
|
|
|
|
fn collect_link_text(node: &AstNode, out: &mut String) {
|
|
if matches!(node.kind, AstKind::Link | AstKind::Image) {
|
|
if let Some(url) = &node.url {
|
|
let mut text = String::new();
|
|
node.inline_text(&mut text);
|
|
push_line(out, &format!("{text} {url}"));
|
|
}
|
|
}
|
|
for child in &node.children {
|
|
collect_link_text(child, out);
|
|
}
|
|
}
|
|
|
|
fn links_text(node: &AstNode) -> String {
|
|
let mut out = String::new();
|
|
for (url, _, _, _) in node.links() {
|
|
push_line(&mut out, url);
|
|
}
|
|
out
|
|
}
|
|
|
|
fn table_text(table: &AstNode) -> String {
|
|
let mut out = String::new();
|
|
for row in &table.children {
|
|
let mut cells = Vec::new();
|
|
for cell in &row.children {
|
|
let mut text = String::new();
|
|
cell.inline_text(&mut text);
|
|
cells.push(text.trim().to_string());
|
|
}
|
|
push_line(&mut out, &cells.join(" | "));
|
|
}
|
|
out
|
|
}
|
|
|
|
fn push_line(out: &mut String, value: &str) {
|
|
if !out.is_empty() {
|
|
out.push('\n');
|
|
}
|
|
out.push_str(value);
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::document::discovery::{discover, resolve_scope};
|
|
use std::io::Write;
|
|
|
|
fn plain_facts(content: &str) -> DocumentFacts {
|
|
let temp = tempfile::tempdir().unwrap();
|
|
let path = temp.path().join("doc.md");
|
|
let mut file = std::fs::File::create(&path).unwrap();
|
|
file.write_all(content.as_bytes()).unwrap();
|
|
let scope = resolve_scope(&path, &[]).unwrap();
|
|
let snapshot = discover(&scope).unwrap();
|
|
parse_plain(&snapshot.files[0])
|
|
}
|
|
|
|
#[test]
|
|
fn heading_units_have_paths_parents_and_complete_spans() {
|
|
let facts =
|
|
plain_facts("# 力学\n\n## 牛顿\n\ntext\n\n### 子节\n\nmore\n\n## 计算力\n\nz\n");
|
|
let names: Vec<_> = facts.units.iter().map(|u| u.name.as_str()).collect();
|
|
assert_eq!(names, vec!["", "力学", "牛顿", "子节", "计算力"]);
|
|
assert_eq!(facts.units[2].path, vec!["力学", "牛顿"]);
|
|
assert_eq!(facts.units[2].parent, Some(1));
|
|
assert_eq!(facts.units[3].parent, Some(2));
|
|
assert_eq!(facts.units[4].parent, Some(1));
|
|
assert!(facts.units[2].span.contains(facts.units[3].span));
|
|
assert!(facts.units[2].span.end <= facts.units[4].span.start);
|
|
assert_eq!(facts.document_title, "力学");
|
|
}
|
|
|
|
#[test]
|
|
fn links_keep_raw_urls_and_exact_spans() {
|
|
let content = "# t\n\n见 [牛顿](theory.md#牛顿) 与 。\n";
|
|
let facts = plain_facts(content);
|
|
assert_eq!(facts.references.len(), 2);
|
|
assert_eq!(facts.references[0].url, "theory.md#牛顿");
|
|
assert!(!facts.references[0].is_image);
|
|
assert_eq!(facts.references[1].url, "img/p.png");
|
|
assert!(facts.references[1].is_image);
|
|
assert_eq!(
|
|
facts.references[0].span.slice(content.as_bytes()).unwrap(),
|
|
"[牛顿](theory.md#牛顿)"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn blocks_capture_text_formula_table_and_code() {
|
|
let content = "# t\n\n段落 $E=mc^2$ 与 [链接](a.md)。\n\n| a | b |\n| - | - |\n| 1 | 2 |\n\n```rust\nlet x = 1;\n```\n\n$$\nF = ma\n$$\n";
|
|
let facts = plain_facts(content);
|
|
let kinds: Vec<_> = facts.blocks.iter().map(|b| b.kind.clone()).collect();
|
|
assert!(kinds.contains(&BlockKind::Paragraph));
|
|
assert!(kinds.contains(&BlockKind::Table));
|
|
assert!(kinds.contains(&BlockKind::Code));
|
|
assert!(kinds.contains(&BlockKind::Formula));
|
|
let paragraph = facts
|
|
.blocks
|
|
.iter()
|
|
.find(|b| b.kind == BlockKind::Paragraph)
|
|
.unwrap();
|
|
assert!(paragraph.text.contains("段落"));
|
|
assert!(paragraph.formula.contains("E=mc^2"));
|
|
assert!(paragraph.links.contains("a.md"));
|
|
let table = facts
|
|
.blocks
|
|
.iter()
|
|
.find(|b| b.kind == BlockKind::Table)
|
|
.unwrap();
|
|
assert!(table.table.contains("a | b"));
|
|
assert!(table.table.contains("1 | 2"));
|
|
let code = facts
|
|
.blocks
|
|
.iter()
|
|
.find(|b| b.kind == BlockKind::Code)
|
|
.unwrap();
|
|
assert!(code.code.contains("let x = 1;"));
|
|
let formula = facts
|
|
.blocks
|
|
.iter()
|
|
.find(|b| b.kind == BlockKind::Formula)
|
|
.unwrap();
|
|
assert!(formula.formula.contains("F = ma"));
|
|
}
|
|
|
|
#[test]
|
|
fn byte_spans_are_exact_for_bom_crlf_and_cjk() {
|
|
let content = "\u{feff}# 标题\r\n\r\n中文 😀\r\n";
|
|
let facts = plain_facts(content);
|
|
let heading = facts
|
|
.units
|
|
.iter()
|
|
.find(|u| u.kind == UnitKind::Namespace)
|
|
.unwrap();
|
|
let heading_span = heading.heading_span.unwrap();
|
|
let slice = heading_span.slice(content.as_bytes()).unwrap();
|
|
assert!(slice.starts_with("# 标题"));
|
|
// BOM must be preserved, never stripped.
|
|
assert_eq!(&content.as_bytes()[..3], &[0xEF, 0xBB, 0xBF]);
|
|
assert_eq!(facts.units[0].span, Span::new(0, content.len() as u64));
|
|
assert_eq!(heading.span.start, heading_span.start);
|
|
assert_eq!(heading.span.end, content.len() as u64);
|
|
}
|
|
|
|
#[test]
|
|
fn anchors_are_deterministic_and_duplicates_are_numbered() {
|
|
let facts = plain_facts("# A\n\n## Same Name\n\nx\n\n## Same Name\n\ny\n");
|
|
let anchors: Vec<_> = facts.anchors.iter().map(|a| a.anchor.as_str()).collect();
|
|
assert_eq!(anchors, vec!["a", "same-name", "same-name-1"]);
|
|
assert_eq!(slugify(" Hello, 世界! "), "hello-世界");
|
|
}
|
|
|
|
#[test]
|
|
fn front_matter_is_parsed_but_unknown_fields_are_preserved() {
|
|
let content = "---\ntype: Theory\ntitle: 经典力学\ntags: [physics, mechanics]\ncustom: {a: 1}\n---\n\n# 经典力学\n";
|
|
let facts = plain_facts(content);
|
|
let front = facts.front_matter.as_ref().unwrap();
|
|
assert!(front.error.is_none());
|
|
let value = front.value.as_ref().unwrap();
|
|
assert_eq!(value["type"], "Theory");
|
|
assert_eq!(value["tags"][1], "mechanics");
|
|
assert_eq!(value["custom"]["a"], 1);
|
|
}
|
|
|
|
#[test]
|
|
fn front_matter_aliases_are_rejected_without_losing_raw_text() {
|
|
let content = "---\na: &x 1\nb: *x\n---\n\n# t\n";
|
|
let facts = plain_facts(content);
|
|
let front = facts.front_matter.as_ref().unwrap();
|
|
assert!(front.error.is_some());
|
|
assert!(front.value.is_none());
|
|
assert!(front.literal.contains("&x"));
|
|
assert!(facts
|
|
.diagnostics
|
|
.iter()
|
|
.any(|d| d.code == code::UNKNOWN_FRONT_MATTER));
|
|
}
|
|
|
|
#[test]
|
|
fn exec_text_in_plain_markdown_has_no_semantics() {
|
|
let facts = plain_facts("# t\n\n## @exec 计算力\n\n`params(m, a)`\n\n`return m * a`\n");
|
|
assert!(facts.functions.is_empty());
|
|
assert!(facts
|
|
.units
|
|
.iter()
|
|
.all(|unit| unit.kind != UnitKind::Function));
|
|
assert!(facts.units.iter().any(|unit| unit.name == "@exec 计算力"));
|
|
}
|
|
|
|
#[test]
|
|
fn tight_list_content_is_not_lost() {
|
|
let facts = plain_facts("# t\n\n- a\n- b\n");
|
|
let text: String = facts.blocks.iter().map(|b| b.text.clone()).collect();
|
|
assert!(text.contains('a'));
|
|
assert!(text.contains('b'));
|
|
}
|
|
|
|
#[test]
|
|
fn duplicate_heading_paths_get_distinct_units() {
|
|
let facts = plain_facts("# t\n\n## dup\n\nx\n\n## dup\n\ny\n");
|
|
let dups: Vec<_> = facts.units.iter().filter(|u| u.name == "dup").collect();
|
|
assert_eq!(dups.len(), 2);
|
|
assert_eq!(dups[0].path, dups[1].path);
|
|
assert_ne!(dups[0].span.start, dups[1].span.start);
|
|
}
|
|
}
|