feat: add narrative metrics and documentation rules

This commit is contained in:
cflmy committed 2026-11-23 17:22:14 +08:00
1 parent 0717216c9d
commit f26f6099f2
7 files changed
+615 -1

No files matched your search

+1
View File
@@ -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;
+299
View File
@@ -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<Span>,
pub result_anchor_span: Option<Span>,
pub result_span: Option<Span>,
pub repeated_prose_spans: Vec<Span>,
}
#[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<f64>,
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<FunctionNarrative> {
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<FunctionNarrative> {
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<Span> {
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<Span> {
let mut occurrences: BTreeMap<String, Vec<Span>> = BTreeMap::new();
for fragment in prose {
let normalized = fragment.text.nfc().collect::<String>();
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);
}
}
+20
View File
@@ -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<NodeId>, nodes: &mut Vec<MarkdownNode>) -> 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 == "重要"));
}
}
+4 -1
View File
@@ -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};
+93
View File
@@ -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<Diagnostic> {
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<Diagnostic> {
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
}
+2
View File
@@ -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};