From f26f6099f24cfe14e0da806bb3c6e2430d17a086 Mon Sep 17 00:00:00 2001 From: cflmy Date: Mon, 23 Nov 2026 17:22:14 +0800 Subject: [PATCH] feat: add narrative metrics and documentation rules --- src/lib.rs | 1 + src/metrics/mod.rs | 299 +++++++++++++++++++++++++++++++++++ src/model/markdown.rs | 20 +++ src/model/mod.rs | 5 +- src/rules/documentation.rs | 93 +++++++++++ src/rules/mod.rs | 2 + tests/documentation_rules.rs | 196 +++++++++++++++++++++++ 7 files changed, 615 insertions(+), 1 deletion(-) create mode 100644 src/metrics/mod.rs create mode 100644 src/rules/documentation.rs create mode 100644 tests/documentation_rules.rs diff --git a/src/lib.rs b/src/lib.rs index 942e17c..f48fae0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,7 @@ pub mod alignment; pub mod diagnostics; pub mod error; pub mod input; +pub mod metrics; pub mod model; pub mod rules; diff --git a/src/metrics/mod.rs b/src/metrics/mod.rs new file mode 100644 index 0000000..9fe7906 --- /dev/null +++ b/src/metrics/mod.rs @@ -0,0 +1,299 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use unicode_general_category::{get_general_category, GeneralCategory}; +use unicode_normalization::UnicodeNormalization; + +use crate::{ + alignment::{node_span, statement_count}, + input::SourceDocument, + model::{ + semantic_nodes, AnalysisFunction, Carrier, HeadingMode, MarkdownTree, NodeId, ProseFragment, + Span, + }, +}; + +pub const MEASUREMENT_VERSION: u8 = 1; + +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct NarrativeConfig { + pub threshold: f64, + pub short_function_threshold: usize, +} + +impl Default for NarrativeConfig { + fn default() -> Self { + Self { + threshold: 0.50, + short_function_threshold: 4, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum NarrativeStatus { + Applicable, + NotApplicable, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ExplanationCoverage { + pub entry_span: Option, + pub result_anchor_span: Option, + pub result_span: Option, + pub repeated_prose_spans: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FunctionNarrative { + pub function_id: String, + pub function_name: String, + pub heading_span: Span, + pub n: usize, + pub e: usize, + pub table_n: usize, + pub statement_count: usize, + pub threshold: f64, + pub ratio: Option, + pub status: NarrativeStatus, + pub measurement_version: u8, + pub has_control_flow: bool, + pub has_explicit_effects: bool, + pub heading_segment_count: usize, + pub coverage: ExplanationCoverage, + #[serde(skip)] + pub coverage_complete: bool, +} + +impl FunctionNarrative { + pub fn is_trivial_short_function(&self, config: NarrativeConfig) -> bool { + self.statement_count <= config.short_function_threshold + && !self.has_control_flow + && !self.has_explicit_effects + } +} + +pub fn measure_document( + document: &SourceDocument, + config: NarrativeConfig, +) -> Vec { + let Some(module) = &document.module else { + return Vec::new(); + }; + module + .functions + .iter() + .filter_map(|function| measure_function(&document.markdown, function, config)) + .collect() +} + +pub fn measure_function( + markdown: &MarkdownTree, + analysis: &AnalysisFunction, + config: NarrativeConfig, +) -> Option { + let heading = markdown.headings.iter().find(|heading| { + heading.function == Some(heading.node) + && markdown.nodes[heading.node].span == analysis.heading_span + })?; + let function = heading.node; + let mut carriers: Vec<_> = markdown + .carriers + .iter() + .filter(|carrier| carrier.function == Some(function)) + .collect(); + carriers.sort_by_key(|carrier| carrier.span.start); + let prose = markdown.prose_fragments(function); + let n = prose + .iter() + .map(|fragment| narrative_count(&fragment.text)) + .sum(); + let e = carriers + .iter() + .map(|carrier| carrier.payload.chars().count()) + .sum(); + let table_n = table_narrative_count(markdown, function); + let denominator = n + e; + let entry_span = carriers.first().and_then(|first| { + prose + .iter() + .filter(|fragment| { + fragment.span.start >= markdown.nodes[function].span.end + && fragment.span.end <= first.span.start + && narrative_count(&fragment.text) > 0 + }) + .map(|fragment| fragment.span) + .min_by_key(|span| span.start) + }); + let last_return = semantic_nodes(&analysis.body) + .filter(|node| node.get("kind").and_then(serde_json::Value::as_str) == Some("return")) + .filter_map(|node| node_span(node)) + .max_by_key(|span| span.start); + let mut coverage_complete = !carriers.is_empty(); + let result_anchor = if let Some(return_span) = last_return { + let carrier = carriers + .iter() + .find(|carrier| carrier.span == return_span) + .copied(); + if carrier.is_none() { + coverage_complete = false; + } + carrier + } else { + carriers.last().copied() + }; + let result_span = result_anchor.and_then(|anchor| { + result_explanation(markdown, &carriers, &prose, function, anchor) + }); + let repeated_prose_spans = repeated_prose(&prose); + let heading_segment_count = markdown + .headings + .iter() + .filter(|heading| heading.function == Some(function) && heading.level > 2) + .count(); + let has_control_flow = semantic_nodes(&analysis.body).any(|node| { + matches!( + node.get("kind").and_then(serde_json::Value::as_str), + Some("branch" | "loop") + ) + }); + let has_explicit_effects = analysis.effects.iter().any(|effect| { + !matches!(effect.trim(), "" | "unknown" | "none" | "pure") + }); + Some(FunctionNarrative { + function_id: analysis.id.clone(), + function_name: analysis.local_name.clone(), + heading_span: analysis.heading_span, + n, + e, + table_n, + statement_count: statement_count(analysis), + threshold: config.threshold, + ratio: (denominator > 0).then(|| n as f64 / denominator as f64), + status: if denominator > 0 { + NarrativeStatus::Applicable + } else { + NarrativeStatus::NotApplicable + }, + measurement_version: MEASUREMENT_VERSION, + has_control_flow, + has_explicit_effects, + heading_segment_count, + coverage: ExplanationCoverage { + entry_span, + result_anchor_span: result_anchor.map(|carrier| carrier.span), + result_span, + repeated_prose_spans, + }, + coverage_complete, + }) +} + +fn result_explanation( + markdown: &MarkdownTree, + carriers: &[&Carrier], + prose: &[ProseFragment], + function: NodeId, + anchor: &Carrier, +) -> Option { + let index = carriers.iter().position(|carrier| carrier.node == anchor.node)?; + let before_start = index + .checked_sub(1) + .map(|previous| carriers[previous].span.end) + .unwrap_or(markdown.nodes[function].span.end); + let after_end = carriers + .get(index + 1) + .map(|next| next.span.start) + .unwrap_or(usize::MAX); + prose + .iter() + .filter(|fragment| { + fragment.heading == anchor.heading + && narrative_count(&fragment.text) > 0 + && ((fragment.span.start >= before_start + && fragment.span.end <= anchor.span.start) + || (fragment.span.start >= anchor.span.end + && fragment.span.end <= after_end)) + }) + .map(|fragment| fragment.span) + .min_by_key(|span| span.start) +} + +fn repeated_prose(prose: &[ProseFragment]) -> Vec { + let mut occurrences: BTreeMap> = BTreeMap::new(); + for fragment in prose { + let normalized = fragment.text.nfc().collect::(); + let normalized = normalized.trim(); + if narrative_count(normalized) >= 8 { + occurrences + .entry(normalized.to_string()) + .or_default() + .push(fragment.span); + } + } + let mut spans: Vec<_> = occurrences + .into_values() + .filter(|spans| spans.len() > 1) + .flat_map(|spans| spans.into_iter().skip(1)) + .collect(); + spans.sort(); + spans +} + +fn table_narrative_count(markdown: &MarkdownTree, function: NodeId) -> usize { + markdown + .nodes + .iter() + .enumerate() + .filter(|(index, node)| { + node.kind == "text" + && markdown.function_of(*index) == Some(function) + && markdown.mode_of(*index) == HeadingMode::Exec + && markdown + .ancestors(*index) + .into_iter() + .any(|ancestor| markdown.nodes[ancestor].kind == "table") + }) + .map(|(_, node)| { + node.literal + .as_deref() + .map(narrative_count) + .unwrap_or_default() + }) + .sum() +} + +pub fn narrative_count(text: &str) -> usize { + text.nfc() + .filter(|character| { + !character.is_whitespace() + && !matches!( + get_general_category(*character), + GeneralCategory::ClosePunctuation + | GeneralCategory::ConnectorPunctuation + | GeneralCategory::DashPunctuation + | GeneralCategory::FinalPunctuation + | GeneralCategory::InitialPunctuation + | GeneralCategory::OpenPunctuation + | GeneralCategory::OtherPunctuation + | GeneralCategory::Control + | GeneralCategory::Format + | GeneralCategory::LineSeparator + | GeneralCategory::ParagraphSeparator + ) + }) + .count() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn narrative_count_is_nfc_reproducible_and_ignores_punctuation() { + assert_eq!(narrative_count("Cafe\u{301}, 处理 😀"), 7); + assert_eq!(narrative_count("Café, 处理 😀"), 7); + assert_eq!(narrative_count(" \n\t,。! "), 0); + } +} diff --git a/src/model/markdown.rs b/src/model/markdown.rs index bfdfd63..5a92907 100644 --- a/src/model/markdown.rs +++ b/src/model/markdown.rs @@ -334,6 +334,7 @@ impl MarkdownTree { && self.mode_of(node) == HeadingMode::Exec && !self.has_carrier_ancestor(node) && !self.has_inert_ancestor(node) + && !self.has_heading_ancestor(node) { if let Some(text) = self.nodes[node].literal.clone() { fragments.push(ProseFragment { @@ -363,6 +364,12 @@ impl MarkdownTree { ) }) } + + fn has_heading_ancestor(&self, node: NodeId) -> bool { + self.ancestors(node) + .into_iter() + .any(|ancestor| self.nodes[ancestor].kind == "heading") + } } fn flatten(raw: RawNode, parent: Option, nodes: &mut Vec) -> NodeId { @@ -453,4 +460,17 @@ mod tests { assert!(tree.carriers.is_empty()); assert!(tree.prose_fragments(0).is_empty()); } + + #[test] + fn exec_emphasis_is_a_carrier_not_prose_and_headings_are_excluded() { + let tree = tree("## @exec 标题不计量\n\n普通说明 **重要** 继续说明。\n\n### 小节也不计量\n\n*return 0*\n"); + let function = tree.headings[0].node; + let prose: Vec<_> = tree + .prose_fragments(function) + .into_iter() + .map(|fragment| fragment.text) + .collect(); + assert_eq!(prose, vec!["普通说明 ", " 继续说明。"]); + assert!(tree.carriers.iter().any(|carrier| carrier.payload == "重要")); + } } diff --git a/src/model/mod.rs b/src/model/mod.rs index df01fa9..afa4615 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -4,6 +4,9 @@ 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 markdown::{ + Carrier, CarrierKind, HeadingMode, HeadingSegment, MarkdownNode, MarkdownTree, NodeId, + ProseFragment, +}; pub use source::SourceSnapshot; pub use span::{LineColumn, Span}; diff --git a/src/rules/documentation.rs b/src/rules/documentation.rs new file mode 100644 index 0000000..0f4cb2e --- /dev/null +++ b/src/rules/documentation.rs @@ -0,0 +1,93 @@ +use crate::{ + diagnostics::Diagnostic, + input::SourceDocument, + metrics::{measure_function, FunctionNarrative, NarrativeConfig}, + model::MarkdownTree, + rules::Severity, +}; + +pub fn check_documentation( + document: &SourceDocument, + config: NarrativeConfig, +) -> Vec { + let Some(module) = &document.module else { + return Vec::new(); + }; + let mut diagnostics = Vec::new(); + for function in &module.functions { + if let Some(metrics) = measure_function(&document.markdown, function, config) { + diagnostics.extend(check_function_documentation( + &document.markdown, + &metrics, + config, + )); + } + } + diagnostics.sort_by(|left, right| { + (left.span.start, left.span.end, &left.id).cmp(&( + right.span.start, + right.span.end, + &right.id, + )) + }); + diagnostics +} + +pub fn check_function_documentation( + markdown: &MarkdownTree, + metrics: &FunctionNarrative, + config: NarrativeConfig, +) -> Vec { + let mut diagnostics = Vec::new(); + if metrics.coverage.entry_span.is_none() { + diagnostics.push( + Diagnostic::new("MQD-DOC-001", metrics.heading_span) + .with_function(&metrics.function_name), + ); + } + if metrics.coverage_complete && metrics.coverage.result_span.is_none() { + diagnostics.push( + Diagnostic::new( + "MQD-DOC-002", + metrics + .coverage + .result_anchor_span + .unwrap_or(metrics.heading_span), + ) + .with_function(&metrics.function_name), + ); + } + if let Some(ratio) = metrics.ratio { + if ratio < config.threshold { + let mut diagnostic = Diagnostic::new("MQD-DOC-003", metrics.heading_span) + .with_function(&metrics.function_name) + .with_message(format!( + "函数叙述占比 R={ratio:.3},低于配置阈值 {:.3}", + config.threshold + )); + if metrics.is_trivial_short_function(config) { + diagnostic.severity = Severity::Info; + } + diagnostics.push(diagnostic); + } + } + if metrics.statement_count > config.short_function_threshold + && (metrics.heading_segment_count == 0 + || metrics.heading_segment_count > metrics.statement_count) + { + let mut diagnostic = Diagnostic::new("MQD-DOC-004", metrics.heading_span) + .with_function(&metrics.function_name); + if metrics.heading_segment_count > 0 { + for heading in markdown.headings.iter().filter(|heading| { + heading.level > 2 + && heading.function.is_some_and(|function| { + markdown.nodes[function].span == metrics.heading_span + }) + }) { + diagnostic = diagnostic.with_related(markdown.nodes[heading.node].span); + } + } + diagnostics.push(diagnostic); + } + diagnostics +} diff --git a/src/rules/mod.rs b/src/rules/mod.rs index bbb2c82..263e699 100644 --- a/src/rules/mod.rs +++ b/src/rules/mod.rs @@ -1,6 +1,8 @@ mod control; +mod documentation; pub use control::{check_document, check_function}; +pub use documentation::{check_documentation, check_function_documentation}; use serde::{Deserialize, Serialize}; diff --git a/tests/documentation_rules.rs b/tests/documentation_rules.rs new file mode 100644 index 0000000..fa4f488 --- /dev/null +++ b/tests/documentation_rules.rs @@ -0,0 +1,196 @@ +use std::{fs, path::Path}; + +use marqdo_lint::{ + input::{AnalysisStatus, MarqdoRunner, ProjectInput}, + metrics::{measure_document, NarrativeConfig, NarrativeStatus}, + rules::{check_documentation, Severity}, +}; + +fn load(source: &str) -> Option { + let binary = std::env::var("MARQDO_BIN").ok().or_else(|| { + eprintln!("MARQDO_BIN 未设置,跳过冻结核心叙述规则测试"); + None + })?; + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("case.mq.md"); + fs::write(&path, source).unwrap(); + let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); + Some(ProjectInput::load(path, &runner).unwrap()) +} + +fn metrics(project: &ProjectInput) -> Vec { + assert_eq!( + project.analysis_status, + AnalysisStatus::Complete, + "{}", + project.core_output + ); + measure_document(&project.documents[0], NarrativeConfig::default()) +} + +fn diagnostics(project: &ProjectInput) -> Vec { + assert_eq!( + project.analysis_status, + AnalysisStatus::Complete, + "{}", + project.core_output + ); + check_documentation(&project.documents[0], NarrativeConfig::default()) +} + +#[test] +fn t14_t15_and_t24_unicode_nfc_counts_use_code_points_not_utf8_bytes() { + let decomposed = "## @exec Unicode\n\nCafe\u{301}, 处理 😀\n\n`params(x: Int)`\n\n**结果 = x**\n\n*return 结果*\n"; + let composed = "## @exec Unicode\n\nCafé, 处理 😀\n\n`params(x: Int)`\n\n**结果 = x**\n\n*return 结果*\n"; + let Some(first) = load(decomposed) else { return }; + let Some(second) = load(composed) else { return }; + let first = metrics(&first); + let second = metrics(&second); + assert_eq!(first.len(), 1); + assert_eq!(first[0].n, 7); + assert_eq!(first[0].e, 29); + assert_eq!(first[0].ratio, Some(7.0 / 36.0)); + assert_eq!(first[0].measurement_version, 1); + assert_eq!((first[0].n, first[0].e), (second[0].n, second[0].e)); + + let english = "## @exec English\n\nEnglish prose\n\n`params(x: Int)`\n\n**结果 = x**\n\n*return 结果*\n"; + let Some(english) = load(english) else { return }; + assert_eq!(metrics(&english)[0].n, 12); +} + +#[test] +fn t13_t21_and_t22_knowledge_and_tables_cannot_inflate_the_main_ratio() { + let base = "## @exec 计算\n\n计算结果。\n\n`params(x: Int)`\n\n**结果 = x**\n\n返回结果。\n\n*return 结果*\n"; + let knowledge = "## @knowledge 资料\n\n**大量** `惰性` 内容不参与执行,也不增加叙述。\n\n## @exec 计算\n\n计算结果。\n\n`params(x: Int)`\n\n**结果 = x**\n\n返回结果。\n\n*return 结果*\n"; + let table = "## @exec 计算\n\n计算结果。\n\n`params(x: Int)`\n\n| 列甲 | 列乙 |\n| --- | --- |\n| 很长的表格资料 | 其他数据 |\n\n**结果 = x**\n\n返回结果。\n\n*return 结果*\n"; + let Some(base) = load(base) else { return }; + let Some(knowledge) = load(knowledge) else { return }; + let Some(table) = load(table) else { return }; + let base = metrics(&base); + let knowledge = metrics(&knowledge); + let table = metrics(&table); + assert_eq!((base[0].n, base[0].e), (knowledge[0].n, knowledge[0].e)); + assert_eq!((base[0].n, base[0].e), (table[0].n, table[0].e)); + assert_eq!(base[0].statement_count, table[0].statement_count); + assert_eq!(base[0].table_n, 0); + assert!(table[0].table_n > 0); +} + +#[test] +fn doc_001_and_doc_002_check_explanation_existence_and_position() { + let missing_entry = "## @exec 缺少入口\n\n`params(x: Int)`\n\n**结果 = x**\n\n返回整数结果。\n\n*return 结果*\n"; + let Some(project) = load(missing_entry) else { return }; + assert!(diagnostics(&project) + .iter() + .any(|diagnostic| diagnostic.id == "MQD-DOC-001")); + + let missing_result = "## @exec 缺少结果\n\n计算输入并返回。\n\n`params(x: Int)`\n\n**结果 = x**\n\n*return 结果*\n"; + let Some(project) = load(missing_result) else { return }; + assert!(diagnostics(&project) + .iter() + .any(|diagnostic| diagnostic.id == "MQD-DOC-002")); + + let covered = "## @exec 已说明\n\n计算输入并返回。\n\n`params(x: Int)`\n\n**结果 = x**\n\n返回整数结果,没有单位。\n\n*return 结果*\n"; + let Some(project) = load(covered) else { return }; + assert!(!diagnostics(&project).iter().any(|diagnostic| { + matches!(diagnostic.id.as_str(), "MQD-DOC-001" | "MQD-DOC-002") + })); +} + +#[test] +fn t23_trivial_short_functions_only_receive_info_ratio_diagnostics() { + let source = "## @exec 短函数\n\n`params(x: Int)`\n\n**结果 = x**\n\n*return 结果*\n"; + let Some(project) = load(source) else { return }; + let diagnostics = diagnostics(&project); + let ratio = diagnostics + .iter() + .find(|diagnostic| diagnostic.id == "MQD-DOC-003") + .unwrap(); + assert_eq!(ratio.severity, Severity::Info); + assert!(!diagnostics + .iter() + .any(|diagnostic| diagnostic.id == "MQD-DOC-004")); +} + +#[test] +fn long_functions_use_warning_ratio_and_h3_reading_sections() { + let assignments = "**甲 = x**\n\n**乙 = 甲**\n\n**丙 = 乙**\n\n**丁 = 丙**\n\n**结果 = 丁**"; + let without_section = format!( + "## @exec 长函数\n\n`params(x: Int)`\n\n{assignments}\n\n*return 结果*\n" + ); + let with_section = format!( + "## @exec 长函数\n\n计算并返回结果。\n\n`params(x: Int)`\n\n### 计算阶段\n\n{assignments}\n\n返回整数结果。\n\n*return 结果*\n" + ); + let Some(long) = load(&without_section) else { return }; + let Some(sectioned) = load(&with_section) else { return }; + let long_diagnostics = diagnostics(&long); + assert_eq!( + long_diagnostics + .iter() + .find(|diagnostic| diagnostic.id == "MQD-DOC-003") + .unwrap() + .severity, + Severity::Warning + ); + assert!(long_diagnostics + .iter() + .any(|diagnostic| diagnostic.id == "MQD-DOC-004")); + assert!(!diagnostics(§ioned) + .iter() + .any(|diagnostic| diagnostic.id == "MQD-DOC-004")); + + let sectioned_metrics = metrics(§ioned); + assert_eq!(sectioned_metrics[0].heading_segment_count, 1); + assert_eq!(sectioned_metrics[0].n, 13); +} + +#[test] +fn carrier_markup_replacement_is_metric_and_doc_rule_neutral() { + let sources = [ + "## @exec 载体\n\n计算输入。\n\n`params(x: Int)`\n\n**结果 = x**\n\n返回结果。\n\n*return 结果*\n", + "## @exec 载体\n\n计算输入。\n\n`params(x: Int)`\n\n*结果 = x*\n\n返回结果。\n\n`return 结果`\n", + "## @exec 载体\n\n计算输入。\n\n`params(x: Int)`\n\n`结果 = x`\n\n返回结果。\n\n**return 结果**\n", + ]; + let mut expected = None; + for source in sources { + let Some(project) = load(source) else { return }; + let current_metrics = metrics(&project); + let current_rules: Vec<_> = diagnostics(&project) + .into_iter() + .map(|diagnostic| (diagnostic.id, diagnostic.severity)) + .collect(); + let current = ( + current_metrics[0].n, + current_metrics[0].e, + current_metrics[0].statement_count, + current_rules, + ); + if let Some(expected) = &expected { + assert_eq!(¤t, expected); + } else { + expected = Some(current); + } + } +} + +#[test] +fn zero_denominator_is_explicitly_not_applicable() { + let source = "## @exec 空函数\n"; + let Some(project) = load(source) else { return }; + let metrics = metrics(&project); + assert_eq!(metrics.len(), 1); + assert_eq!((metrics[0].n, metrics[0].e), (0, 0)); + assert_eq!(metrics[0].ratio, None); + assert_eq!(metrics[0].status, NarrativeStatus::NotApplicable); + assert!(!diagnostics(&project) + .iter() + .any(|diagnostic| diagnostic.id == "MQD-DOC-003")); +} + +#[test] +fn repeated_long_prose_is_reported_conservatively_as_coverage_data() { + let source = "## @exec 重复\n\n这是完全重复且足够长的说明。\n\n这是完全重复且足够长的说明。\n\n`params(x: Int)`\n\n**结果 = x**\n\n返回结果。\n\n*return 结果*\n"; + let Some(project) = load(source) else { return }; + let metrics = metrics(&project); + assert_eq!(metrics[0].coverage.repeated_prose_spans.len(), 1); +}