feat: align executable control flow with markdown

This commit is contained in:
cflmy committed 2026-11-23 17:13:44 +08:00
1 parent e67697be06
commit 0717216c9d
10 files changed
+922

No files matched your search

+275
View File
@@ -0,0 +1,275 @@
use serde_json::Value;
use crate::model::{semantic_nodes, AnalysisFunction, Carrier, MarkdownTree, NodeId, Span};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ControlKind {
Branch,
Loop,
}
#[derive(Debug, Clone)]
pub struct ControlLayout {
pub kind: ControlKind,
pub function: NodeId,
pub heading: NodeId,
pub opener: Carrier,
pub else_carrier: Option<Carrier>,
pub end: Option<Carrier>,
pub parent: Option<usize>,
pub children: Vec<usize>,
pub semantic_span: Option<Span>,
}
#[derive(Debug, Clone)]
pub struct ReadableControlTree {
pub function: Option<NodeId>,
pub function_name: String,
pub controls: Vec<ControlLayout>,
pub complete: bool,
pub issues: Vec<String>,
}
impl ReadableControlTree {
pub fn control(&self, index: usize) -> &ControlLayout {
&self.controls[index]
}
}
pub fn align_function(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> ReadableControlTree {
let function = markdown.headings.iter().find(|heading| {
heading.function == Some(heading.node)
&& markdown.nodes[heading.node].span == analysis.heading_span
});
let Some(function_heading) = function else {
return ReadableControlTree {
function: None,
function_name: analysis.local_name.clone(),
controls: Vec::new(),
complete: false,
issues: vec!["Analysis heading_span 无法唯一对应 Exec H2".into()],
};
};
let function = function_heading.node;
let carriers: Vec<_> = markdown
.carriers
.iter()
.filter(|carrier| carrier.function == Some(function))
.cloned()
.collect();
let semantic = semantic_controls(analysis);
let mut tree = ReadableControlTree {
function: Some(function),
function_name: analysis.local_name.clone(),
controls: Vec::new(),
complete: true,
issues: Vec::new(),
};
let mut stack: Vec<usize> = Vec::new();
let mut heading = None;
for carrier in carriers {
if heading != carrier.heading {
if !stack.is_empty() {
tree.issues.push("控制载体跨 heading 段".into());
stack.clear();
}
heading = carrier.heading;
}
let keyword = Keyword::classify(&carrier.payload);
match keyword {
Keyword::If | Keyword::While => {
let kind = if keyword == Keyword::If {
ControlKind::Branch
} else {
ControlKind::Loop
};
let parent = stack.last().copied();
let index = tree.controls.len();
tree.controls.push(ControlLayout {
kind,
function,
heading: carrier.heading.expect("Exec 函数载体必有 heading"),
opener: carrier,
else_carrier: None,
end: None,
parent,
children: Vec::new(),
semantic_span: None,
});
if let Some(parent) = parent {
tree.controls[parent].children.push(index);
}
stack.push(index);
}
Keyword::Else => {
let Some(open) = stack.last().copied() else {
tree.issues.push("else 没有对应的对齐 opener".into());
continue;
};
if tree.controls[open].kind != ControlKind::Branch
|| tree.controls[open].else_carrier.is_some()
{
tree.issues.push("else 与语义 opener 无法对齐".into());
continue;
}
tree.controls[open].else_carrier = Some(carrier);
}
Keyword::End => {
let Some(open) = stack.pop() else {
tree.issues.push("end 没有对应的对齐 opener".into());
continue;
};
tree.controls[open].end = Some(carrier);
}
Keyword::Other => {}
}
}
if !stack.is_empty() {
tree.issues.push("控制载体没有完整 end 配对".into());
}
let mut semantic_to_control = vec![None; semantic.len()];
for (control_index, control) in tree.controls.iter_mut().enumerate() {
let expected = control.kind;
let candidates: Vec<_> = semantic
.iter()
.enumerate()
.filter(|(_, node)| {
node.kind == expected
&& (node.span == control.opener.span
|| node.condition_span == Some(control.opener.span))
})
.collect();
if candidates.len() != 1 {
tree.issues.push(format!(
"{:?} opener [{}, {}) 与 Analysis 关联数量为 {}",
expected, control.opener.span.start, control.opener.span.end, candidates.len()
));
continue;
}
let (index, node) = candidates[0];
if semantic_to_control[index].is_some() {
tree.issues.push("多个载体复用了同一 Analysis 控制节点".into());
continue;
}
semantic_to_control[index] = Some(control_index);
control.semantic_span = Some(node.span);
}
if semantic_to_control.iter().any(Option::is_none) {
tree.issues.push("Analysis 中存在未对齐的控制节点".into());
}
for (semantic_index, control_index) in semantic_to_control.iter().enumerate() {
let Some(control_index) = control_index else {
continue;
};
let semantic_parent = semantic[semantic_index]
.parent
.and_then(|parent| semantic_to_control[parent]);
if semantic_parent != tree.controls[*control_index].parent {
tree.issues.push("源载体嵌套与 Analysis 控制嵌套不一致".into());
}
}
tree.complete = tree.issues.is_empty();
tree
}
#[derive(Debug)]
struct SemanticControl {
kind: ControlKind,
span: Span,
condition_span: Option<Span>,
parent: Option<usize>,
}
fn semantic_controls(analysis: &AnalysisFunction) -> Vec<SemanticControl> {
fn walk(body: &[Value], parent: Option<usize>, controls: &mut Vec<SemanticControl>) {
for node in body {
let Some(kind) = node.get("kind").and_then(Value::as_str) else {
continue;
};
if !matches!(kind, "branch" | "loop") {
continue;
}
let (Some(span), condition_span) = (
node_span(node),
node.get("condition_span").and_then(node_span),
) else {
continue;
};
let index = controls.len();
controls.push(SemanticControl {
kind: if kind == "branch" {
ControlKind::Branch
} else {
ControlKind::Loop
},
span,
condition_span,
parent,
});
if kind == "branch" {
for arm in node
.get("arms")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
if let Some(body) = arm.get("body").and_then(Value::as_array) {
walk(body, Some(index), controls);
}
}
} else if let Some(body) = node.get("body").and_then(Value::as_array) {
walk(body, Some(index), controls);
}
}
}
let mut controls = Vec::new();
walk(&analysis.body, None, &mut controls);
controls
}
pub fn node_span(node: &Value) -> Option<Span> {
let span = node.get("span")?;
Some(Span::new(
span.get("start")?.as_u64()? as usize,
span.get("end")?.as_u64()? as usize,
))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Keyword {
If,
Else,
While,
End,
Other,
}
impl Keyword {
fn classify(payload: &str) -> Self {
let trimmed = payload.trim();
if trimmed == "else" {
return Self::Else;
}
if trimmed == "end" {
return Self::End;
}
let mut words = trimmed.split_whitespace();
match (words.next(), words.next()) {
(Some("if"), Some(_)) => Self::If,
(Some("while"), Some(_)) => Self::While,
_ => Self::Other,
}
}
}
pub fn statement_count(analysis: &AnalysisFunction) -> usize {
semantic_nodes(&analysis.body)
.filter(|node| {
node.get("kind").and_then(Value::as_str).is_some_and(|kind| {
matches!(kind, "assign" | "expression" | "branch" | "loop" | "return")
})
})
.count()
}