feat(document): normalized AST and plain Markdown projection
- add the closed normalized AST shape shared by the plain projection and upstream Analysis, with required-attribute, UTF-8 span and depth validation - parse plain .md with pinned comrak 1.0.0 fixed options (GFM tables, footnotes, task lists, strikethrough, autolink, dollar math, front matter) - convert parser line/column positions to exact half-open byte spans and keep BOM/CRLF/CJK byte identity - build heading units (complete section spans, parents, occurrence-indexed duplicate paths), fixed-rule anchors, raw link facts and searchable blocks - parse front matter as bounded YAML to JSON with alias/depth/size rejection while preserving the raw literal; plain @exec text stays inert - add shared DocumentFacts vocabulary with serde caching shape
This commit is contained in:
1 parent
f2f3b38eca
commit
682717a610
5 files changed
+1648
-4
No files matched your search
+1
-1
@@ -4,7 +4,7 @@
|
||||
//! Argument parsing owns usage errors; rendering owns stdout/stderr so that the
|
||||
//! compiler and query layers never print.
|
||||
|
||||
use crate::error::{KnowledgeError, EXIT_INPUT, EXIT_OK, EXIT_USAGE};
|
||||
use crate::error::{KnowledgeError, EXIT_INPUT, EXIT_OK};
|
||||
use crate::model::NodeKind;
|
||||
use clap::{Args, Parser, Subcommand, ValueEnum};
|
||||
use std::fmt::Write as _;
|
||||
|
||||
+2
-1
@@ -167,7 +167,8 @@ impl fmt::Display for Diagnostic {
|
||||
}
|
||||
|
||||
/// A deterministic diagnostic collection.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct DiagnosticSet {
|
||||
items: Vec<Diagnostic>,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
//! Normalised document AST projection.
|
||||
//!
|
||||
//! One shape is used for both input profiles: the core CLI's public
|
||||
//! `modules[].document` (Marqdo) and this tool's own projection of plain
|
||||
//! CommonMark/GFM. The shape is closed: unknown node kinds, unknown attributes
|
||||
//! and missing required attributes are rejected instead of being silently
|
||||
//! dropped. Spans are half-open UTF-8 byte offsets into the document's exact
|
||||
//! source.
|
||||
|
||||
use crate::model::Span;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Node kinds from the public Markdown profile. `other` preserves unmodelled
|
||||
/// parser nodes inertly with their `tag`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AstKind {
|
||||
Document,
|
||||
FrontMatter,
|
||||
BlockQuote,
|
||||
List,
|
||||
Item,
|
||||
Heading,
|
||||
Paragraph,
|
||||
Text,
|
||||
Strong,
|
||||
Emph,
|
||||
Strikethrough,
|
||||
Code,
|
||||
CodeBlock,
|
||||
Math,
|
||||
MathBlock,
|
||||
Link,
|
||||
Image,
|
||||
Table,
|
||||
TableRow,
|
||||
TableCell,
|
||||
ThematicBreak,
|
||||
SoftBreak,
|
||||
LineBreak,
|
||||
HtmlBlock,
|
||||
HtmlInline,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl AstKind {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
AstKind::Document => "document",
|
||||
AstKind::FrontMatter => "front_matter",
|
||||
AstKind::BlockQuote => "block_quote",
|
||||
AstKind::List => "list",
|
||||
AstKind::Item => "item",
|
||||
AstKind::Heading => "heading",
|
||||
AstKind::Paragraph => "paragraph",
|
||||
AstKind::Text => "text",
|
||||
AstKind::Strong => "strong",
|
||||
AstKind::Emph => "emph",
|
||||
AstKind::Strikethrough => "strikethrough",
|
||||
AstKind::Code => "code",
|
||||
AstKind::CodeBlock => "code_block",
|
||||
AstKind::Math => "math",
|
||||
AstKind::MathBlock => "math_block",
|
||||
AstKind::Link => "link",
|
||||
AstKind::Image => "image",
|
||||
AstKind::Table => "table",
|
||||
AstKind::TableRow => "table_row",
|
||||
AstKind::TableCell => "table_cell",
|
||||
AstKind::ThematicBreak => "thematic_break",
|
||||
AstKind::SoftBreak => "soft_break",
|
||||
AstKind::LineBreak => "line_break",
|
||||
AstKind::HtmlBlock => "html_block",
|
||||
AstKind::HtmlInline => "html_inline",
|
||||
AstKind::Other => "other",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_block(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
AstKind::BlockQuote
|
||||
| AstKind::List
|
||||
| AstKind::Item
|
||||
| AstKind::Heading
|
||||
| AstKind::Paragraph
|
||||
| AstKind::CodeBlock
|
||||
| AstKind::MathBlock
|
||||
| AstKind::Table
|
||||
| AstKind::TableRow
|
||||
| AstKind::TableCell
|
||||
| AstKind::ThematicBreak
|
||||
| AstKind::HtmlBlock
|
||||
| AstKind::FrontMatter
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Alignment {
|
||||
None,
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
}
|
||||
|
||||
impl Alignment {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Alignment::None => "none",
|
||||
Alignment::Left => "left",
|
||||
Alignment::Center => "center",
|
||||
Alignment::Right => "right",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One normalised AST node.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AstNode {
|
||||
pub kind: AstKind,
|
||||
pub span: Span,
|
||||
pub children: Vec<AstNode>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub literal: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tag: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub level: Option<u8>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub setext: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub ordered: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub start: Option<u64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tight: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub task: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub ticks: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub fenced: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub info: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub display: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub title: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub alignments: Option<Vec<Alignment>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub header: Option<bool>,
|
||||
}
|
||||
|
||||
impl AstNode {
|
||||
pub fn new(kind: AstKind, span: Span) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
span,
|
||||
children: Vec::new(),
|
||||
literal: None,
|
||||
tag: None,
|
||||
level: None,
|
||||
setext: None,
|
||||
ordered: None,
|
||||
start: None,
|
||||
tight: None,
|
||||
task: None,
|
||||
ticks: None,
|
||||
fenced: None,
|
||||
info: None,
|
||||
display: None,
|
||||
url: None,
|
||||
title: None,
|
||||
alignments: None,
|
||||
header: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_literal(mut self, literal: impl Into<String>) -> Self {
|
||||
self.literal = Some(literal.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_children(mut self, children: Vec<AstNode>) -> Self {
|
||||
self.children = children;
|
||||
self
|
||||
}
|
||||
|
||||
/// Concatenate inert inline literals (text, inline code, math, links text)
|
||||
/// in document order. Never includes URLs or generated text.
|
||||
pub fn inline_text(&self, out: &mut String) {
|
||||
match self.kind {
|
||||
AstKind::Text | AstKind::Code | AstKind::Math | AstKind::HtmlInline => {
|
||||
if let Some(literal) = &self.literal {
|
||||
out.push_str(literal);
|
||||
}
|
||||
}
|
||||
AstKind::SoftBreak | AstKind::LineBreak => out.push('\n'),
|
||||
_ => {}
|
||||
}
|
||||
for child in &self.children {
|
||||
child.inline_text(out);
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalised heading name: NFC, collapsed Unicode whitespace, trimmed.
|
||||
pub fn normalized_name(&self) -> String {
|
||||
let mut text = String::new();
|
||||
self.inline_text(&mut text);
|
||||
normalize_heading_name(&text)
|
||||
}
|
||||
|
||||
/// Validate structural invariants that JSON Schema cannot express: span
|
||||
/// bounds, UTF-8 boundaries, depth and the attributes required per kind.
|
||||
pub fn validate(&self, source: &[u8], max_depth: usize) -> Result<(), String> {
|
||||
self.validate_inner(source, 0, max_depth)
|
||||
}
|
||||
|
||||
fn validate_inner(&self, source: &[u8], depth: usize, max_depth: usize) -> Result<(), String> {
|
||||
if depth > max_depth {
|
||||
return Err(format!(
|
||||
"document AST depth exceeds the {max_depth} level budget"
|
||||
));
|
||||
}
|
||||
if self.span.start > self.span.end || self.span.end > source.len() as u64 {
|
||||
return Err(format!(
|
||||
"{} span {} is outside the {}-byte source",
|
||||
self.kind.as_str(),
|
||||
self.span,
|
||||
source.len()
|
||||
));
|
||||
}
|
||||
if !self.span.on_utf8_boundaries(source) {
|
||||
return Err(format!(
|
||||
"{} span {} does not lie on UTF-8 boundaries",
|
||||
self.kind.as_str(),
|
||||
self.span
|
||||
));
|
||||
}
|
||||
self.validate_attributes()?;
|
||||
for child in &self.children {
|
||||
child.validate_inner(source, depth + 1, max_depth)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_attributes(&self) -> Result<(), String> {
|
||||
let kind = self.kind.as_str();
|
||||
let require = |present: bool, name: &str| {
|
||||
if present {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"{kind} node is missing required attribute `{name}`"
|
||||
))
|
||||
}
|
||||
};
|
||||
match self.kind {
|
||||
AstKind::FrontMatter
|
||||
| AstKind::Text
|
||||
| AstKind::MathBlock
|
||||
| AstKind::HtmlBlock
|
||||
| AstKind::HtmlInline => require(self.literal.is_some(), "literal"),
|
||||
AstKind::Code => {
|
||||
require(self.literal.is_some(), "literal")?;
|
||||
require(self.ticks.is_some(), "ticks")
|
||||
}
|
||||
AstKind::CodeBlock => {
|
||||
require(self.fenced.is_some(), "fenced")?;
|
||||
require(self.literal.is_some(), "literal")?;
|
||||
if self.fenced == Some(true) {
|
||||
require(self.info.is_some(), "info")
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
AstKind::Math => {
|
||||
require(self.display.is_some(), "display")?;
|
||||
require(self.literal.is_some(), "literal")
|
||||
}
|
||||
AstKind::Heading => {
|
||||
match self.level {
|
||||
Some(1..=6) => {}
|
||||
_ => return Err(format!("{kind} node has invalid level {:?}", self.level)),
|
||||
}
|
||||
require(self.setext.is_some(), "setext")
|
||||
}
|
||||
AstKind::Link | AstKind::Image => {
|
||||
require(self.url.is_some(), "url")?;
|
||||
require(self.title.is_some(), "title")
|
||||
}
|
||||
AstKind::List => {
|
||||
require(self.ordered.is_some(), "ordered")?;
|
||||
require(self.tight.is_some(), "tight")?;
|
||||
if self.ordered == Some(true) && self.start.is_none() {
|
||||
return Err(format!("{kind} node is missing required attribute `start`"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
AstKind::Table => require(self.alignments.is_some(), "alignments"),
|
||||
AstKind::TableRow => require(self.header.is_some(), "header"),
|
||||
AstKind::Other => require(self.tag.is_some(), "tag"),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Depth-first walk with the node's depth.
|
||||
pub fn walk<'a>(&'a self, depth: usize, visit: &mut dyn FnMut(&'a AstNode, usize)) {
|
||||
visit(self, depth);
|
||||
for child in &self.children {
|
||||
child.walk(depth + 1, visit);
|
||||
}
|
||||
}
|
||||
|
||||
/// Find every link/image node in document order:
|
||||
/// (url, span, title, is_image).
|
||||
pub fn links(&self) -> Vec<(&str, Span, Option<&str>, bool)> {
|
||||
let mut out = Vec::new();
|
||||
self.collect_links(&mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn collect_links<'a>(&'a self, out: &mut Vec<(&'a str, Span, Option<&'a str>, bool)>) {
|
||||
if matches!(self.kind, AstKind::Link | AstKind::Image) {
|
||||
if let Some(url) = &self.url {
|
||||
out.push((
|
||||
url.as_str(),
|
||||
self.span,
|
||||
self.title.as_deref(),
|
||||
self.kind == AstKind::Image,
|
||||
));
|
||||
}
|
||||
}
|
||||
for child in &self.children {
|
||||
child.collect_links(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// NFC, collapse all Unicode whitespace runs to one space, trim.
|
||||
pub fn normalize_heading_name(text: &str) -> String {
|
||||
let nfc: String = {
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
text.nfc().collect()
|
||||
};
|
||||
let mut out = String::with_capacity(nfc.len());
|
||||
let mut pending_space = false;
|
||||
for ch in nfc.chars() {
|
||||
if ch.is_whitespace() {
|
||||
pending_space = true;
|
||||
continue;
|
||||
}
|
||||
if pending_space && !out.is_empty() {
|
||||
out.push(' ');
|
||||
}
|
||||
pending_space = false;
|
||||
out.push(ch);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::Span;
|
||||
|
||||
fn text(value: &str, span: Span) -> AstNode {
|
||||
AstNode::new(AstKind::Text, span).with_literal(value)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heading_normalisation_is_nfc_and_collapses_whitespace() {
|
||||
assert_eq!(
|
||||
normalize_heading_name(" 牛顿\t 第二\n定律 "),
|
||||
"牛顿 第二 定律"
|
||||
);
|
||||
let decomposed = "Cafe\u{0301}";
|
||||
assert_eq!(normalize_heading_name(decomposed), "Café");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_text_never_uses_urls_or_generated_text() {
|
||||
let mut link = AstNode::new(AstKind::Link, Span::new(0, 10));
|
||||
link.url = Some("https://example.com".into());
|
||||
link.title = Some("title".into());
|
||||
link.children = vec![text("链接", Span::new(1, 4))];
|
||||
let mut out = String::new();
|
||||
link.inline_text(&mut out);
|
||||
assert_eq!(out, "链接");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ast_validation_requires_profile_attributes() {
|
||||
let source = b"# heading\n";
|
||||
let mut heading = AstNode::new(AstKind::Heading, Span::new(0, 9));
|
||||
assert!(heading.validate(source, 256).is_err());
|
||||
heading.level = Some(1);
|
||||
heading.setext = Some(false);
|
||||
assert!(heading.validate(source, 256).is_ok());
|
||||
|
||||
let bad_span = AstNode::new(AstKind::Paragraph, Span::new(0, 100));
|
||||
assert!(bad_span.validate(source, 256).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_budget_is_enforced() {
|
||||
let mut node = AstNode::new(AstKind::Document, Span::new(0, 1));
|
||||
let mut current = &mut node;
|
||||
for _ in 0..8 {
|
||||
let child = AstNode::new(AstKind::Paragraph, Span::new(0, 1));
|
||||
current.children.push(child);
|
||||
current = current.children.last_mut().unwrap();
|
||||
}
|
||||
assert!(node.validate(b"x", 4).is_err());
|
||||
assert!(node.validate(b"x", 8).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_node_kinds_are_rejected_by_deserialization() {
|
||||
let json = r#"{"kind":"magic","span":{"start":0,"end":0},"children":[]}"#;
|
||||
assert!(serde_json::from_str::<AstNode>(json).is_err());
|
||||
let json =
|
||||
r#"{"kind":"text","span":{"start":0,"end":1},"children":[],"literal":"a","extra":1}"#;
|
||||
assert!(serde_json::from_str::<AstNode>(json).is_err());
|
||||
}
|
||||
}
|
||||
+959
-2
@@ -1,4 +1,961 @@
|
||||
//! Plain CommonMark/GFM projection for `.md` documents.
|
||||
//!
|
||||
//! Implemented in the document milestone. Plain Markdown never gains
|
||||
//! executable Marqdo semantics from `@exec` text.
|
||||
//! 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 = extract_front_matter(&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 = extract_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 index + 1..units.len() {
|
||||
if units[later].level <= level {
|
||||
end = units[later]
|
||||
.heading_span
|
||||
.map(|span| span.start)
|
||||
.unwrap_or(units[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()
|
||||
}
|
||||
|
||||
fn extract_front_matter(
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
fn extract_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);
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,14 @@
|
||||
//! source snapshot it belongs to.
|
||||
|
||||
pub mod analysis;
|
||||
pub mod ast;
|
||||
pub mod discovery;
|
||||
pub mod markdown;
|
||||
pub mod okf;
|
||||
|
||||
use crate::diagnostic::DiagnosticSet;
|
||||
use crate::model::{DocumentFormat, Span};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Hard input budgets. They are part of the safety contract: hard overruns
|
||||
@@ -312,10 +314,263 @@ impl SourceSnapshot {
|
||||
}
|
||||
}
|
||||
|
||||
/// Unit kinds as projected into graph nodes. The document root maps to the
|
||||
/// document node; an Exec H2 and its function are one node.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum UnitKind {
|
||||
Root,
|
||||
Namespace,
|
||||
Knowledge,
|
||||
Function,
|
||||
Section,
|
||||
}
|
||||
|
||||
impl UnitKind {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
UnitKind::Root => "root",
|
||||
UnitKind::Namespace => "namespace",
|
||||
UnitKind::Knowledge => "knowledge",
|
||||
UnitKind::Function => "function",
|
||||
UnitKind::Section => "section",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One heading scope. `path` is authoritative; ids are never split.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UnitFact {
|
||||
/// Canonical structured heading path; `[]` for the root.
|
||||
pub path: Vec<String>,
|
||||
pub kind: UnitKind,
|
||||
pub name: String,
|
||||
pub level: u8,
|
||||
/// Complete section range (root: whole source).
|
||||
pub span: Span,
|
||||
pub heading_span: Option<Span>,
|
||||
/// Index into the same unit vector.
|
||||
pub parent: Option<usize>,
|
||||
/// Canonical upstream FunctionId for an Exec section.
|
||||
pub function_id: Option<String>,
|
||||
/// Upstream canonical UnitId when the fact came from Analysis.
|
||||
pub unit_id: Option<String>,
|
||||
/// Effective mode: `knowledge` or `exec`.
|
||||
pub mode: String,
|
||||
/// Deterministic occurrence index for duplicate canonical paths (0 for
|
||||
/// the first occurrence). Together with `path` it makes the node key
|
||||
/// unique without changing the authoritative path.
|
||||
pub occurrence: u32,
|
||||
}
|
||||
|
||||
/// Navigation anchor (unique by construction).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AnchorFact {
|
||||
pub anchor: String,
|
||||
pub unit: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FunctionFact {
|
||||
pub function_id: String,
|
||||
pub unit: usize,
|
||||
pub local_name: String,
|
||||
pub namespace: Option<String>,
|
||||
pub span: Span,
|
||||
pub heading_span: Span,
|
||||
pub signature: serde_json::Value,
|
||||
pub effects: Vec<String>,
|
||||
pub body: serde_json::Value,
|
||||
}
|
||||
|
||||
/// Upstream resolution record for a Marqdo Markdown link. Knowledge must not
|
||||
/// re-bind a resolved target and must not turn `not_loaded` into `missing`.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AnalysisReferenceFact {
|
||||
pub state: crate::model::EdgeState,
|
||||
pub target_kind: Option<String>,
|
||||
pub target_module: Option<String>,
|
||||
pub target_unit: Option<String>,
|
||||
pub candidate_package_instance_id: Option<String>,
|
||||
pub candidate_path: Option<String>,
|
||||
pub fragment: Option<String>,
|
||||
pub candidates: Vec<String>,
|
||||
}
|
||||
|
||||
/// One Markdown link/image occurrence.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ReferenceFact {
|
||||
/// Raw URL exactly as written (never percent-decoded).
|
||||
pub url: String,
|
||||
pub span: Span,
|
||||
/// Innermost unit containing the occurrence.
|
||||
pub unit: usize,
|
||||
pub is_image: bool,
|
||||
pub title: Option<String>,
|
||||
/// Present only for `.mq.md` facts that came from Analysis.
|
||||
pub analysis: Option<AnalysisReferenceFact>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ImportFact {
|
||||
pub alias: String,
|
||||
pub target: String,
|
||||
pub span: Span,
|
||||
pub unit: usize,
|
||||
/// Canonical resolved module id, or `None` for a diagnostic import.
|
||||
pub resolved: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CallFact {
|
||||
/// Canonical owning FunctionId.
|
||||
pub function_id: String,
|
||||
pub span: Span,
|
||||
pub callee: serde_json::Value,
|
||||
/// `function`, `builtin`, `plugin` or `unresolved`.
|
||||
pub state: String,
|
||||
pub target: Option<String>,
|
||||
pub target_kind: Option<String>,
|
||||
pub target_owner: Option<serde_json::Value>,
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ResourceFact {
|
||||
pub id: String,
|
||||
pub kind: String,
|
||||
pub span: Span,
|
||||
pub content_digest: String,
|
||||
pub language: Option<String>,
|
||||
pub display: Option<bool>,
|
||||
/// Innermost unit containing the resource.
|
||||
pub unit: usize,
|
||||
}
|
||||
|
||||
/// One extractable content block used to build search units.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum BlockKind {
|
||||
Paragraph,
|
||||
List,
|
||||
Quote,
|
||||
Table,
|
||||
Formula,
|
||||
Code,
|
||||
Html,
|
||||
Other,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct BlockFact {
|
||||
pub kind: BlockKind,
|
||||
pub span: Span,
|
||||
/// Innermost unit owning the block.
|
||||
pub unit: usize,
|
||||
pub text: String,
|
||||
pub formula: String,
|
||||
pub table: String,
|
||||
pub links: String,
|
||||
pub code: String,
|
||||
}
|
||||
|
||||
/// Bounded front-matter facts. YAML is parsed only to a JSON value with strict
|
||||
/// size/depth/alias limits; the raw literal is always preserved.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FrontMatterFact {
|
||||
pub span: Span,
|
||||
pub literal: String,
|
||||
pub value: Option<serde_json::Value>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Analysis context identity of one `.mq.md` module.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AnalysisFacts {
|
||||
pub module_id: String,
|
||||
pub package_instance_id: String,
|
||||
pub context_id: String,
|
||||
pub entry_module_id: String,
|
||||
pub root_id: String,
|
||||
pub identity_kind: String,
|
||||
pub manifest_digest: String,
|
||||
pub lock_digest: String,
|
||||
pub stdlib_digest: Option<String>,
|
||||
pub producer_version: String,
|
||||
/// SHA-256 of the exact emitted Analysis bytes.
|
||||
pub analysis_digest: String,
|
||||
pub extensions: serde_json::Value,
|
||||
}
|
||||
|
||||
/// Everything one document contributes to the graph, before linking.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct DocumentFacts {
|
||||
pub rel_path: String,
|
||||
pub format: DocumentFormat,
|
||||
pub source_digest: String,
|
||||
pub document_title: String,
|
||||
pub ast: crate::document::ast::AstNode,
|
||||
pub units: Vec<UnitFact>,
|
||||
pub anchors: Vec<AnchorFact>,
|
||||
pub functions: Vec<FunctionFact>,
|
||||
pub imports: Vec<ImportFact>,
|
||||
pub references: Vec<ReferenceFact>,
|
||||
pub calls: Vec<CallFact>,
|
||||
pub resources: Vec<ResourceFact>,
|
||||
pub blocks: Vec<BlockFact>,
|
||||
pub front_matter: Option<FrontMatterFact>,
|
||||
pub analysis: Option<AnalysisFacts>,
|
||||
pub diagnostics: DiagnosticSet,
|
||||
}
|
||||
|
||||
impl DocumentFacts {
|
||||
/// Innermost unit whose complete span contains `span`. The root unit is the
|
||||
/// fallback and always spans the whole source.
|
||||
pub fn innermost_unit(&self, span: Span) -> usize {
|
||||
let mut best = 0usize;
|
||||
let mut best_level = 0u8;
|
||||
for (index, unit) in self.units.iter().enumerate() {
|
||||
if unit.span.contains(span) && (index == 0 || unit.level >= best_level) {
|
||||
if index == 0 || unit.level >= best_level {
|
||||
best = index;
|
||||
best_level = unit.level;
|
||||
}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Node path for a unit: the document root is the empty path.
|
||||
pub fn unit_path(&self, unit: usize) -> Vec<String> {
|
||||
self.units
|
||||
.get(unit)
|
||||
.map(|unit| unit.path.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn function_by_id(&self, function_id: &str) -> Option<&FunctionFact> {
|
||||
self.functions
|
||||
.iter()
|
||||
.find(|function| function.function_id == function_id)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // consumed by the incremental compiler milestone
|
||||
pub(crate) fn facts_cache_version() -> u32 {
|
||||
// Bump when the serialised DocumentFacts shape or extraction semantics
|
||||
// change. The cache is derived data; a mismatch forces re-extraction.
|
||||
1
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn facts_cache_version_is_positive() {
|
||||
assert!(facts_cache_version() >= 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_database_path_is_fixed_below_root() {
|
||||
let root = PathBuf::from("/tmp/example");
|
||||
|
||||
Reference in new issue
Block a user