diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..4f10109 --- /dev/null +++ b/src/error.rs @@ -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 = std::result::Result; + +pub fn io(path: impl Into, source: std::io::Error) -> LintError { + LintError::Io { + path: path.into(), + source, + } +} diff --git a/src/input/fallback.rs b/src/input/fallback.rs new file mode 100644 index 0000000..763302f --- /dev/null +++ b/src/input/fallback.rs @@ -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 { + 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 { + 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) +} diff --git a/src/input/marqdo.rs b/src/input/marqdo.rs new file mode 100644 index 0000000..7854442 --- /dev/null +++ b/src/input/marqdo.rs @@ -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, + pub output: String, +} + +impl MarqdoRunner { + pub fn discover(explicit: Option<&Path>) -> Result { + 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::().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 { + 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 { + 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 { + 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), + } +} diff --git a/src/input/mod.rs b/src/input/mod.rs new file mode 100644 index 0000000..86d0250 --- /dev/null +++ b/src/input/mod.rs @@ -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}; diff --git a/src/input/project.rs b/src/input/project.rs new file mode 100644 index 0000000..62b9c5c --- /dev/null +++ b/src/input/project.rs @@ -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, +} + +#[derive(Debug)] +pub struct ProjectInput { + pub entry: PathBuf, + pub documents: Vec, + pub analysis: Option, + pub analysis_status: AnalysisStatus, + pub core_output: String, + pub notices: Vec, +} + +impl ProjectInput { + pub fn load(entry: impl AsRef, runner: &MarqdoRunner) -> Result { + 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, runner: &MarqdoRunner) -> Result { + 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, +) -> Result { + 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; + } +} diff --git a/src/lib.rs b/src/lib.rs index c183423..1bc34a9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,6 @@ +pub mod error; +pub mod input; +pub mod model; pub mod rules; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/src/model/analysis.rs b/src/model/analysis.rs new file mode 100644 index 0000000..67cf6d6 --- /dev/null +++ b/src/model/analysis.rs @@ -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, + pub body: Vec, +} + +#[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, + pub functions: Vec, + #[serde(default)] + pub imports: Vec, + #[serde(default)] + pub references: Vec, + #[serde(default)] + pub calls: Vec, + #[serde(default)] + pub resources: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CoreDiagnostic { + pub module: Option, + pub relative_path: Option, + pub span: Option, + pub line: Option, + pub column: Option, + pub severity: String, + pub code: String, + pub message: String, + #[serde(default)] + pub hints: Vec, +} + +#[derive(Debug, Clone)] +pub struct ExecutionProjection { + pub producer: Producer, + pub project: Value, + pub modules: Vec, + pub diagnostics: Vec, + pub raw: Value, +} + +impl ExecutionProjection { + pub fn from_json(raw: Value) -> Result { + 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, + #[serde(default)] + diagnostics: Vec, + } + 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 { + body.iter().flat_map(walk_node) +} + +fn walk_node(node: &Value) -> Box + '_> { + 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))), + ) +} diff --git a/src/model/markdown.rs b/src/model/markdown.rs new file mode 100644 index 0000000..bfdfd63 --- /dev/null +++ b/src/model/markdown.rs @@ -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, + pub level: Option, + pub setext: bool, + pub ordered: Option, + pub start: Option, + pub tight: Option, + pub task: Option, + pub ticks: Option, + pub parent: Option, + pub children: Vec, +} + +#[derive(Debug, Clone)] +pub struct HeadingSegment { + pub node: NodeId, + pub level: u8, + pub mode: HeadingMode, + pub name: String, + pub function: Option, +} + +#[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, + pub function: Option, +} + +#[derive(Debug, Clone)] +pub struct ProseFragment { + pub node: NodeId, + pub span: Span, + pub text: String, + pub function: NodeId, + pub heading: Option, +} + +#[derive(Debug, Clone)] +pub struct MarkdownTree { + pub nodes: Vec, + pub root: NodeId, + pub headings: Vec, + pub carriers: Vec, + node_functions: Vec>, + node_headings: Vec>, + node_modes: Vec, +} + +#[derive(Debug, Deserialize)] +struct RawNode { + kind: String, + span: Span, + #[serde(default)] + literal: Option, + #[serde(default)] + level: Option, + #[serde(default)] + setext: bool, + #[serde(default)] + ordered: Option, + #[serde(default)] + start: Option, + #[serde(default)] + tight: Option, + #[serde(default)] + task: Option, + #[serde(default)] + ticks: Option, + #[serde(default)] + children: Vec, +} + +impl MarkdownTree { + pub fn from_json(value: Value, source: &SourceSnapshot) -> Result { + 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 { + 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 = 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, + function: Option, + 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, + function: Option, + 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 { + self.node_functions.get(node).copied().flatten() + } + + pub fn heading_of(&self, node: NodeId) -> Option { + 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 { + 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 { + 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 { + 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, nodes: &mut Vec) -> 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()); + } +} diff --git a/src/model/mod.rs b/src/model/mod.rs new file mode 100644 index 0000000..df01fa9 --- /dev/null +++ b/src/model/mod.rs @@ -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}; diff --git a/src/model/source.rs b/src/model/source.rs new file mode 100644 index 0000000..6ad1dac --- /dev/null +++ b/src/model/source.rs @@ -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, + pub digest: String, + line_starts: Vec, +} + +impl SourceSnapshot { + pub fn load(path: impl AsRef) -> Result { + 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) -> Result { + 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 { + 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()); + } +} diff --git a/src/model/span.rs b/src/model/span.rs new file mode 100644 index 0000000..930eb3f --- /dev/null +++ b/src/model/span.rs @@ -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, +} diff --git a/tests/fixtures/golden/bom.analysis.json b/tests/fixtures/golden/bom.analysis.json new file mode 100644 index 0000000..091cced --- /dev/null +++ b/tests/fixtures/golden/bom.analysis.json @@ -0,0 +1,107 @@ +{ + "diagnostics": [], + "modules": [ + { + "calls": [], + "functions": [ + { + "body": [ + { + "kind": "return", + "span": { + "end": 99, + "start": 89 + }, + "value": { + "kind": "variable", + "name": "x", + "span": { + "end": 98, + "start": 97 + } + } + } + ], + "effects": [ + "unknown" + ], + "heading_span": { + "end": 21, + "start": 3 + }, + "id": "root:default::bom.mq.md::BOM位置", + "local_name": "BOM位置", + "namespace": null, + "signature": { + "kind": "explicit", + "params": [ + { + "default": null, + "name": "x", + "required": true, + "span": { + "end": 84, + "start": 78 + }, + "type": "Int" + } + ] + }, + "span": { + "end": 99, + "start": 3 + }, + "unit_id": "root:default::bom.mq.md#BOM位置" + } + ], + "id": "root:default::bom.mq.md", + "imports": [], + "package_instance_id": "root:default", + "references": [], + "relative_path": "bom.mq.md", + "resources": [], + "source_digest": "b7973730c6130d1f555e78d0685b495fdc70d9a5e76755dd1700a74c761bc802", + "units": [ + { + "function": null, + "id": "root:default::bom.mq.md#", + "kind": "root", + "level": 0, + "name": "", + "span": { + "end": 99, + "start": 3 + } + }, + { + "function": "root:default::bom.mq.md::BOM位置", + "id": "root:default::bom.mq.md#BOM位置", + "kind": "function", + "level": 2, + "name": "BOM位置", + "span": { + "end": 21, + "start": 3 + } + } + ] + } + ], + "producer": { + "markdown_profile": "marqdo.md.v1", + "name": "marqdo", + "version": "3.0.0-rc.1" + }, + "project": { + "identity_kind": "workspace_snapshot", + "lock_digest": "", + "root_id": "sha256:09c24ef9d9b03ffcb4fcf8ff3d40306d47c7c6cbcfb151837edad217d1e70921", + "stdlib": { + "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "version": "0.1.0" + } + }, + "schema": "marqdo.analysis", + "schema_version": 2 +} \ No newline at end of file diff --git a/tests/fixtures/golden/bom.ast.json b/tests/fixtures/golden/bom.ast.json new file mode 100644 index 0000000..52e4ddf --- /dev/null +++ b/tests/fixtures/golden/bom.ast.json @@ -0,0 +1,93 @@ +{ + "ast": { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "@exec BOM位置", + "span": { + "end": 21, + "start": 6 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 21, + "start": 3 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "BOM 后的中文 span 仍相对原始字节。", + "span": { + "end": 69, + "start": 23 + } + } + ], + "kind": "paragraph", + "span": { + "end": 69, + "start": 23 + } + }, + { + "children": [ + { + "kind": "code", + "literal": "params(x: Int)", + "span": { + "end": 87, + "start": 71 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 87, + "start": 71 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "return x", + "span": { + "end": 98, + "start": 90 + } + } + ], + "kind": "emph", + "span": { + "end": 99, + "start": 89 + } + } + ], + "kind": "paragraph", + "span": { + "end": 99, + "start": 89 + } + } + ], + "kind": "document", + "span": { + "end": 99, + "start": 3 + } + }, + "command": "inspect", + "module": "root:default::bom.mq.md" +} diff --git a/tests/fixtures/golden/bom.mq.md b/tests/fixtures/golden/bom.mq.md new file mode 100644 index 0000000..061d9f9 --- /dev/null +++ b/tests/fixtures/golden/bom.mq.md @@ -0,0 +1,7 @@ +## @exec BOM位置 + +BOM 后的中文 span 仍相对原始字节。 + +`params(x: Int)` + +*return x* diff --git a/tests/fixtures/golden/branches.analysis.json b/tests/fixtures/golden/branches.analysis.json new file mode 100644 index 0000000..40ad225 --- /dev/null +++ b/tests/fixtures/golden/branches.analysis.json @@ -0,0 +1,236 @@ +{ + "diagnostics": [], + "modules": [ + { + "calls": [], + "functions": [ + { + "body": [ + { + "kind": "assign", + "span": { + "end": 147, + "start": 133 + }, + "target": "结果", + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "0" + } + }, + { + "arms": [ + { + "body": [ + { + "kind": "assign", + "span": { + "end": 202, + "start": 188 + }, + "target": "结果", + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "1" + } + } + ], + "condition": { + "kind": "binary", + "left": { + "kind": "variable", + "name": "x", + "span": { + "end": 157, + "start": 156 + } + }, + "op": "gt", + "right": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "0" + }, + "span": { + "end": 161, + "start": 156 + } + }, + "condition_span": { + "end": 162, + "start": 152 + }, + "span": { + "end": 162, + "start": 152 + } + }, + { + "body": [ + { + "kind": "assign", + "span": { + "end": 259, + "start": 245 + }, + "target": "结果", + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "0" + } + } + ], + "condition": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "bool", + "value": true + }, + "condition_span": { + "end": 162, + "start": 152 + }, + "span": { + "end": 162, + "start": 152 + } + } + ], + "kind": "branch", + "span": { + "end": 162, + "start": 152 + } + }, + { + "kind": "return", + "span": { + "end": 306, + "start": 291 + }, + "value": { + "kind": "variable", + "name": "结果", + "span": { + "end": 305, + "start": 299 + } + } + } + ], + "effects": [ + "unknown" + ], + "heading_span": { + "end": 48, + "start": 27 + }, + "id": "root:default::branches.mq.md::协议样例.判断正负", + "local_name": "判断正负", + "namespace": "协议样例", + "signature": { + "kind": "explicit", + "params": [ + { + "default": null, + "name": "x", + "required": true, + "span": { + "end": 128, + "start": 122 + }, + "type": "Int" + } + ] + }, + "span": { + "end": 306, + "start": 27 + }, + "unit_id": "root:default::branches.mq.md#协议样例/判断正负" + } + ], + "id": "root:default::branches.mq.md", + "imports": [], + "package_instance_id": "root:default", + "references": [], + "relative_path": "branches.mq.md", + "resources": [], + "source_digest": "dcc2c9869c5f2a53cff5a2c479e67143b9b0617ffe0b605bf920a7322d85aa3f", + "units": [ + { + "function": null, + "id": "root:default::branches.mq.md#", + "kind": "root", + "level": 0, + "name": "", + "span": { + "end": 306, + "start": 0 + } + }, + { + "function": null, + "id": "root:default::branches.mq.md#协议样例", + "kind": "namespace", + "level": 1, + "name": "协议样例", + "span": { + "end": 25, + "start": 0 + } + }, + { + "function": "root:default::branches.mq.md::协议样例.判断正负", + "id": "root:default::branches.mq.md#协议样例/判断正负", + "kind": "function", + "level": 2, + "name": "判断正负", + "span": { + "end": 48, + "start": 27 + } + } + ] + } + ], + "producer": { + "markdown_profile": "marqdo.md.v1", + "name": "marqdo", + "version": "3.0.0-rc.1" + }, + "project": { + "identity_kind": "workspace_snapshot", + "lock_digest": "", + "root_id": "sha256:9dbd8404c6a0bf58390c673052d0076cfcb787646c0ffdb27a30837ef142273d", + "stdlib": { + "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "version": "0.1.0" + } + }, + "schema": "marqdo.analysis", + "schema_version": 2 +} \ No newline at end of file diff --git a/tests/fixtures/golden/branches.ast.json b/tests/fixtures/golden/branches.ast.json new file mode 100644 index 0000000..b51e589 --- /dev/null +++ b/tests/fixtures/golden/branches.ast.json @@ -0,0 +1,307 @@ +{ + "ast": { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "@knowledge 协议样例", + "span": { + "end": 25, + "start": 2 + } + } + ], + "kind": "heading", + "level": 1, + "setext": false, + "span": { + "end": 25, + "start": 0 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "@exec 判断正负", + "span": { + "end": 48, + "start": 30 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 48, + "start": 27 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "根据整数是否为正返回一或零,结果没有单位。", + "span": { + "end": 113, + "start": 50 + } + } + ], + "kind": "paragraph", + "span": { + "end": 113, + "start": 50 + } + }, + { + "children": [ + { + "kind": "code", + "literal": "params(x: Int)", + "span": { + "end": 131, + "start": 115 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 131, + "start": 115 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "结果 = 0", + "span": { + "end": 145, + "start": 135 + } + } + ], + "kind": "strong", + "span": { + "end": 147, + "start": 133 + } + } + ], + "kind": "paragraph", + "span": { + "end": 147, + "start": 133 + } + }, + { + "children": [ + { + "children": [ + { + "children": [ + { + "kind": "code", + "literal": "if x > 0", + "span": { + "end": 162, + "start": 152 + }, + "ticks": 1 + }, + { + "kind": "text", + "literal": ":正数返回一。", + "span": { + "end": 183, + "start": 162 + } + } + ], + "kind": "paragraph", + "span": { + "end": 183, + "start": 152 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "结果 = 1", + "span": { + "end": 200, + "start": 190 + } + } + ], + "kind": "strong", + "span": { + "end": 202, + "start": 188 + } + } + ], + "kind": "paragraph", + "span": { + "end": 202, + "start": 188 + } + } + ], + "kind": "item", + "span": { + "end": 202, + "start": 149 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "code", + "literal": "else", + "span": { + "end": 213, + "start": 207 + }, + "ticks": 1 + }, + { + "kind": "text", + "literal": ":零和负数返回零。", + "span": { + "end": 240, + "start": 213 + } + } + ], + "kind": "paragraph", + "span": { + "end": 240, + "start": 207 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "结果 = 0", + "span": { + "end": 257, + "start": 247 + } + } + ], + "kind": "strong", + "span": { + "end": 259, + "start": 245 + } + } + ], + "kind": "paragraph", + "span": { + "end": 259, + "start": 245 + } + } + ], + "kind": "item", + "span": { + "end": 259, + "start": 204 + } + } + ], + "kind": "list", + "ordered": true, + "span": { + "end": 259, + "start": 149 + }, + "start": 1, + "tight": false + }, + { + "children": [ + { + "kind": "code", + "literal": "end", + "span": { + "end": 266, + "start": 261 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 266, + "start": 261 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "返回整数结果。", + "span": { + "end": 289, + "start": 268 + } + } + ], + "kind": "paragraph", + "span": { + "end": 289, + "start": 268 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "return 结果", + "span": { + "end": 305, + "start": 292 + } + } + ], + "kind": "emph", + "span": { + "end": 306, + "start": 291 + } + } + ], + "kind": "paragraph", + "span": { + "end": 306, + "start": 291 + } + } + ], + "kind": "document", + "span": { + "end": 306, + "start": 0 + } + }, + "command": "inspect", + "module": "root:default::branches.mq.md" +} diff --git a/tests/fixtures/golden/branches.mq.md b/tests/fixtures/golden/branches.mq.md new file mode 100644 index 0000000..ac41127 --- /dev/null +++ b/tests/fixtures/golden/branches.mq.md @@ -0,0 +1,23 @@ +# @knowledge 协议样例 + +## @exec 判断正负 + +根据整数是否为正返回一或零,结果没有单位。 + +`params(x: Int)` + +**结果 = 0** + +1. `if x > 0`:正数返回一。 + + **结果 = 1** + +2. `else`:零和负数返回零。 + + **结果 = 0** + +`end` + +返回整数结果。 + +*return 结果* diff --git a/tests/fixtures/golden/invalid-control.ast.json b/tests/fixtures/golden/invalid-control.ast.json new file mode 100644 index 0000000..c91a3a9 --- /dev/null +++ b/tests/fixtures/golden/invalid-control.ast.json @@ -0,0 +1,237 @@ +{ + "ast": { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "@exec 跨段控制", + "span": { + "end": 21, + "start": 3 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 21, + "start": 0 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "说明跨段控制的错误。", + "span": { + "end": 53, + "start": 23 + } + } + ], + "kind": "paragraph", + "span": { + "end": 53, + "start": 23 + } + }, + { + "children": [ + { + "kind": "code", + "literal": "params(x: Int)", + "span": { + "end": 71, + "start": 55 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 71, + "start": 55 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "开始", + "span": { + "end": 83, + "start": 77 + } + } + ], + "kind": "heading", + "level": 3, + "setext": false, + "span": { + "end": 83, + "start": 73 + } + }, + { + "children": [ + { + "kind": "code", + "literal": "if x > 0", + "span": { + "end": 95, + "start": 85 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 95, + "start": 85 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "结果 = 1", + "span": { + "end": 109, + "start": 99 + } + } + ], + "kind": "strong", + "span": { + "end": 111, + "start": 97 + } + } + ], + "kind": "paragraph", + "span": { + "end": 111, + "start": 97 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "结束", + "span": { + "end": 123, + "start": 117 + } + } + ], + "kind": "heading", + "level": 3, + "setext": false, + "span": { + "end": 123, + "start": 113 + } + }, + { + "children": [ + { + "kind": "code", + "literal": "else", + "span": { + "end": 131, + "start": 125 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 131, + "start": 125 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "结果 = 0", + "span": { + "end": 145, + "start": 135 + } + } + ], + "kind": "strong", + "span": { + "end": 147, + "start": 133 + } + } + ], + "kind": "paragraph", + "span": { + "end": 147, + "start": 133 + } + }, + { + "children": [ + { + "kind": "code", + "literal": "end", + "span": { + "end": 154, + "start": 149 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 154, + "start": 149 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "return 结果", + "span": { + "end": 170, + "start": 157 + } + } + ], + "kind": "emph", + "span": { + "end": 171, + "start": 156 + } + } + ], + "kind": "paragraph", + "span": { + "end": 171, + "start": 156 + } + } + ], + "kind": "document", + "span": { + "end": 171, + "start": 0 + } + }, + "command": "inspect", + "module": "root:default::invalid-control.mq.md" +} diff --git a/tests/fixtures/golden/invalid-control.check.txt b/tests/fixtures/golden/invalid-control.check.txt new file mode 100644 index 0000000..d4706e4 --- /dev/null +++ b/tests/fixtures/golden/invalid-control.check.txt @@ -0,0 +1,10 @@ +error[sem.unclosed_control]: /home/cflmy/work/marqdo-lint/tests/fixtures/golden/invalid-control.mq.md:9:1: `if` is not closed by `end` + `if x > 0` + ^ +error[sem.unmatched_else]: /home/cflmy/work/marqdo-lint/tests/fixtures/golden/invalid-control.mq.md:15:1: `else` has no open `if` + `else` + ^ +error[sem.unmatched_end]: /home/cflmy/work/marqdo-lint/tests/fixtures/golden/invalid-control.mq.md:19:1: `end` has no open `if`/`while` in this heading segment + `end` + ^ +check failed: 3 error(s), 0 warning(s) diff --git a/tests/fixtures/golden/invalid-control.mq.md b/tests/fixtures/golden/invalid-control.mq.md new file mode 100644 index 0000000..41bfcbd --- /dev/null +++ b/tests/fixtures/golden/invalid-control.mq.md @@ -0,0 +1,21 @@ +## @exec 跨段控制 + +说明跨段控制的错误。 + +`params(x: Int)` + +### 开始 + +`if x > 0` + +**结果 = 1** + +### 结束 + +`else` + +**结果 = 0** + +`end` + +*return 结果* diff --git a/tests/fixtures/golden/knowledge.analysis.json b/tests/fixtures/golden/knowledge.analysis.json new file mode 100644 index 0000000..d33c28f --- /dev/null +++ b/tests/fixtures/golden/knowledge.analysis.json @@ -0,0 +1,57 @@ +{ + "diagnostics": [], + "modules": [ + { + "calls": [], + "functions": [], + "id": "root:default::knowledge.mq.md", + "imports": [], + "package_instance_id": "root:default", + "references": [], + "relative_path": "knowledge.mq.md", + "resources": [], + "source_digest": "342f1937f86ae7b4bfd917ad45b1438b6a6756ecba499b45da5d40e34af3ce5c", + "units": [ + { + "function": null, + "id": "root:default::knowledge.mq.md#", + "kind": "root", + "level": 0, + "name": "", + "span": { + "end": 155, + "start": 0 + } + }, + { + "function": null, + "id": "root:default::knowledge.mq.md#富文本", + "kind": "knowledge", + "level": 2, + "name": "富文本", + "span": { + "end": 23, + "start": 0 + } + } + ] + } + ], + "producer": { + "markdown_profile": "marqdo.md.v1", + "name": "marqdo", + "version": "3.0.0-rc.1" + }, + "project": { + "identity_kind": "workspace_snapshot", + "lock_digest": "", + "root_id": "sha256:3cdb7daa24f2c7cda11ed43c931de8f27e3508519c66148759308012ae78930a", + "stdlib": { + "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "version": "0.1.0" + } + }, + "schema": "marqdo.analysis", + "schema_version": 2 +} \ No newline at end of file diff --git a/tests/fixtures/golden/knowledge.ast.json b/tests/fixtures/golden/knowledge.ast.json new file mode 100644 index 0000000..4b956e4 --- /dev/null +++ b/tests/fixtures/golden/knowledge.ast.json @@ -0,0 +1,217 @@ +{ + "ast": { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "@knowledge 富文本", + "span": { + "end": 23, + "start": 3 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 23, + "start": 0 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "这里的 ", + "span": { + "end": 35, + "start": 25 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "加粗", + "span": { + "end": 43, + "start": 37 + } + } + ], + "kind": "strong", + "span": { + "end": 45, + "start": 35 + } + }, + { + "kind": "text", + "literal": "、", + "span": { + "end": 48, + "start": 45 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "斜体", + "span": { + "end": 55, + "start": 49 + } + } + ], + "kind": "emph", + "span": { + "end": 56, + "start": 48 + } + }, + { + "kind": "text", + "literal": " 与 ", + "span": { + "end": 61, + "start": 56 + } + }, + { + "kind": "code", + "literal": "code", + "span": { + "end": 67, + "start": 61 + }, + "ticks": 1 + }, + { + "kind": "text", + "literal": " 都是惰性内容。", + "span": { + "end": 89, + "start": 67 + } + } + ], + "kind": "paragraph", + "span": { + "end": 89, + "start": 25 + } + }, + { + "alignments": [ + "none", + "none" + ], + "children": [ + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "名称", + "span": { + "end": 99, + "start": 93 + } + } + ], + "kind": "table_cell", + "span": { + "end": 100, + "start": 92 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "说明", + "span": { + "end": 108, + "start": 102 + } + } + ], + "kind": "table_cell", + "span": { + "end": 109, + "start": 101 + } + } + ], + "header": true, + "kind": "table_row", + "span": { + "end": 110, + "start": 91 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "表格", + "span": { + "end": 129, + "start": 123 + } + } + ], + "kind": "table_cell", + "span": { + "end": 130, + "start": 122 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "不参与叙述比例", + "span": { + "end": 153, + "start": 132 + } + } + ], + "kind": "table_cell", + "span": { + "end": 154, + "start": 131 + } + } + ], + "header": false, + "kind": "table_row", + "span": { + "end": 155, + "start": 121 + } + } + ], + "kind": "table", + "span": { + "end": 155, + "start": 91 + } + } + ], + "kind": "document", + "span": { + "end": 155, + "start": 0 + } + }, + "command": "inspect", + "module": "root:default::knowledge.mq.md" +} diff --git a/tests/fixtures/golden/knowledge.mq.md b/tests/fixtures/golden/knowledge.mq.md new file mode 100644 index 0000000..563dec6 --- /dev/null +++ b/tests/fixtures/golden/knowledge.mq.md @@ -0,0 +1,7 @@ +## @knowledge 富文本 + +这里的 **加粗**、*斜体* 与 `code` 都是惰性内容。 + +| 名称 | 说明 | +|---|---| +| 表格 | 不参与叙述比例 | diff --git a/tests/fixtures/golden/unicode.analysis.json b/tests/fixtures/golden/unicode.analysis.json new file mode 100644 index 0000000..d2f1d21 --- /dev/null +++ b/tests/fixtures/golden/unicode.analysis.json @@ -0,0 +1,140 @@ +{ + "diagnostics": [], + "modules": [ + { + "calls": [], + "functions": [ + { + "body": [ + { + "kind": "assign", + "span": { + "end": 116, + "start": 98 + }, + "target": "结果", + "value": { + "kind": "binary", + "left": { + "kind": "variable", + "name": "x", + "span": { + "end": 110, + "start": 109 + } + }, + "op": "add", + "right": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "1" + }, + "span": { + "end": 114, + "start": 109 + } + } + }, + { + "kind": "return", + "span": { + "end": 156, + "start": 141 + }, + "value": { + "kind": "variable", + "name": "结果", + "span": { + "end": 155, + "start": 149 + } + } + } + ], + "effects": [ + "unknown" + ], + "heading_span": { + "end": 22, + "start": 0 + }, + "id": "root:default::unicode.mq.md::多字节😀", + "local_name": "多字节😀", + "namespace": null, + "signature": { + "kind": "explicit", + "params": [ + { + "default": null, + "name": "x", + "required": true, + "span": { + "end": 93, + "start": 87 + }, + "type": "Int" + } + ] + }, + "span": { + "end": 156, + "start": 0 + }, + "unit_id": "root:default::unicode.mq.md#多字节😀" + } + ], + "id": "root:default::unicode.mq.md", + "imports": [], + "package_instance_id": "root:default", + "references": [], + "relative_path": "unicode.mq.md", + "resources": [], + "source_digest": "07464d28973b2a7ed9e1d96ed689104239bb61863c90922d74a9f230e73b1bee", + "units": [ + { + "function": null, + "id": "root:default::unicode.mq.md#", + "kind": "root", + "level": 0, + "name": "", + "span": { + "end": 156, + "start": 0 + } + }, + { + "function": "root:default::unicode.mq.md::多字节😀", + "id": "root:default::unicode.mq.md#多字节😀", + "kind": "function", + "level": 2, + "name": "多字节😀", + "span": { + "end": 22, + "start": 0 + } + } + ] + } + ], + "producer": { + "markdown_profile": "marqdo.md.v1", + "name": "marqdo", + "version": "3.0.0-rc.1" + }, + "project": { + "identity_kind": "workspace_snapshot", + "lock_digest": "", + "root_id": "sha256:6bc3c991a61f2f39ae5c8a58f02c1d860b6bcc3d9df547a3b24ff61bcb47f072", + "stdlib": { + "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "version": "0.1.0" + } + }, + "schema": "marqdo.analysis", + "schema_version": 2 +} \ No newline at end of file diff --git a/tests/fixtures/golden/unicode.ast.json b/tests/fixtures/golden/unicode.ast.json new file mode 100644 index 0000000..565b020 --- /dev/null +++ b/tests/fixtures/golden/unicode.ast.json @@ -0,0 +1,136 @@ +{ + "ast": { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "@exec 多字节😀", + "span": { + "end": 22, + "start": 3 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 22, + "start": 0 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "中文说明与 emoji 😀 用于验证精确位置。", + "span": { + "end": 78, + "start": 24 + } + } + ], + "kind": "paragraph", + "span": { + "end": 78, + "start": 24 + } + }, + { + "children": [ + { + "kind": "code", + "literal": "params(x: Int)", + "span": { + "end": 96, + "start": 80 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 96, + "start": 80 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "结果 = x + 1", + "span": { + "end": 114, + "start": 100 + } + } + ], + "kind": "strong", + "span": { + "end": 116, + "start": 98 + } + } + ], + "kind": "paragraph", + "span": { + "end": 116, + "start": 98 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "返回整数结果。", + "span": { + "end": 139, + "start": 118 + } + } + ], + "kind": "paragraph", + "span": { + "end": 139, + "start": 118 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "return 结果", + "span": { + "end": 155, + "start": 142 + } + } + ], + "kind": "emph", + "span": { + "end": 156, + "start": 141 + } + } + ], + "kind": "paragraph", + "span": { + "end": 156, + "start": 141 + } + } + ], + "kind": "document", + "span": { + "end": 156, + "start": 0 + } + }, + "command": "inspect", + "module": "root:default::unicode.mq.md" +} diff --git a/tests/fixtures/golden/unicode.mq.md b/tests/fixtures/golden/unicode.mq.md new file mode 100644 index 0000000..6cf7ea6 --- /dev/null +++ b/tests/fixtures/golden/unicode.mq.md @@ -0,0 +1,11 @@ +## @exec 多字节😀 + +中文说明与 emoji 😀 用于验证精确位置。 + +`params(x: Int)` + +**结果 = x + 1** + +返回整数结果。 + +*return 结果* diff --git a/tests/fixtures/multi/geometry.mq.md b/tests/fixtures/multi/geometry.mq.md new file mode 100644 index 0000000..d44a749 --- /dev/null +++ b/tests/fixtures/multi/geometry.mq.md @@ -0,0 +1,15 @@ +## @exec 圆面积 + +计算圆面积,输入半径与输出面积使用一致单位。 + +`params(r: Number)` + +纯语言算术使用近似 π;公式仅作为惰性 Markdown 资源保留。 + +*return 3.141592653589793 * r * r* + +### @knowledge 公式 + +$$ +A = \pi r^2 +$$ diff --git a/tests/fixtures/multi/index.mq.md b/tests/fixtures/multi/index.mq.md new file mode 100644 index 0000000..8961186 --- /dev/null +++ b/tests/fixtures/multi/index.mq.md @@ -0,0 +1,12 @@ +--- +import: + geometry: "./geometry.mq.md" +--- + +## @exec main + +计算半径为二的圆面积并输出。 + +**面积 = geometry.圆面积(r=2)** + +> **打印(面积)** diff --git a/tests/fixtures/multi/marqdo.yaml b/tests/fixtures/multi/marqdo.yaml new file mode 100644 index 0000000..b560dff --- /dev/null +++ b/tests/fixtures/multi/marqdo.yaml @@ -0,0 +1,5 @@ +project: + name: lint-input-multi + version: 0.1.0 + marqdo: ">=3.0.0-beta.1,<4.0.0" +dependencies: {} diff --git a/tests/input_pipeline.rs b/tests/input_pipeline.rs new file mode 100644 index 0000000..ef50756 --- /dev/null +++ b/tests/input_pipeline.rs @@ -0,0 +1,107 @@ +use std::path::{Path, PathBuf}; + +use marqdo_lint::{ + input::{fallback_ast, AnalysisStatus, MarqdoRunner, ProjectInput}, + model::{ExecutionProjection, SourceSnapshot}, +}; +use serde_json::{json, Value}; + +fn fixture(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/golden") + .join(name) +} + +#[test] +fn fallback_ast_matches_frozen_core_goldens() { + for stem in ["branches", "unicode", "bom", "knowledge", "invalid-control"] { + let source = SourceSnapshot::load(fixture(&format!("{stem}.mq.md"))).unwrap(); + let actual = fallback_ast(&source).unwrap(); + let expected: Value = serde_json::from_slice( + &std::fs::read(fixture(&format!("{stem}.ast.json"))).unwrap(), + ) + .unwrap(); + assert_eq!(actual, expected["ast"], "AST 不一致:{stem}"); + } +} + +#[test] +fn analysis_rejects_unknown_major() { + let error = ExecutionProjection::from_json(json!({ + "schema": "marqdo.analysis", + "schema_version": 3 + })); + assert!(error.is_err()); +} + +#[test] +fn frozen_core_binds_source_ast_and_analysis() { + let Ok(binary) = std::env::var("MARQDO_BIN") else { + eprintln!("MARQDO_BIN 未设置,跳过冻结核心集成测试"); + return; + }; + let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); + let project = ProjectInput::load(fixture("branches.mq.md"), &runner).unwrap(); + assert_eq!(project.analysis_status, AnalysisStatus::Complete); + assert_eq!(project.documents.len(), 1); + let document = &project.documents[0]; + assert_eq!(document.module.as_ref().unwrap().functions.len(), 1); + assert_eq!(document.markdown.carriers.len(), 8); +} + +#[test] +fn failed_check_is_analysis_incomplete_not_clean() { + let Ok(binary) = std::env::var("MARQDO_BIN") else { + eprintln!("MARQDO_BIN 未设置,跳过冻结核心集成测试"); + return; + }; + let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); + let project = ProjectInput::load(fixture("invalid-control.mq.md"), &runner).unwrap(); + assert_eq!(project.analysis_status, AnalysisStatus::AnalysisIncomplete); + assert!(project.analysis.is_none()); + assert!(project.core_output.contains("sem.unclosed_control")); +} + +#[test] +fn inspect_failure_uses_document_only_fallback() { + use std::{fs, os::unix::fs::PermissionsExt}; + + let directory = tempfile::tempdir().unwrap(); + let binary = directory.path().join("marqdo"); + fs::write( + &binary, + "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then echo 'marqdo 3.0.0-rc.1'; exit 0; fi\nif [ \"$1\" = \"inspect\" ]; then exit 2; fi\nif [ \"$1\" = \"check\" ]; then echo 'invalid document'; exit 1; fi\n", + ) + .unwrap(); + let mut permissions = fs::metadata(&binary).unwrap().permissions(); + permissions.set_mode(0o755); + fs::set_permissions(&binary, permissions).unwrap(); + let runner = MarqdoRunner::discover(Some(&binary)).unwrap(); + let project = ProjectInput::load(fixture("branches.mq.md"), &runner).unwrap(); + assert_eq!(project.analysis_status, AnalysisStatus::AnalysisIncomplete); + assert_eq!( + project.documents[0].markdown_origin, + marqdo_lint::input::MarkdownOrigin::ComrakFallback + ); + assert_eq!(project.notices.len(), 1); +} + +#[test] +fn multi_module_documents_keep_their_own_digest_and_spans() { + let Ok(binary) = std::env::var("MARQDO_BIN") else { + eprintln!("MARQDO_BIN 未设置,跳过冻结核心集成测试"); + return; + }; + let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); + let entry = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/multi/index.mq.md"); + let project = ProjectInput::load(entry, &runner).unwrap(); + assert_eq!(project.analysis_status, AnalysisStatus::Complete); + assert_eq!(project.documents.len(), 2); + for document in project.documents { + let module = document.module.unwrap(); + assert_eq!(module.source_digest, document.source.digest_hex()); + for function in module.functions { + assert!(function.span.end <= document.source.bytes.len()); + } + } +}