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()
}
+53
View File
@@ -0,0 +1,53 @@
use serde::{Deserialize, Serialize};
use crate::{
model::Span,
rules::{self, FixSafety, Severity},
};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Diagnostic {
pub id: String,
pub severity: Severity,
pub span: Span,
#[serde(default)]
pub related_spans: Vec<Span>,
pub message: String,
pub reason: String,
pub suggestion: String,
pub fix_safety: FixSafety,
#[serde(skip_serializing_if = "Option::is_none")]
pub function: Option<String>,
}
impl Diagnostic {
pub fn new(id: &str, span: Span) -> Self {
let spec = rules::find(id).expect("诊断必须使用已登记 Rule ID");
Self {
id: id.to_string(),
severity: spec.default_severity,
span,
related_spans: Vec::new(),
message: spec.summary.to_string(),
reason: spec.reason.to_string(),
suggestion: spec.suggestion.to_string(),
fix_safety: spec.fix_safety,
function: None,
}
}
pub fn with_related(mut self, span: Span) -> Self {
self.related_spans.push(span);
self
}
pub fn with_function(mut self, function: &str) -> Self {
self.function = Some(function.to_string());
self
}
pub fn with_message(mut self, message: impl Into<String>) -> Self {
self.message = message.into();
self
}
}
+2
View File
@@ -1,3 +1,5 @@
pub mod alignment;
pub mod diagnostics;
pub mod error;
pub mod input;
pub mod model;
+329
View File
@@ -0,0 +1,329 @@
use serde_json::Value;
use crate::{
alignment::{align_function, node_span, ControlKind, ControlLayout, ReadableControlTree},
diagnostics::Diagnostic,
input::SourceDocument,
model::{AnalysisFunction, MarkdownTree, NodeId},
};
pub fn check_document(document: &SourceDocument) -> Vec<Diagnostic> {
let Some(module) = &document.module else {
return Vec::new();
};
let mut diagnostics = Vec::new();
for function in &module.functions {
diagnostics.extend(check_function(&document.markdown, function));
}
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(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> Vec<Diagnostic> {
let tree = align_function(markdown, analysis);
if !tree.complete {
return Vec::new();
}
let mut diagnostics = Vec::new();
for (index, control) in tree.controls.iter().enumerate() {
match control.kind {
ControlKind::Branch => {
branch_rules(markdown, analysis, &tree, control, &mut diagnostics)
}
ControlKind::Loop => {
loop_rules(markdown, analysis, &tree, control, &mut diagnostics)
}
}
nesting_rule(markdown, &tree, index, &mut diagnostics);
end_rule(markdown, &tree, control, &mut diagnostics);
}
diagnostics.sort_by(|left, right| {
(left.span.start, left.span.end, &left.id).cmp(&(
right.span.start,
right.span.end,
&right.id,
))
});
diagnostics
}
fn branch_rules(
markdown: &MarkdownTree,
analysis: &AnalysisFunction,
tree: &ReadableControlTree,
control: &ControlLayout,
diagnostics: &mut Vec<Diagnostic>,
) {
let opener_item = markdown.nearest(control.opener.node, "item");
let else_item = control
.else_carrier
.as_ref()
.and_then(|carrier| markdown.nearest(carrier.node, "item"));
if let (Some(item), Some(else_carrier), Some(other)) = (
opener_item,
control.else_carrier.as_ref(),
else_item,
) {
if item == other {
diagnostics.push(
Diagnostic::new("MQD-BRANCH-001", markdown.nodes[item].span)
.with_related(control.opener.span)
.with_related(else_carrier.span)
.with_function(&tree.function_name),
);
return;
}
}
for carrier in std::iter::once(&control.opener).chain(control.else_carrier.iter()) {
let valid = markdown.nearest(carrier.node, "item").is_some_and(|item| {
markdown
.nearest(item, "list")
.is_some_and(|list| markdown.nodes[list].ordered == Some(true))
&& markdown.first_carrier_in_item(item).map(|first| first.node)
== Some(carrier.node)
});
if !valid {
let mut diagnostic = Diagnostic::new("MQD-BRANCH-002", carrier.span)
.with_function(&tree.function_name);
if let Some(item) = markdown.nearest(carrier.node, "item") {
diagnostic = diagnostic.with_related(markdown.nodes[item].span);
}
diagnostics.push(diagnostic);
}
}
if let Some(else_carrier) = &control.else_carrier {
if let (Some(if_item), Some(else_item)) = (opener_item, else_item) {
if !are_adjacent_ordered_siblings(markdown, if_item, else_item) {
diagnostics.push(
Diagnostic::new("MQD-BRANCH-003", control.opener.span)
.with_related(else_carrier.span)
.with_function(&tree.function_name),
);
}
}
}
if !branch_is_nontrivial(analysis, control) {
return;
}
for carrier in std::iter::once(&control.opener).chain(control.else_carrier.iter()) {
let Some(item) = markdown.nearest(carrier.node, "item") else {
continue;
};
if !item_has_prose_after(markdown, control.function, item, carrier.span.end) {
diagnostics.push(
Diagnostic::new("MQD-BRANCH-004", carrier.span)
.with_related(markdown.nodes[item].span)
.with_function(&tree.function_name),
);
}
}
}
fn loop_rules(
markdown: &MarkdownTree,
analysis: &AnalysisFunction,
tree: &ReadableControlTree,
control: &ControlLayout,
diagnostics: &mut Vec<Diagnostic>,
) {
let item = markdown.nearest(control.opener.node, "item");
let valid = item.is_some_and(|item| {
markdown
.nearest(item, "list")
.is_some_and(|list| markdown.nodes[list].ordered == Some(false))
&& markdown.first_carrier_in_item(item).map(|first| first.node)
== Some(control.opener.node)
});
if !valid {
diagnostics.push(
Diagnostic::new("MQD-LOOP-001", control.opener.span)
.with_function(&tree.function_name),
);
}
let Some(item) = item else {
return;
};
if loop_contains_statements(analysis, control)
&& !item_has_prose_after(markdown, control.function, item, control.opener.span.end)
{
diagnostics.push(
Diagnostic::new("MQD-LOOP-002", control.opener.span)
.with_related(markdown.nodes[item].span)
.with_function(&tree.function_name),
);
}
}
fn nesting_rule(
markdown: &MarkdownTree,
tree: &ReadableControlTree,
index: usize,
diagnostics: &mut Vec<Diagnostic>,
) {
let control = &tree.controls[index];
let visual_parent = tree
.controls
.iter()
.enumerate()
.filter(|(candidate, parent)| {
*candidate != index
&& parent.end.as_ref().is_some_and(|end| {
control.opener.span.start > parent.opener.span.end
&& control.opener.span.start < end.span.start
})
&& visual_container(markdown, parent).is_some_and(|container| {
markdown.is_descendant(control.opener.node, container)
})
})
.max_by_key(|(_, parent)| parent.opener.span.start)
.map(|(candidate, _)| candidate);
if visual_parent != control.parent {
let mut diagnostic = Diagnostic::new("MQD-LOOP-003", control.opener.span)
.with_function(&tree.function_name);
if let Some(parent) = control.parent {
diagnostic = diagnostic.with_related(tree.controls[parent].opener.span);
}
diagnostics.push(diagnostic);
}
}
fn end_rule(
markdown: &MarkdownTree,
tree: &ReadableControlTree,
control: &ControlLayout,
diagnostics: &mut Vec<Diagnostic>,
) {
let Some(end) = &control.end else {
return;
};
let detached = match control.kind {
ControlKind::Branch => {
let opener_item = markdown.nearest(control.opener.node, "item");
let else_item = control
.else_carrier
.as_ref()
.and_then(|carrier| markdown.nearest(carrier.node, "item"));
if opener_item.is_some() && opener_item == else_item {
false
} else {
opener_item
.and_then(|item| markdown.nearest(item, "list"))
.is_some_and(|list| markdown.is_descendant(end.node, list))
}
}
ControlKind::Loop => markdown.nearest(control.opener.node, "item").is_some_and(|item| {
markdown.nearest(end.node, "item") != Some(item)
|| markdown
.item_carriers(item)
.into_iter()
.max_by_key(|carrier| carrier.span.start)
.map(|carrier| carrier.node)
!= Some(end.node)
}),
};
if detached {
diagnostics.push(
Diagnostic::new("MQD-CTRL-001", end.span)
.with_related(control.opener.span)
.with_function(&tree.function_name),
);
}
}
fn are_adjacent_ordered_siblings(
markdown: &MarkdownTree,
if_item: NodeId,
else_item: NodeId,
) -> bool {
let (Some(if_list), Some(else_list)) = (
markdown.nearest(if_item, "list"),
markdown.nearest(else_item, "list"),
) else {
return false;
};
if if_list != else_list || markdown.nodes[if_list].ordered != Some(true) {
return false;
}
let items: Vec<_> = markdown.nodes[if_list]
.children
.iter()
.copied()
.filter(|node| markdown.nodes[*node].kind == "item")
.collect();
let (Some(if_index), Some(else_index)) = (
items.iter().position(|node| *node == if_item),
items.iter().position(|node| *node == else_item),
) else {
return false;
};
else_index == if_index + 1
}
fn visual_container(markdown: &MarkdownTree, control: &ControlLayout) -> Option<NodeId> {
let item = markdown.nearest(control.opener.node, "item")?;
if control.kind == ControlKind::Branch {
if let Some(else_carrier) = &control.else_carrier {
let else_item = markdown.nearest(else_carrier.node, "item")?;
if are_adjacent_ordered_siblings(markdown, item, else_item) {
return markdown.nearest(item, "list");
}
}
}
Some(item)
}
fn item_has_prose_after(
markdown: &MarkdownTree,
function: NodeId,
item: NodeId,
start: usize,
) -> bool {
markdown.prose_fragments(function).into_iter().any(|fragment| {
fragment.span.start >= start
&& markdown.nearest(fragment.node, "item") == Some(item)
&& !fragment.text.trim().is_empty()
})
}
fn semantic_control<'a>(
analysis: &'a AnalysisFunction,
control: &ControlLayout,
) -> Option<&'a Value> {
let expected = match control.kind {
ControlKind::Branch => "branch",
ControlKind::Loop => "loop",
};
crate::model::semantic_nodes(&analysis.body).find(|node| {
node.get("kind").and_then(Value::as_str) == Some(expected)
&& node_span(node) == control.semantic_span
})
}
fn branch_is_nontrivial(analysis: &AnalysisFunction, control: &ControlLayout) -> bool {
semantic_control(analysis, control)
.and_then(|node| node.get("arms"))
.and_then(Value::as_array)
.is_some_and(|arms| {
arms.iter().any(|arm| {
arm.get("body")
.and_then(Value::as_array)
.is_some_and(|body| !body.is_empty())
})
})
}
fn loop_contains_statements(analysis: &AnalysisFunction, control: &ControlLayout) -> bool {
semantic_control(analysis, control)
.and_then(|node| node.get("body"))
.and_then(Value::as_array)
.is_some_and(|body| !body.is_empty())
}
+4
View File
@@ -1,3 +1,7 @@
mod control;
pub use control::{check_document, check_function};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]