feat: align ordered branch arms and nearest-loop transfers

This commit is contained in:
cflmy committed 2026-11-23 23:46:49 +08:00
1 parent bcd07a43af
commit 7282918c50
8 files changed
+717 -319

No files matched your search

+83 -225
View File
@@ -1,6 +1,9 @@
use serde_json::Value;
mod semantic;
mod source;
use crate::model::{span_value, statements, AnalysisFunction, Carrier, MarkdownTree, NodeId, Span};
use crate::model::{
statements, AnalysisFunction, Carrier, MarkdownTree, NodeId, Span, StatementKind,
};
pub use crate::model::node_span;
@@ -10,17 +13,68 @@ pub enum ControlKind {
Loop,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArmRole {
If,
ElseIf,
Else,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BodyOwner {
pub control: usize,
pub arm: Option<usize>,
}
#[derive(Debug, Clone)]
pub struct BranchArm {
pub role: ArmRole,
pub carrier: Carrier,
pub analysis_index: Option<usize>,
pub(crate) body: Vec<BodyStatement>,
}
#[derive(Debug, Clone)]
pub(crate) struct BodyStatement {
pub kind: StatementKind,
pub carrier: Carrier,
}
#[derive(Debug, Clone)]
pub struct ControlLayout {
pub kind: ControlKind,
pub function: NodeId,
pub heading: NodeId,
pub opener: Carrier,
pub else_carrier: Option<Carrier>,
pub arms: Vec<BranchArm>,
pub end: Option<Carrier>,
pub parent: Option<usize>,
pub parent: Option<BodyOwner>,
pub children: Vec<usize>,
pub semantic_span: Option<Span>,
pub(crate) body: Vec<BodyStatement>,
}
impl ControlLayout {
pub(crate) fn else_carrier(&self) -> Option<&Carrier> {
self.arms
.last()
.filter(|arm| arm.role == ArmRole::Else)
.map(|arm| &arm.carrier)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JumpKind {
Break,
Continue,
}
#[derive(Debug, Clone)]
pub struct JumpLayout {
pub kind: JumpKind,
pub carrier: Carrier,
pub parent: BodyOwner,
pub target_loop: usize,
}
#[derive(Debug, Clone)]
@@ -28,6 +82,7 @@ pub struct ReadableControlTree {
pub function: Option<NodeId>,
pub function_name: String,
pub controls: Vec<ControlLayout>,
pub jumps: Vec<JumpLayout>,
pub complete: bool,
pub issues: Vec<String>,
}
@@ -39,238 +94,41 @@ impl ReadableControlTree {
}
pub fn align_function(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> ReadableControlTree {
let function = markdown.headings.iter().find(|heading| {
let mut tree = ReadableControlTree {
function: None,
function_name: analysis.local_name.clone(),
controls: Vec::new(),
jumps: Vec::new(),
complete: false,
issues: Vec::new(),
};
let mut headings = markdown.headings.iter().filter(|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()
let function = match (headings.next(), headings.next()) {
(Some(heading), None) => heading.node,
_ => {
tree.issues.push(at(
analysis.heading_span,
"Analysis heading_span 无法唯一对应 Exec H2",
));
continue;
return tree;
}
let (index, node) = candidates[0];
// The frozen core omits an explicitly empty else arm from Analysis.
if node.arm_count.is_some_and(|count| match count {
1 => false,
2 => control.else_carrier.is_none(),
_ => true,
}) {
tree.issues.push("分支臂数量与 Analysis 不一致".into());
}
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.function = Some(function);
let source = source::scan(markdown, function, &mut tree);
if tree.issues.is_empty() {
if let Err(issue) = semantic::align(&analysis.body, &source, &mut tree) {
tree.issues.push(issue);
}
}
tree.complete = tree.issues.is_empty();
tree
}
#[derive(Debug)]
struct SemanticControl {
kind: ControlKind,
span: Span,
condition_span: Option<Span>,
arm_count: Option<usize>,
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(span_value),
) else {
continue;
};
let index = controls.len();
controls.push(SemanticControl {
kind: if kind == "branch" {
ControlKind::Branch
} else {
ControlKind::Loop
},
span,
condition_span,
arm_count: node.get("arms").and_then(Value::as_array).map(Vec::len),
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
}
#[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,
}
}
fn at(span: Span, issue: &str) -> String {
format!("字节 [{}, {}):{issue}", span.start, span.end)
}
pub fn statement_count(analysis: &AnalysisFunction) -> usize {