feat: adopt marqdo 3.0.0-rc.4 public analysis boundary

This commit is contained in:
cflmy committed 2026-11-25 21:18:35 +08:00
1 parent 769550b14b
commit fe18df6c4b
74 files changed
+7618 -5368

No files matched your search

+1727 -118
View File
File diff suppressed because it is too large. Load diff
+190 -137
View File
@@ -1,18 +1,14 @@
use std::collections::HashMap;
use serde::Deserialize;
use serde_json::Value;
use crate::error::{LintError, Result};
use super::{SourceSnapshot, Span};
use super::{AnalysisFunction, AnalysisUnit, HeadingMode, SourceSnapshot, Span, UnitKind};
pub type NodeId = usize;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HeadingMode {
Knowledge,
Exec,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CarrierKind {
Code,
@@ -39,6 +35,7 @@ pub struct MarkdownNode {
#[derive(Debug, Clone)]
pub struct HeadingSegment {
pub node: NodeId,
pub unit_id: String,
pub level: u8,
pub mode: HeadingMode,
pub name: String,
@@ -74,6 +71,10 @@ pub struct MarkdownTree {
node_functions: Vec<Option<NodeId>>,
node_headings: Vec<Option<NodeId>>,
node_modes: Vec<HeadingMode>,
function_headings: HashMap<String, NodeId>,
unit_headings: HashMap<String, NodeId>,
unit_functions: HashMap<String, String>,
heading_units: HashMap<NodeId, usize>,
}
#[derive(Debug, Deserialize)]
@@ -101,20 +102,71 @@ struct RawNode {
}
impl MarkdownTree {
pub fn from_json(value: Value, source: &SourceSnapshot) -> Result<Self> {
let raw: RawNode = serde_json::from_value(value)
.map_err(|error| LintError::Protocol(format!("AST JSON 无效:{error}")))?;
Self::from_raw(raw, source)
/// Empty container used only for an honest `analysis_incomplete` report
/// after `check` failed. It contains no document AST and therefore runs no
/// document-dependent rules.
pub fn empty(source: &SourceSnapshot) -> Self {
let span = Span::new(0, source.bytes.len());
Self {
nodes: vec![MarkdownNode {
kind: "document".into(),
span,
literal: None,
level: None,
setext: false,
ordered: None,
start: None,
tight: None,
task: None,
ticks: None,
parent: None,
children: Vec::new(),
}],
root: 0,
headings: Vec::new(),
carriers: Vec::new(),
node_functions: vec![None],
node_headings: vec![None],
node_modes: vec![HeadingMode::Knowledge],
function_headings: HashMap::new(),
unit_headings: HashMap::new(),
unit_functions: HashMap::new(),
heading_units: HashMap::new(),
}
}
fn from_raw(raw: RawNode, source: &SourceSnapshot) -> Result<Self> {
/// Build the Markdown container and carrier index from the public
/// `modules[].document` projection plus the authoritative `units` list.
/// No declaration syntax is parsed here: modes, names, section ranges and
/// function ownership come only from Analysis.
pub fn from_analysis(
document: Value,
units: &[AnalysisUnit],
functions: &[AnalysisFunction],
source: &SourceSnapshot,
) -> Result<Self> {
let raw: RawNode = serde_json::from_value(document).map_err(|error| {
LintError::Protocol(format!("modules[].document JSON 无效:{error}"))
})?;
Self::from_raw(raw, units, functions, source)
}
fn from_raw(
raw: RawNode,
units: &[AnalysisUnit],
functions: &[AnalysisFunction],
source: &SourceSnapshot,
) -> Result<Self> {
if raw.kind != "document" {
return Err(LintError::Protocol("AST 根节点不是 document".into()));
return Err(LintError::Protocol(
"modules[].document 根节点不是 document".into(),
));
}
let mut nodes = Vec::new();
let root = flatten(raw, None, &mut nodes);
for node in &nodes {
node.span.validate(source.bytes.len())?;
source.slice(node.span)?;
}
let count = nodes.len();
let mut tree = Self {
@@ -125,62 +177,119 @@ impl MarkdownTree {
node_functions: vec![None; count],
node_headings: vec![None; count],
node_modes: vec![HeadingMode::Knowledge; count],
function_headings: HashMap::new(),
unit_headings: HashMap::new(),
unit_functions: HashMap::new(),
heading_units: HashMap::new(),
};
tree.index_headings_and_carriers(source)?;
tree.index_units(units, functions)?;
tree.index_regions_and_carriers(units, source)?;
Ok(tree)
}
fn index_headings_and_carriers(&mut self, source: &SourceSnapshot) -> Result<()> {
struct Ancestor {
level: u8,
mode: HeadingMode,
fn index_units(
&mut self,
units: &[AnalysisUnit],
functions: &[AnalysisFunction],
) -> Result<()> {
let function_unit_to_id: HashMap<&str, &str> = functions
.iter()
.map(|function| (function.unit_id.as_str(), function.id.as_str()))
.collect();
let units_by_id: HashMap<&str, &AnalysisUnit> =
units.iter().map(|unit| (unit.id.as_str(), unit)).collect();
for unit in units.iter().filter(|unit| unit.kind != UnitKind::Root) {
let mut cursor = Some(unit);
let mut owner = None;
while let Some(current) = cursor {
if current.kind == UnitKind::Function {
owner = function_unit_to_id.get(current.id.as_str()).copied();
break;
}
cursor = current
.parent_id
.as_deref()
.and_then(|id| units_by_id.get(id).copied());
}
if let Some(owner) = owner {
self.unit_functions
.insert(unit.id.clone(), owner.to_string());
}
}
let mut stack: Vec<Ancestor> = Vec::new();
for (index, unit) in units
.iter()
.enumerate()
.filter(|(_, unit)| unit.kind != UnitKind::Root)
{
let heading_span = unit.heading_span.ok_or_else(|| {
LintError::Protocol(format!("unit {} 缺少 heading_span", unit.id))
})?;
let node = self.heading_node_at(heading_span).ok_or_else(|| {
LintError::Protocol(format!(
"unit {} 的 heading_span 无法唯一对应 document heading",
unit.id
))
})?;
self.unit_headings.insert(unit.id.clone(), node);
self.heading_units.insert(node, index);
if unit.kind == UnitKind::Function {
let function_id = function_unit_to_id.get(unit.id.as_str()).ok_or_else(|| {
LintError::Protocol(format!("function unit {} 缺少 function 记录", unit.id))
})?;
self.function_headings
.insert((*function_id).to_string(), node);
}
}
Ok(())
}
fn heading_node_at(&self, span: Span) -> Option<NodeId> {
let matches: Vec<_> = self
.nodes
.iter()
.enumerate()
.filter(|(_, node)| node.kind == "heading" && node.span == span)
.map(|(node, _)| node)
.collect();
(matches.len() == 1).then_some(matches[0])
}
fn index_regions_and_carriers(
&mut self,
units: &[AnalysisUnit],
source: &SourceSnapshot,
) -> Result<()> {
let mut current_heading = None;
let mut current_function = None;
let mut current_mode = HeadingMode::Knowledge;
let root_children = self.nodes[self.root].children.clone();
for child in root_children {
if self.nodes[child].kind == "heading" {
let level = self.nodes[child].level.unwrap_or(0);
while stack.last().is_some_and(|entry| entry.level >= level) {
stack.pop();
}
let inherited = stack
.last()
.map(|entry| entry.mode)
.unwrap_or(HeadingMode::Knowledge);
let declared = if self.nodes[child].setext {
None
} else {
heading_declaration(self, child)
};
current_mode = declared
.as_ref()
.map(|(mode, _)| *mode)
.unwrap_or(inherited);
let unit_index = self.heading_units.get(&child).copied().ok_or_else(|| {
LintError::Protocol(format!(
"document heading 字节 [{}, {}) 没有对应 unit",
self.nodes[child].span.start, self.nodes[child].span.end
))
})?;
let unit = &units[unit_index];
current_heading = Some(child);
match level {
1 => current_function = None,
2 => {
current_function = (current_mode == HeadingMode::Exec).then_some(child)
}
_ => {}
}
let name = declared
.map(|(_, name)| name)
.unwrap_or_else(|| plain_text(self, child));
current_mode = unit.mode;
current_function = match unit.kind {
UnitKind::Function => Some(child),
UnitKind::Section => self
.unit_functions
.get(&unit.id)
.and_then(|id| self.function_headings.get(id).copied()),
_ => None,
};
self.headings.push(HeadingSegment {
node: child,
level,
mode: current_mode,
name,
unit_id: unit.id.clone(),
level: unit.level,
mode: unit.mode,
name: unit.name.clone(),
function: current_function,
});
stack.push(Ancestor {
level,
mode: current_mode,
});
self.node_headings[child] = current_heading;
self.node_functions[child] = current_function;
self.node_modes[child] = current_mode;
@@ -253,7 +362,7 @@ impl MarkdownTree {
});
let mut spans = children;
let first = spans.next().unwrap_or(span);
let last = spans.last().unwrap_or(first);
let last = spans.next_back().unwrap_or(first);
Span::new(first.start, last.end)
};
source.slice(span)?;
@@ -296,6 +405,19 @@ impl MarkdownTree {
self.headings.iter().find(|heading| heading.node == node)
}
pub fn heading_for_unit(&self, unit_id: &str) -> Option<NodeId> {
self.unit_headings.get(unit_id).copied()
}
pub fn function_heading(&self, function_id: &str) -> Option<NodeId> {
self.function_headings.get(function_id).copied()
}
pub fn function_segment(&self, function_id: &str) -> Option<&HeadingSegment> {
let node = self.function_heading(function_id)?;
self.heading(node)
}
pub fn ancestors(&self, mut node: NodeId) -> Vec<NodeId> {
let mut result = Vec::new();
while let Some(parent) = self.nodes[node].parent {
@@ -319,7 +441,9 @@ impl MarkdownTree {
}
pub fn first_carrier_in_item(&self, item: NodeId) -> Option<&Carrier> {
self.item_carriers(item).into_iter().min_by_key(|c| c.span.start)
self.item_carriers(item)
.into_iter()
.min_by_key(|c| c.span.start)
}
pub fn is_descendant(&self, node: NodeId, ancestor: NodeId) -> bool {
@@ -352,7 +476,10 @@ impl MarkdownTree {
fn has_carrier_ancestor(&self, node: NodeId) -> bool {
self.ancestors(node).into_iter().any(|ancestor| {
matches!(self.nodes[ancestor].kind.as_str(), "strong" | "emph" | "code")
matches!(
self.nodes[ancestor].kind.as_str(),
"strong" | "emph" | "code"
)
})
}
@@ -360,7 +487,13 @@ impl MarkdownTree {
self.ancestors(node).into_iter().any(|ancestor| {
matches!(
self.nodes[ancestor].kind.as_str(),
"table" | "strikethrough" | "code_block" | "math" | "math_block" | "html_block" | "html_inline"
"table"
| "strikethrough"
| "code_block"
| "math"
| "math_block"
| "html_block"
| "html_inline"
)
})
}
@@ -394,83 +527,3 @@ fn flatten(raw: RawNode, parent: Option<NodeId>, nodes: &mut Vec<MarkdownNode>)
}
id
}
fn heading_declaration(tree: &MarkdownTree, heading: NodeId) -> Option<(HeadingMode, String)> {
let first = tree.nodes[heading].children.first()?;
let first = &tree.nodes[*first];
if first.kind != "text" {
return None;
}
let literal = first.literal.as_deref()?;
for (prefix, mode) in [
("@exec", HeadingMode::Exec),
("@knowledge", HeadingMode::Knowledge),
] {
if let Some(rest) = literal.strip_prefix(prefix) {
if rest.is_empty() || rest.starts_with(char::is_whitespace) {
let name = rest.trim();
if !name.is_empty() {
return Some((mode, name.to_string()));
}
}
}
}
None
}
pub fn plain_text(tree: &MarkdownTree, node: NodeId) -> String {
let node = &tree.nodes[node];
if let Some(literal) = &node.literal {
if node.kind == "text" || node.kind == "code" {
return literal.clone();
}
}
node.children
.iter()
.map(|child| plain_text(tree, *child))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn tree(markdown: &str) -> MarkdownTree {
let source = SourceSnapshot::new(PathBuf::from("test.mq.md"), markdown.as_bytes().to_vec()).unwrap();
let ast = crate::input::fallback_ast(&source).unwrap();
MarkdownTree::from_json(ast, &source).unwrap()
}
#[test]
fn indexes_functions_carriers_and_list_ancestors() {
let tree = tree("# @knowledge 示例\n\n## @exec 判断\n\n说明。\n\n`params(x: Int)`\n\n1. `if x > 0`:正数。\n\n **结果 = 1**\n\n2. `else`:其他。\n\n **结果 = 0**\n\n`end`\n\n*return 结果*\n");
assert_eq!(tree.headings.len(), 2);
assert_eq!(tree.carriers.len(), 7);
let if_carrier = tree.carriers.iter().find(|c| c.payload == "if x > 0").unwrap();
let item = tree.nearest(if_carrier.node, "item").unwrap();
assert_eq!(tree.first_carrier_in_item(item).unwrap().node, if_carrier.node);
let list = tree.nearest(item, "list").unwrap();
assert_eq!(tree.nodes[list].ordered, Some(true));
}
#[test]
fn knowledge_carriers_are_not_executable() {
let tree = tree("## @knowledge 说明\n\n**重要** 和 `code`。\n");
assert!(tree.carriers.is_empty());
assert!(tree.prose_fragments(0).is_empty());
}
#[test]
fn exec_emphasis_is_a_carrier_not_prose_and_headings_are_excluded() {
let tree = tree("## @exec 标题不计量\n\n普通说明 **重要** 继续说明。\n\n### 小节也不计量\n\n*return 0*\n");
let function = tree.headings[0].node;
let prose: Vec<_> = tree
.prose_fragments(function)
.into_iter()
.map(|fragment| fragment.text)
.collect();
assert_eq!(prose, vec!["普通说明 ", " 继续说明。"]);
assert!(tree.carriers.iter().any(|carrier| carrier.payload == "重要"));
}
}
+7 -3
View File
@@ -4,11 +4,15 @@ mod source;
mod span;
pub use analysis::{
semantic_nodes, AnalysisFunction, AnalysisModule, CoreDiagnostic, ExecutionProjection,
semantic_nodes, AnalysisAnchor, AnalysisCall, AnalysisDiagnostic, AnalysisFunction,
AnalysisImport, AnalysisModule, AnalysisParam, AnalysisProject, AnalysisReference,
AnalysisResource, AnalysisSignature, AnalysisUnit, CallReason, CallState, CallTargetKind,
CallTargetOwner, ExecutionProjection, ExtensionIdentity, HeadingMode, IdentityKind, ModeOrigin,
Producer, ReferenceState, ReferenceTargetKind, ResourceKind, SignatureKind, StdlibIdentity,
UnitKind,
};
pub use markdown::{
Carrier, CarrierKind, HeadingMode, HeadingSegment, MarkdownNode, MarkdownTree, NodeId,
ProseFragment,
Carrier, CarrierKind, HeadingSegment, MarkdownNode, MarkdownTree, NodeId, ProseFragment,
};
pub use source::SourceSnapshot;
pub use span::{LineColumn, Span};
+20 -5
View File
@@ -1,4 +1,7 @@
use std::{fs, path::{Path, PathBuf}};
use std::{
fs,
path::{Path, PathBuf},
};
use sha2::{Digest, Sha256};
@@ -52,7 +55,10 @@ impl SourceSnapshot {
pub fn slice(&self, span: Span) -> Result<&str> {
span.validate(self.bytes.len())?;
self.text().get(span.start..span.end).ok_or_else(|| {
LintError::Protocol(format!("span [{}, {}) 不在 UTF-8 字符边界", span.start, span.end))
LintError::Protocol(format!(
"span [{}, {}) 不在 UTF-8 字符边界",
span.start, span.end
))
})
}
@@ -93,9 +99,18 @@ mod tests {
)
.unwrap();
assert!(source.digest.starts_with("sha256:"));
assert_eq!(source.line_column(3).unwrap(), LineColumn { line: 1, column: 1 });
assert_eq!(source.line_column(6).unwrap(), LineColumn { line: 1, column: 2 });
assert_eq!(source.line_column(11).unwrap(), LineColumn { line: 2, column: 1 });
assert_eq!(
source.line_column(3).unwrap(),
LineColumn { line: 1, column: 1 }
);
assert_eq!(
source.line_column(6).unwrap(),
LineColumn { line: 1, column: 2 }
);
assert_eq!(
source.line_column(11).unwrap(),
LineColumn { line: 2, column: 1 }
);
}
#[test]