feat: add source and public protocol inputs

This commit is contained in:
cflmy committed 2026-11-23 16:58:12 +08:00
1 parent 68b14db095
commit e67697be06
30 files changed
+3021

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
use std::path::PathBuf;
#[derive(Debug, thiserror::Error)]
pub enum LintError {
#[error("无法读取 {path}: {source}")]
Io {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("{path} 不是有效 UTF-8:{source}")]
Utf8 {
path: PathBuf,
#[source]
source: std::str::Utf8Error,
},
#[error("协议错误:{0}")]
Protocol(String),
#[error("Marqdo 核心调用失败:{0}")]
Core(String),
#[error("配置错误:{0}")]
Config(String),
}
pub type Result<T> = std::result::Result<T, LintError>;
pub fn io(path: impl Into<PathBuf>, source: std::io::Error) -> LintError {
LintError::Io {
path: path.into(),
source,
}
}
+201
View File
@@ -0,0 +1,201 @@
use comrak::{
nodes::{ListType, Node, NodeValue, Sourcepos, TableAlignment},
parse_document, Arena, Options,
};
use serde_json::{json, Map, Value};
use crate::{error::Result, model::SourceSnapshot};
pub fn profile_options() -> Options<'static> {
let mut options = Options::default();
options.extension.table = true;
options.extension.strikethrough = true;
options.extension.tasklist = true;
options.extension.math_dollars = true;
options.extension.math_dollars_block = true;
options.extension.front_matter_delimiter = Some("---".to_string());
options
}
pub fn fallback_ast(source: &SourceSnapshot) -> Result<Value> {
let text = source.text();
let (shift, body) = text
.strip_prefix('\u{feff}')
.map(|body| (3, body))
.unwrap_or((0, text));
let arena = Arena::new();
let root = parse_document(&arena, body, &profile_options());
let line_starts = line_starts(body);
Ok(convert(&root, &line_starts, shift, body.len()))
}
fn line_starts(source: &str) -> Vec<usize> {
let mut starts = vec![0];
for (index, byte) in source.bytes().enumerate() {
if byte == b'\n' {
starts.push(index + 1);
}
}
starts
}
fn span(pos: Sourcepos, starts: &[usize], shift: usize, len: usize) -> SpanValue {
let offset = |line: usize, column: usize, inclusive: bool| {
if line == 0 {
return 0;
}
starts
.get(line - 1)
.map(|start| {
(start + column.saturating_sub(1) + usize::from(inclusive)).min(len)
})
.unwrap_or(len)
};
let start = offset(pos.start.line, pos.start.column, false);
let end = offset(pos.end.line, pos.end.column, true).max(start);
SpanValue(start + shift, end + shift)
}
struct SpanValue(usize, usize);
fn convert(node: &Node<'_>, starts: &[usize], shift: usize, len: usize) -> Value {
let data = node.data();
let SpanValue(start, end) = span(data.sourcepos, starts, shift, len);
let mut object = Map::new();
object.insert("span".into(), json!({"start": start, "end": end}));
let mut literal = None;
match &data.value {
NodeValue::Document => {
object.insert("kind".into(), json!("document"));
}
NodeValue::FrontMatter(raw) => {
object.insert("kind".into(), json!("front_matter"));
literal = Some(raw.clone());
}
NodeValue::BlockQuote | NodeValue::MultilineBlockQuote(_) => {
object.insert("kind".into(), json!("block_quote"));
}
NodeValue::List(list) => {
object.insert("kind".into(), json!("list"));
object.insert(
"ordered".into(),
json!(list.list_type == ListType::Ordered),
);
if list.list_type == ListType::Ordered {
object.insert("start".into(), json!(list.start));
}
object.insert("tight".into(), json!(list.tight));
}
NodeValue::Item(_) => {
object.insert("kind".into(), json!("item"));
}
NodeValue::TaskItem(item) => {
object.insert("kind".into(), json!("item"));
object.insert("task".into(), json!(item.symbol.is_some()));
}
NodeValue::Heading(heading) => {
object.insert("kind".into(), json!("heading"));
object.insert("level".into(), json!(heading.level));
object.insert("setext".into(), json!(heading.setext));
}
NodeValue::Paragraph => {
object.insert("kind".into(), json!("paragraph"));
}
NodeValue::Text(text) => {
object.insert("kind".into(), json!("text"));
literal = Some(text.to_string());
}
NodeValue::Strong(_) => {
object.insert("kind".into(), json!("strong"));
}
NodeValue::Emph(_) => {
object.insert("kind".into(), json!("emph"));
}
NodeValue::Strikethrough(_) => {
object.insert("kind".into(), json!("strikethrough"));
}
NodeValue::Code(code) => {
object.insert("kind".into(), json!("code"));
object.insert("ticks".into(), json!(code.num_backticks));
literal = Some(code.literal.clone());
}
NodeValue::CodeBlock(block) => {
object.insert("kind".into(), json!("code_block"));
object.insert("fenced".into(), json!(block.fenced));
object.insert("info".into(), json!(block.info.trim()));
literal = Some(block.literal.clone());
}
NodeValue::Math(math) => {
object.insert("kind".into(), json!("math"));
object.insert("display".into(), json!(math.display_math));
literal = Some(math.literal.clone());
}
NodeValue::MathBlock(block) => {
object.insert("kind".into(), json!("math_block"));
literal = Some(block.literal.clone());
}
NodeValue::Link(link) => {
object.insert("kind".into(), json!("link"));
object.insert("url".into(), json!(link.url));
object.insert("title".into(), json!(link.title));
}
NodeValue::Image(image) => {
object.insert("kind".into(), json!("image"));
object.insert("url".into(), json!(image.url));
object.insert("title".into(), json!(image.title));
}
NodeValue::Table(table) => {
object.insert("kind".into(), json!("table"));
let alignments: Vec<_> = table
.alignments
.iter()
.map(|alignment| match alignment {
TableAlignment::Left => "left",
TableAlignment::Center => "center",
TableAlignment::Right => "right",
TableAlignment::None => "none",
})
.collect();
object.insert("alignments".into(), json!(alignments));
}
NodeValue::TableRow(row) => {
object.insert("kind".into(), json!("table_row"));
object.insert("header".into(), json!(row.header));
}
NodeValue::TableCell => {
object.insert("kind".into(), json!("table_cell"));
}
NodeValue::ThematicBreak(_) => {
object.insert("kind".into(), json!("thematic_break"));
}
NodeValue::SoftBreak => {
object.insert("kind".into(), json!("softbreak"));
}
NodeValue::LineBreak => {
object.insert("kind".into(), json!("linebreak"));
}
NodeValue::HtmlBlock(block) => {
object.insert("kind".into(), json!("html_block"));
literal = Some(block.literal.clone());
}
NodeValue::HtmlInline(raw) => {
object.insert("kind".into(), json!("html_inline"));
literal = Some(raw.clone());
}
other => {
object.insert("kind".into(), json!("other"));
object.insert("tag".into(), json!(format!("{other:?}")));
}
}
if let Some(literal) = literal {
object.insert("literal".into(), json!(literal));
}
let children: Vec<_> = node
.children()
.map(|child| convert(&child, starts, shift, len))
.collect();
if !children.is_empty() {
object.insert("children".into(), Value::Array(children));
}
Value::Object(object)
}
+124
View File
@@ -0,0 +1,124 @@
use std::{
fs,
path::{Path, PathBuf},
process::{Command, Output},
};
use serde_json::Value;
use tempfile::NamedTempFile;
use crate::error::{io, LintError, Result};
#[derive(Debug, Clone)]
pub struct MarqdoRunner {
binary: PathBuf,
}
#[derive(Debug)]
pub struct CheckOutcome {
pub success: bool,
pub analysis: Option<Value>,
pub output: String,
}
impl MarqdoRunner {
pub fn discover(explicit: Option<&Path>) -> Result<Self> {
let binary = explicit
.map(Path::to_path_buf)
.or_else(|| std::env::var_os("MARQDO_BIN").map(PathBuf::from))
.unwrap_or_else(|| PathBuf::from("marqdo"));
let runner = Self { binary };
runner.ensure_compatible()?;
Ok(runner)
}
pub fn binary(&self) -> &Path {
&self.binary
}
pub fn ensure_compatible(&self) -> Result<()> {
let output = self.run(&[std::ffi::OsStr::new("--version")])?;
if !output.status.success() {
return Err(LintError::Core(format_output(&output)));
}
let version = String::from_utf8_lossy(&output.stdout);
let version = version.trim().strip_prefix("marqdo ").unwrap_or(version.trim());
let major = version
.split('.')
.next()
.and_then(|part| part.parse::<u64>().ok());
if major != Some(3) {
return Err(LintError::Protocol(format!(
"需要 Marqdo >=3.0.0-beta.1,<4.0.0,实际为 {version}"
)));
}
Ok(())
}
pub fn inspect(&self, file: &Path) -> Result<Value> {
let output = Command::new(&self.binary)
.arg("inspect")
.arg(file)
.arg("--ast")
.arg("--json")
.output()
.map_err(|error| io(&self.binary, error))?;
if !output.status.success() {
return Err(LintError::Core(format_output(&output)));
}
let value: Value = serde_json::from_slice(&output.stdout)
.map_err(|error| LintError::Protocol(format!("inspect AST JSON 无效:{error}")))?;
if value.get("command").and_then(Value::as_str) != Some("inspect") {
return Err(LintError::Protocol("inspect 输出缺少 command=inspect".into()));
}
value
.get("ast")
.cloned()
.ok_or_else(|| LintError::Protocol("inspect 输出缺少 ast 字段".into()))
}
pub fn check(&self, file: &Path) -> Result<CheckOutcome> {
let temporary = NamedTempFile::new().map_err(|error| io("Analysis 临时文件", error))?;
let output = Command::new(&self.binary)
.arg("check")
.arg(file)
.arg("--emit")
.arg(temporary.path())
.output()
.map_err(|error| io(&self.binary, error))?;
let text = format_output(&output);
if !output.status.success() {
return Ok(CheckOutcome {
success: false,
analysis: None,
output: text,
});
}
let bytes = fs::read(temporary.path()).map_err(|error| io(temporary.path(), error))?;
let analysis = serde_json::from_slice(&bytes)
.map_err(|error| LintError::Protocol(format!("Analysis JSON 无效:{error}")))?;
Ok(CheckOutcome {
success: true,
analysis: Some(analysis),
output: text,
})
}
fn run(&self, args: &[&std::ffi::OsStr]) -> Result<Output> {
Command::new(&self.binary)
.args(args)
.output()
.map_err(|error| io(&self.binary, error))
}
}
fn format_output(output: &Output) -> String {
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
match (stdout.trim().is_empty(), stderr.trim().is_empty()) {
(false, false) => format!("{}\n{}", stdout.trim(), stderr.trim()),
(false, true) => stdout.trim().to_string(),
(true, false) => stderr.trim().to_string(),
(true, true) => format!("核心退出状态 {}", output.status),
}
}
+7
View File
@@ -0,0 +1,7 @@
mod fallback;
mod marqdo;
mod project;
pub use fallback::{fallback_ast, profile_options};
pub use marqdo::{CheckOutcome, MarqdoRunner};
pub use project::{AnalysisStatus, MarkdownOrigin, ProjectInput, SourceDocument};
+169
View File
@@ -0,0 +1,169 @@
use std::{
fs,
path::{Path, PathBuf},
};
use serde::Serialize;
use crate::{
error::{io, LintError, Result},
model::{AnalysisModule, ExecutionProjection, MarkdownTree, SourceSnapshot},
};
use super::{fallback_ast, MarqdoRunner};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AnalysisStatus {
Complete,
AnalysisIncomplete,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MarkdownOrigin {
MarqdoInspect,
ComrakFallback,
}
#[derive(Debug, Clone)]
pub struct SourceDocument {
pub source: SourceSnapshot,
pub markdown: MarkdownTree,
pub markdown_origin: MarkdownOrigin,
pub module: Option<AnalysisModule>,
}
#[derive(Debug)]
pub struct ProjectInput {
pub entry: PathBuf,
pub documents: Vec<SourceDocument>,
pub analysis: Option<ExecutionProjection>,
pub analysis_status: AnalysisStatus,
pub core_output: String,
pub notices: Vec<String>,
}
impl ProjectInput {
pub fn load(entry: impl AsRef<Path>, runner: &MarqdoRunner) -> Result<Self> {
let entry = fs::canonicalize(entry.as_ref()).map_err(|error| io(entry.as_ref(), error))?;
let mut notices = Vec::new();
let entry_document = read_document(&entry, runner, &mut notices)?;
let check = runner.check(&entry)?;
if !check.success {
return Ok(Self {
entry,
documents: vec![entry_document],
analysis: None,
analysis_status: AnalysisStatus::AnalysisIncomplete,
core_output: check.output,
notices,
});
}
let raw = check.analysis.ok_or_else(|| {
LintError::Protocol("核心 check 成功但没有生成 Analysis".into())
})?;
let analysis = ExecutionProjection::from_json(raw).map_err(LintError::Protocol)?;
let root = project_root(&entry);
let mut documents = Vec::new();
for module in analysis
.modules
.iter()
.filter(|module| module.package_instance_id.starts_with("root:"))
{
let path = root.join(&module.relative_path);
let mut document = read_document(&path, runner, &mut notices)?;
if document.source.digest_hex() != module.source_digest {
return Err(LintError::Protocol(format!(
"模块 {} 的源码摘要与 Analysis 不一致",
module.id
)));
}
for function in &module.functions {
function.span.validate(document.source.bytes.len())?;
function.heading_span.validate(document.source.bytes.len())?;
}
document.module = Some(module.clone());
documents.push(document);
}
if documents.is_empty() {
let module = analysis
.modules
.iter()
.find(|module| module.source_digest == entry_document.source.digest_hex())
.cloned();
let mut document = entry_document;
document.module = module;
documents.push(document);
}
documents.sort_by(|left, right| left.source.path.cmp(&right.source.path));
Ok(Self {
entry,
documents,
analysis: Some(analysis),
analysis_status: AnalysisStatus::Complete,
core_output: String::new(),
notices,
})
}
pub fn document_only(entry: impl AsRef<Path>, runner: &MarqdoRunner) -> Result<Self> {
let entry = fs::canonicalize(entry.as_ref()).map_err(|error| io(entry.as_ref(), error))?;
let mut notices = Vec::new();
let document = read_document(&entry, runner, &mut notices)?;
Ok(Self {
entry,
documents: vec![document],
analysis: None,
analysis_status: AnalysisStatus::AnalysisIncomplete,
core_output: String::new(),
notices,
})
}
}
fn read_document(
path: &Path,
runner: &MarqdoRunner,
notices: &mut Vec<String>,
) -> Result<SourceDocument> {
let source = SourceSnapshot::load(path)?;
match runner.inspect(path) {
Ok(ast) => {
let markdown = MarkdownTree::from_json(ast, &source)?;
Ok(SourceDocument {
source,
markdown,
markdown_origin: MarkdownOrigin::MarqdoInspect,
module: None,
})
}
Err(LintError::Core(message)) => {
let markdown = MarkdownTree::from_json(fallback_ast(&source)?, &source)?;
notices.push(format!(
"{}:inspect 不可用,已使用严格 comrak 降级;{message}",
path.display()
));
Ok(SourceDocument {
source,
markdown,
markdown_origin: MarkdownOrigin::ComrakFallback,
module: None,
})
}
Err(error) => Err(error),
}
}
fn project_root(entry: &Path) -> PathBuf {
let mut current = entry.parent().unwrap_or(Path::new("."));
loop {
if current.join("marqdo.yaml").is_file() {
return current.to_path_buf();
}
let Some(parent) = current.parent() else {
return entry.parent().unwrap_or(Path::new(".")).to_path_buf();
};
current = parent;
}
}
+3
View File
@@ -1,3 +1,6 @@
pub mod error;
pub mod input;
pub mod model;
pub mod rules;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
+130
View File
@@ -0,0 +1,130 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::Span;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Producer {
pub name: String,
pub version: String,
pub markdown_profile: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalysisFunction {
pub id: String,
pub unit_id: String,
pub local_name: String,
pub span: Span,
pub heading_span: Span,
pub signature: Value,
#[serde(default)]
pub effects: Vec<String>,
pub body: Vec<Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalysisModule {
pub id: String,
pub package_instance_id: String,
pub relative_path: String,
pub source_digest: String,
pub units: Vec<Value>,
pub functions: Vec<AnalysisFunction>,
#[serde(default)]
pub imports: Vec<Value>,
#[serde(default)]
pub references: Vec<Value>,
#[serde(default)]
pub calls: Vec<Value>,
#[serde(default)]
pub resources: Vec<Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoreDiagnostic {
pub module: Option<String>,
pub relative_path: Option<String>,
pub span: Option<Span>,
pub line: Option<usize>,
pub column: Option<usize>,
pub severity: String,
pub code: String,
pub message: String,
#[serde(default)]
pub hints: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct ExecutionProjection {
pub producer: Producer,
pub project: Value,
pub modules: Vec<AnalysisModule>,
pub diagnostics: Vec<CoreDiagnostic>,
pub raw: Value,
}
impl ExecutionProjection {
pub fn from_json(raw: Value) -> Result<Self, String> {
if raw.get("schema").and_then(Value::as_str) != Some("marqdo.analysis") {
return Err("Analysis schema 不是 marqdo.analysis".into());
}
if raw.get("schema_version").and_then(Value::as_u64) != Some(2) {
return Err("只支持 Analysis schema_version 2".into());
}
#[derive(Deserialize)]
struct Wire {
producer: Producer,
project: Value,
modules: Vec<AnalysisModule>,
#[serde(default)]
diagnostics: Vec<CoreDiagnostic>,
}
let wire: Wire = serde_json::from_value(raw.clone()).map_err(|error| error.to_string())?;
if wire.producer.markdown_profile != "marqdo.md.v1" {
return Err(format!(
"不支持的 Markdown Profile {}",
wire.producer.markdown_profile
));
}
for module in &wire.modules {
if module.source_digest.len() != 64
|| !module.source_digest.bytes().all(|byte| byte.is_ascii_hexdigit())
{
return Err(format!("模块 {} 的 source_digest 无效", module.id));
}
if module.relative_path.starts_with('/') || module.relative_path.contains("..") {
return Err(format!("模块 {} 的 relative_path 不安全", module.id));
}
}
Ok(Self {
producer: wire.producer,
project: wire.project,
modules: wire.modules,
diagnostics: wire.diagnostics,
raw,
})
}
}
pub fn semantic_nodes(body: &[Value]) -> impl Iterator<Item = &Value> {
body.iter().flat_map(walk_node)
}
fn walk_node(node: &Value) -> Box<dyn Iterator<Item = &Value> + '_> {
let mut nested = Vec::new();
if let Some(object) = node.as_object() {
for value in object.values() {
match value {
Value::Object(_) => nested.push(value),
Value::Array(array) => {
nested.extend(array.iter().filter(|value| value.is_object()));
}
_ => {}
}
}
}
Box::new(
std::iter::once(node).chain(nested.into_iter().flat_map(|value| walk_node(value))),
)
}
+456
View File
@@ -0,0 +1,456 @@
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());
}
}
+9
View File
@@ -0,0 +1,9 @@
mod analysis;
mod markdown;
mod source;
mod span;
pub use analysis::{semantic_nodes, AnalysisFunction, AnalysisModule, CoreDiagnostic, ExecutionProjection};
pub use markdown::{Carrier, CarrierKind, HeadingMode, HeadingSegment, MarkdownNode, MarkdownTree, NodeId};
pub use source::SourceSnapshot;
pub use span::{LineColumn, Span};
+107
View File
@@ -0,0 +1,107 @@
use std::{fs, path::{Path, PathBuf}};
use sha2::{Digest, Sha256};
use crate::error::{io, LintError, Result};
use super::{LineColumn, Span};
#[derive(Debug, Clone)]
pub struct SourceSnapshot {
pub path: PathBuf,
pub bytes: Vec<u8>,
pub digest: String,
line_starts: Vec<usize>,
}
impl SourceSnapshot {
pub fn load(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref();
let bytes = fs::read(path).map_err(|error| io(path, error))?;
Self::new(path.to_path_buf(), bytes)
}
pub fn new(path: PathBuf, bytes: Vec<u8>) -> Result<Self> {
std::str::from_utf8(&bytes).map_err(|source| LintError::Utf8 {
path: path.clone(),
source,
})?;
let digest = format!("sha256:{:x}", Sha256::digest(&bytes));
let mut line_starts = vec![0];
for (index, byte) in bytes.iter().enumerate() {
if *byte == b'\n' {
line_starts.push(index + 1);
}
}
Ok(Self {
path,
bytes,
digest,
line_starts,
})
}
pub fn text(&self) -> &str {
std::str::from_utf8(&self.bytes).expect("SourceSnapshot 构造时已验证 UTF-8")
}
pub fn digest_hex(&self) -> &str {
self.digest.trim_start_matches("sha256:")
}
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))
})
}
pub fn line_column(&self, offset: usize) -> Result<LineColumn> {
if offset > self.bytes.len() || !self.text().is_char_boundary(offset) {
return Err(LintError::Protocol(format!("无效源码偏移 {offset}")));
}
let line_index = match self.line_starts.binary_search(&offset) {
Ok(index) => index,
Err(index) => index - 1,
};
let start = self.line_starts[line_index];
let content_start = if line_index == 0 && self.bytes.starts_with(&[0xef, 0xbb, 0xbf]) {
3
} else {
start
};
let column = self.text()[content_start..offset.max(content_start)]
.chars()
.count()
+ 1;
Ok(LineColumn {
line: line_index + 1,
column,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn digest_and_columns_use_original_utf8_bytes() {
let source = SourceSnapshot::new(
PathBuf::from("unicode.mq.md"),
"\u{feff}甲😀\n乙".as_bytes().to_vec(),
)
.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 });
}
#[test]
fn rejects_invalid_span_and_invalid_utf8() {
let source = SourceSnapshot::new(PathBuf::from("x"), b"abc".to_vec()).unwrap();
assert!(source.slice(Span::new(2, 4)).is_err());
assert!(SourceSnapshot::new(PathBuf::from("x"), vec![0xff]).is_err());
}
}
+35
View File
@@ -0,0 +1,35 @@
use serde::{Deserialize, Serialize};
use crate::error::{LintError, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Span {
pub start: usize,
pub end: usize,
}
impl Span {
pub fn new(start: usize, end: usize) -> Self {
Self { start, end }
}
pub fn contains(self, other: Span) -> bool {
self.start <= other.start && other.end <= self.end
}
pub fn validate(self, len: usize) -> Result<()> {
if self.start > self.end || self.end > len {
return Err(LintError::Protocol(format!(
"span [{}, {}) 超出源码长度 {len}",
self.start, self.end
)));
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct LineColumn {
pub line: usize,
pub column: usize,
}