306 lines
9.6 KiB
Rust
306 lines
9.6 KiB
Rust
use std::collections::BTreeMap;
|
||
|
||
use serde::{Deserialize, Serialize};
|
||
use unicode_general_category::{get_general_category, GeneralCategory};
|
||
use unicode_normalization::UnicodeNormalization;
|
||
|
||
use crate::{
|
||
alignment::statement_count,
|
||
input::SourceDocument,
|
||
model::{
|
||
effect_sites, statements, AnalysisCall, AnalysisFunction, Carrier, HeadingMode,
|
||
MarkdownTree, NodeId, ProseFragment, Span, StatementKind,
|
||
},
|
||
};
|
||
|
||
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_module_function(&document.markdown, function, &module.calls, config)
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
pub(crate) fn measure_module_function(
|
||
markdown: &MarkdownTree,
|
||
function: &AnalysisFunction,
|
||
calls: &[AnalysisCall],
|
||
config: NarrativeConfig,
|
||
) -> Option<FunctionNarrative> {
|
||
let mut metrics = measure_function(markdown, function, config)?;
|
||
metrics.has_explicit_effects |= effect_sites(function, calls).next().is_some();
|
||
Some(metrics)
|
||
}
|
||
|
||
pub fn measure_function(
|
||
markdown: &MarkdownTree,
|
||
analysis: &AnalysisFunction,
|
||
config: NarrativeConfig,
|
||
) -> Option<FunctionNarrative> {
|
||
let heading = markdown.function_segment(&analysis.id)?;
|
||
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 = prose
|
||
.iter()
|
||
.filter(|fragment| {
|
||
fragment.span.start >= markdown.nodes[function].span.end
|
||
&& carriers
|
||
.first()
|
||
.is_none_or(|first| fragment.span.end <= first.span.start)
|
||
&& narrative_count(&fragment.text) > 0
|
||
})
|
||
.map(|fragment| fragment.span)
|
||
.min_by_key(|span| span.start);
|
||
let last_return = statements(&analysis.body)
|
||
.filter(|statement| statement.kind == StatementKind::Return)
|
||
.map(|statement| statement.span)
|
||
.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 = statements(&analysis.body)
|
||
.any(|statement| matches!(statement.kind, StatementKind::Branch | StatementKind::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);
|
||
}
|
||
}
|