457 lines
15 KiB
Rust
457 lines
15 KiB
Rust
use serde::Deserialize;
|
|
use serde_json::Value;
|
|
|
|
use crate::error::{LintError, Result};
|
|
|
|
use super::{SourceSnapshot, Span};
|
|
|
|
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,
|
|
Strong,
|
|
Emph,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct MarkdownNode {
|
|
pub kind: String,
|
|
pub span: Span,
|
|
pub literal: Option<String>,
|
|
pub level: Option<u8>,
|
|
pub setext: bool,
|
|
pub ordered: Option<bool>,
|
|
pub start: Option<i64>,
|
|
pub tight: Option<bool>,
|
|
pub task: Option<bool>,
|
|
pub ticks: Option<usize>,
|
|
pub parent: Option<NodeId>,
|
|
pub children: Vec<NodeId>,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct HeadingSegment {
|
|
pub node: NodeId,
|
|
pub level: u8,
|
|
pub mode: HeadingMode,
|
|
pub name: String,
|
|
pub function: Option<NodeId>,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct Carrier {
|
|
pub node: NodeId,
|
|
pub kind: CarrierKind,
|
|
pub span: Span,
|
|
pub payload_span: Span,
|
|
pub payload: String,
|
|
pub heading: Option<NodeId>,
|
|
pub function: Option<NodeId>,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct ProseFragment {
|
|
pub node: NodeId,
|
|
pub span: Span,
|
|
pub text: String,
|
|
pub function: NodeId,
|
|
pub heading: Option<NodeId>,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct MarkdownTree {
|
|
pub nodes: Vec<MarkdownNode>,
|
|
pub root: NodeId,
|
|
pub headings: Vec<HeadingSegment>,
|
|
pub carriers: Vec<Carrier>,
|
|
node_functions: Vec<Option<NodeId>>,
|
|
node_headings: Vec<Option<NodeId>>,
|
|
node_modes: Vec<HeadingMode>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct RawNode {
|
|
kind: String,
|
|
span: Span,
|
|
#[serde(default)]
|
|
literal: Option<String>,
|
|
#[serde(default)]
|
|
level: Option<u8>,
|
|
#[serde(default)]
|
|
setext: bool,
|
|
#[serde(default)]
|
|
ordered: Option<bool>,
|
|
#[serde(default)]
|
|
start: Option<i64>,
|
|
#[serde(default)]
|
|
tight: Option<bool>,
|
|
#[serde(default)]
|
|
task: Option<bool>,
|
|
#[serde(default)]
|
|
ticks: Option<usize>,
|
|
#[serde(default)]
|
|
children: Vec<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)
|
|
}
|
|
|
|
fn from_raw(raw: RawNode, source: &SourceSnapshot) -> Result<Self> {
|
|
if raw.kind != "document" {
|
|
return Err(LintError::Protocol("AST 根节点不是 document".into()));
|
|
}
|
|
let mut nodes = Vec::new();
|
|
let root = flatten(raw, None, &mut nodes);
|
|
for node in &nodes {
|
|
node.span.validate(source.bytes.len())?;
|
|
}
|
|
let count = nodes.len();
|
|
let mut tree = Self {
|
|
nodes,
|
|
root,
|
|
headings: Vec::new(),
|
|
carriers: Vec::new(),
|
|
node_functions: vec![None; count],
|
|
node_headings: vec![None; count],
|
|
node_modes: vec![HeadingMode::Knowledge; count],
|
|
};
|
|
tree.index_headings_and_carriers(source)?;
|
|
Ok(tree)
|
|
}
|
|
|
|
fn index_headings_and_carriers(&mut self, source: &SourceSnapshot) -> Result<()> {
|
|
struct Ancestor {
|
|
level: u8,
|
|
mode: HeadingMode,
|
|
}
|
|
let mut stack: Vec<Ancestor> = Vec::new();
|
|
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);
|
|
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));
|
|
self.headings.push(HeadingSegment {
|
|
node: child,
|
|
level,
|
|
mode: current_mode,
|
|
name,
|
|
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;
|
|
continue;
|
|
}
|
|
self.assign_region(child, current_heading, current_function, current_mode);
|
|
if current_mode == HeadingMode::Exec && current_function.is_some() {
|
|
self.collect_carriers(child, current_heading, current_function, source)?;
|
|
}
|
|
}
|
|
self.carriers.sort_by_key(|carrier| carrier.span.start);
|
|
Ok(())
|
|
}
|
|
|
|
fn assign_region(
|
|
&mut self,
|
|
node: NodeId,
|
|
heading: Option<NodeId>,
|
|
function: Option<NodeId>,
|
|
mode: HeadingMode,
|
|
) {
|
|
self.node_headings[node] = heading;
|
|
self.node_functions[node] = function;
|
|
self.node_modes[node] = mode;
|
|
let children = self.nodes[node].children.clone();
|
|
for child in children {
|
|
self.assign_region(child, heading, function, mode);
|
|
}
|
|
}
|
|
|
|
fn collect_carriers(
|
|
&mut self,
|
|
node: NodeId,
|
|
heading: Option<NodeId>,
|
|
function: Option<NodeId>,
|
|
source: &SourceSnapshot,
|
|
) -> Result<()> {
|
|
let kind = self.nodes[node].kind.as_str();
|
|
let carrier_kind = match kind {
|
|
"code" => Some(CarrierKind::Code),
|
|
"strong" => Some(CarrierKind::Strong),
|
|
"emph" => Some(CarrierKind::Emph),
|
|
_ => None,
|
|
};
|
|
if let Some(carrier_kind) = carrier_kind {
|
|
let payload = if carrier_kind == CarrierKind::Code {
|
|
self.nodes[node].literal.clone().unwrap_or_default()
|
|
} else {
|
|
self.nodes[node]
|
|
.children
|
|
.iter()
|
|
.filter_map(|child| {
|
|
let child = &self.nodes[*child];
|
|
matches!(child.kind.as_str(), "text" | "code")
|
|
.then(|| child.literal.clone().unwrap_or_default())
|
|
})
|
|
.collect()
|
|
};
|
|
let span = self.nodes[node].span;
|
|
let payload_span = if carrier_kind == CarrierKind::Code {
|
|
let ticks = self.nodes[node].ticks.unwrap_or(1);
|
|
Span::new(
|
|
span.start.saturating_add(ticks).min(span.end),
|
|
span.end.saturating_sub(ticks).max(span.start),
|
|
)
|
|
} else {
|
|
let children = self.nodes[node].children.iter().filter_map(|child| {
|
|
let child = &self.nodes[*child];
|
|
matches!(child.kind.as_str(), "text" | "code").then_some(child.span)
|
|
});
|
|
let mut spans = children;
|
|
let first = spans.next().unwrap_or(span);
|
|
let last = spans.last().unwrap_or(first);
|
|
Span::new(first.start, last.end)
|
|
};
|
|
source.slice(span)?;
|
|
self.carriers.push(Carrier {
|
|
node,
|
|
kind: carrier_kind,
|
|
span,
|
|
payload_span,
|
|
payload,
|
|
heading,
|
|
function,
|
|
});
|
|
return Ok(());
|
|
}
|
|
if matches!(kind, "paragraph" | "list" | "item" | "block_quote") {
|
|
let children = self.nodes[node].children.clone();
|
|
for child in children {
|
|
self.collect_carriers(child, heading, function, source)?;
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn function_of(&self, node: NodeId) -> Option<NodeId> {
|
|
self.node_functions.get(node).copied().flatten()
|
|
}
|
|
|
|
pub fn heading_of(&self, node: NodeId) -> Option<NodeId> {
|
|
self.node_headings.get(node).copied().flatten()
|
|
}
|
|
|
|
pub fn mode_of(&self, node: NodeId) -> HeadingMode {
|
|
self.node_modes
|
|
.get(node)
|
|
.copied()
|
|
.unwrap_or(HeadingMode::Knowledge)
|
|
}
|
|
|
|
pub fn heading(&self, node: NodeId) -> Option<&HeadingSegment> {
|
|
self.headings.iter().find(|heading| heading.node == node)
|
|
}
|
|
|
|
pub fn ancestors(&self, mut node: NodeId) -> Vec<NodeId> {
|
|
let mut result = Vec::new();
|
|
while let Some(parent) = self.nodes[node].parent {
|
|
result.push(parent);
|
|
node = parent;
|
|
}
|
|
result
|
|
}
|
|
|
|
pub fn nearest(&self, node: NodeId, kind: &str) -> Option<NodeId> {
|
|
self.ancestors(node)
|
|
.into_iter()
|
|
.find(|ancestor| self.nodes[*ancestor].kind == kind)
|
|
}
|
|
|
|
pub fn item_carriers(&self, item: NodeId) -> Vec<&Carrier> {
|
|
self.carriers
|
|
.iter()
|
|
.filter(|carrier| self.nearest(carrier.node, "item") == Some(item))
|
|
.collect()
|
|
}
|
|
|
|
pub fn first_carrier_in_item(&self, item: NodeId) -> Option<&Carrier> {
|
|
self.item_carriers(item).into_iter().min_by_key(|c| c.span.start)
|
|
}
|
|
|
|
pub fn is_descendant(&self, node: NodeId, ancestor: NodeId) -> bool {
|
|
node == ancestor || self.ancestors(node).contains(&ancestor)
|
|
}
|
|
|
|
pub fn prose_fragments(&self, function: NodeId) -> Vec<ProseFragment> {
|
|
let mut fragments = Vec::new();
|
|
for node in 0..self.nodes.len() {
|
|
if self.nodes[node].kind == "text"
|
|
&& self.function_of(node) == Some(function)
|
|
&& self.mode_of(node) == HeadingMode::Exec
|
|
&& !self.has_carrier_ancestor(node)
|
|
&& !self.has_inert_ancestor(node)
|
|
{
|
|
if let Some(text) = self.nodes[node].literal.clone() {
|
|
fragments.push(ProseFragment {
|
|
node,
|
|
span: self.nodes[node].span,
|
|
text,
|
|
function,
|
|
heading: self.heading_of(node),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
fragments
|
|
}
|
|
|
|
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")
|
|
})
|
|
}
|
|
|
|
fn has_inert_ancestor(&self, node: NodeId) -> bool {
|
|
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"
|
|
)
|
|
})
|
|
}
|
|
}
|
|
|
|
fn flatten(raw: RawNode, parent: Option<NodeId>, nodes: &mut Vec<MarkdownNode>) -> NodeId {
|
|
let id = nodes.len();
|
|
nodes.push(MarkdownNode {
|
|
kind: raw.kind,
|
|
span: raw.span,
|
|
literal: raw.literal,
|
|
level: raw.level,
|
|
setext: raw.setext,
|
|
ordered: raw.ordered,
|
|
start: raw.start,
|
|
tight: raw.tight,
|
|
task: raw.task,
|
|
ticks: raw.ticks,
|
|
parent,
|
|
children: Vec::new(),
|
|
});
|
|
for child in raw.children {
|
|
let child = flatten(child, Some(id), nodes);
|
|
nodes[id].children.push(child);
|
|
}
|
|
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());
|
|
}
|
|
}
|