feat: align ordered branch arms and nearest-loop transfers
This commit is contained in:
1 parent
bcd07a43af
commit
7282918c50
8 files changed
+717
-319
No files matched your search
+83
-225
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::model::{body, node_span, span_value, NodeId, Span, Statement, StatementKind};
|
||||
|
||||
use super::{
|
||||
at,
|
||||
source::{LocatedCarrier, SourceIndex},
|
||||
ArmRole, BodyOwner, BodyStatement, ControlKind, JumpKind, JumpLayout, ReadableControlTree,
|
||||
};
|
||||
|
||||
pub(super) fn align(
|
||||
body: &[Value],
|
||||
source: &SourceIndex<'_>,
|
||||
tree: &mut ReadableControlTree,
|
||||
) -> Result<(), String> {
|
||||
let mut matcher = Matcher {
|
||||
source,
|
||||
tree,
|
||||
matched: HashSet::new(),
|
||||
};
|
||||
matcher.align_body(body, None, None)?;
|
||||
if let Some(control) = matcher
|
||||
.tree
|
||||
.controls
|
||||
.iter()
|
||||
.find(|control| control.semantic_span.is_none())
|
||||
{
|
||||
return Err(at(control.opener.span, "控制头没有对应的 Analysis 语句"));
|
||||
}
|
||||
if let Some(jump) = source
|
||||
.jumps
|
||||
.iter()
|
||||
.find(|carrier| !matcher.matched.contains(&carrier.node))
|
||||
{
|
||||
return Err(at(jump.span, "循环跳转没有对应的 Analysis 语句"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Matcher<'a, 'source> {
|
||||
source: &'a SourceIndex<'source>,
|
||||
tree: &'a mut ReadableControlTree,
|
||||
matched: HashSet<NodeId>,
|
||||
}
|
||||
|
||||
impl<'a, 'source> Matcher<'a, 'source> {
|
||||
fn align_body(
|
||||
&mut self,
|
||||
nodes: &[Value],
|
||||
owner: Option<BodyOwner>,
|
||||
nearest_loop: Option<usize>,
|
||||
) -> Result<(), String> {
|
||||
let mut previous = None;
|
||||
for node in nodes {
|
||||
let statement = Statement::read(node)?;
|
||||
let located = self.locate(statement)?;
|
||||
let carrier = located.carrier;
|
||||
if located.owner != owner {
|
||||
return Err(at(carrier.span, "源载体所属语句体与 Analysis 不一致"));
|
||||
}
|
||||
if previous.is_some_and(|last| last >= carrier.span.start)
|
||||
|| !self.matched.insert(carrier.node)
|
||||
{
|
||||
return Err(at(carrier.span, "Analysis 语句关联重复或顺序不一致"));
|
||||
}
|
||||
previous = Some(carrier.span.start);
|
||||
if let Some(owner) = owner {
|
||||
let control = &mut self.tree.controls[owner.control];
|
||||
let body = match owner.arm {
|
||||
Some(arm) => &mut control.arms[arm].body,
|
||||
None => &mut control.body,
|
||||
};
|
||||
body.push(BodyStatement {
|
||||
kind: statement.kind,
|
||||
carrier: carrier.clone(),
|
||||
});
|
||||
}
|
||||
match statement.kind {
|
||||
StatementKind::Branch => {
|
||||
let index = located.control.expect("matched branch header");
|
||||
self.tree.controls[index].semantic_span = Some(statement.span);
|
||||
self.align_arms(index, node, nearest_loop)?;
|
||||
}
|
||||
StatementKind::Loop => {
|
||||
let index = located.control.expect("matched loop header");
|
||||
self.tree.controls[index].semantic_span = Some(statement.span);
|
||||
let children =
|
||||
body(node).ok_or_else(|| at(statement.span, "loop 缺少 body"))?;
|
||||
self.align_body(
|
||||
children,
|
||||
Some(BodyOwner {
|
||||
control: index,
|
||||
arm: None,
|
||||
}),
|
||||
Some(index),
|
||||
)?;
|
||||
}
|
||||
StatementKind::Break | StatementKind::Continue => {
|
||||
let (Some(parent), Some(target_loop), Some(kind)) =
|
||||
(owner, nearest_loop, located.jump)
|
||||
else {
|
||||
return Err(at(carrier.span, "循环跳转缺少最近的循环目标"));
|
||||
};
|
||||
if carrier.heading != Some(self.tree.controls[target_loop].heading) {
|
||||
return Err(at(carrier.span, "循环跳转与目标循环跨 heading 段"));
|
||||
}
|
||||
self.tree.jumps.push(JumpLayout {
|
||||
kind,
|
||||
carrier: carrier.clone(),
|
||||
parent,
|
||||
target_loop,
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn locate(&self, statement: Statement<'_>) -> Result<&'a LocatedCarrier<'source>, String> {
|
||||
let kind = statement.kind;
|
||||
let condition_span = match kind {
|
||||
StatementKind::Branch => span_value(&statement.value["arms"][0]["condition_span"]),
|
||||
StatementKind::Loop => span_value(&statement.value["condition_span"]),
|
||||
_ => None,
|
||||
};
|
||||
let index = self.source;
|
||||
let eligible = |located: &&LocatedCarrier<'_>| match kind {
|
||||
StatementKind::Branch => located
|
||||
.control
|
||||
.is_some_and(|control| self.tree.controls[control].kind == ControlKind::Branch),
|
||||
StatementKind::Loop => located
|
||||
.control
|
||||
.is_some_and(|control| self.tree.controls[control].kind == ControlKind::Loop),
|
||||
StatementKind::Break => located.jump == Some(JumpKind::Break),
|
||||
StatementKind::Continue => located.jump == Some(JumpKind::Continue),
|
||||
_ => located.ordinary,
|
||||
};
|
||||
let primary = index.at(statement.span).filter(eligible);
|
||||
let condition = condition_span
|
||||
.filter(|span| *span != statement.span)
|
||||
.and_then(|span| index.at(span))
|
||||
.filter(eligible);
|
||||
match (primary, condition) {
|
||||
(Some(located), None) | (None, Some(located)) => Ok(located),
|
||||
_ => Err(at(
|
||||
statement.span,
|
||||
&format!("{kind:?} 无法唯一对应本函数的执行载体"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn align_arms(
|
||||
&mut self,
|
||||
index: usize,
|
||||
branch: &Value,
|
||||
nearest_loop: Option<usize>,
|
||||
) -> Result<(), String> {
|
||||
let arms = branch["arms"].as_array().ok_or("branch 缺少 arms")?;
|
||||
let control = &self.tree.controls[index];
|
||||
let source_arms = &control.arms;
|
||||
let omitted_else = source_arms.len() == arms.len() + 1
|
||||
&& source_arms
|
||||
.last()
|
||||
.is_some_and(|arm| arm.role == ArmRole::Else)
|
||||
&& !self.source.nonempty_bodies.contains(&BodyOwner {
|
||||
control: index,
|
||||
arm: Some(arms.len()),
|
||||
});
|
||||
if source_arms.len() != arms.len() && !omitted_else {
|
||||
return Err(at(control.opener.span, "分支臂数量与 Analysis 不一致"));
|
||||
}
|
||||
let mut used_spans = HashSet::new();
|
||||
for (position, arm) in arms.iter().enumerate() {
|
||||
let source_arm = &source_arms[position];
|
||||
let carrier = &source_arm.carrier;
|
||||
let span =
|
||||
node_span(arm).ok_or_else(|| at(carrier.span, "Analysis 分支臂缺少 span"))?;
|
||||
let condition = span_value(&arm["condition_span"]);
|
||||
let legacy = position == 1
|
||||
&& source_arms.len() == 2
|
||||
&& source_arm.role == ArmRole::Else
|
||||
&& is_legacy_else(&arms[0], arm);
|
||||
if self.source.at(carrier.span).is_none() {
|
||||
return Err(at(carrier.span, "源码分支臂无法唯一对应载体"));
|
||||
}
|
||||
if !legacy {
|
||||
let anchors = [Some(span), condition.filter(|condition| *condition != span)];
|
||||
let mut matches = false;
|
||||
for anchor in anchors.into_iter().flatten() {
|
||||
if !used_spans.insert(anchor) {
|
||||
return Err(at(carrier.span, "Analysis 分支臂 span 重复"));
|
||||
}
|
||||
matches |= anchor == carrier.span;
|
||||
}
|
||||
if !matches {
|
||||
return Err(at(carrier.span, "Analysis 分支臂与载体的位置或顺序不一致"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (position, arm) in arms.iter().enumerate() {
|
||||
self.tree.controls[index].arms[position].analysis_index = Some(position);
|
||||
let children = body(arm).ok_or("Analysis 分支臂缺少 body")?;
|
||||
let owner = BodyOwner {
|
||||
control: index,
|
||||
arm: Some(position),
|
||||
};
|
||||
self.align_body(children, Some(owner), nearest_loop)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn is_legacy_else(first: &Value, last: &Value) -> bool {
|
||||
let condition = &last["condition"];
|
||||
let Some(first_span) = node_span(first) else {
|
||||
return false;
|
||||
};
|
||||
node_span(last) == Some(first_span)
|
||||
&& span_value(&last["condition_span"]) == Some(first_span)
|
||||
&& span_value(&first["condition_span"]) == Some(first_span)
|
||||
&& body(last).is_some_and(|body| !body.is_empty())
|
||||
&& condition["kind"] == "literal"
|
||||
&& condition["type"] == "bool"
|
||||
&& condition["value"] == true
|
||||
&& node_span(condition) == Some(Span::new(0, 0))
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::model::{Carrier, MarkdownTree, NodeId, Span};
|
||||
|
||||
use super::{
|
||||
at, ArmRole, BodyOwner, BranchArm, ControlKind, ControlLayout, JumpKind, ReadableControlTree,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct LocatedCarrier<'a> {
|
||||
pub carrier: &'a Carrier,
|
||||
pub owner: Option<BodyOwner>,
|
||||
pub control: Option<usize>,
|
||||
pub jump: Option<JumpKind>,
|
||||
pub ordinary: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct SourceIndex<'a> {
|
||||
pub carriers: HashMap<Span, Vec<LocatedCarrier<'a>>>,
|
||||
pub nonempty_bodies: HashSet<BodyOwner>,
|
||||
pub jumps: Vec<&'a Carrier>,
|
||||
}
|
||||
|
||||
impl<'a> SourceIndex<'a> {
|
||||
pub fn at(&self, span: Span) -> Option<&LocatedCarrier<'a>> {
|
||||
match self.carriers.get(&span)?.as_slice() {
|
||||
[located] => Some(located),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn scan<'a>(
|
||||
markdown: &'a MarkdownTree,
|
||||
function: NodeId,
|
||||
tree: &mut ReadableControlTree,
|
||||
) -> SourceIndex<'a> {
|
||||
let mut source = SourceIndex::default();
|
||||
let mut stack: Vec<BodyOwner> = Vec::new();
|
||||
let mut heading = None;
|
||||
for carrier in markdown
|
||||
.carriers
|
||||
.iter()
|
||||
.filter(|carrier| carrier.function == Some(function))
|
||||
{
|
||||
if heading != carrier.heading {
|
||||
if !stack.is_empty() {
|
||||
tree.issues.push(at(carrier.span, "控制载体跨 heading 段"));
|
||||
stack.clear();
|
||||
}
|
||||
heading = carrier.heading;
|
||||
}
|
||||
let mut located = LocatedCarrier {
|
||||
carrier,
|
||||
owner: stack.last().copied(),
|
||||
control: None,
|
||||
jump: None,
|
||||
ordinary: false,
|
||||
};
|
||||
match Keyword::classify(&carrier.payload) {
|
||||
Keyword::Open(kind) => {
|
||||
let index = tree.controls.len();
|
||||
let arms = if kind == ControlKind::Branch {
|
||||
vec![branch_arm(ArmRole::If, carrier)]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
tree.controls.push(ControlLayout {
|
||||
kind,
|
||||
function,
|
||||
heading: carrier.heading.expect("Exec 函数载体必有 heading"),
|
||||
opener: carrier.clone(),
|
||||
arms,
|
||||
end: None,
|
||||
parent: located.owner,
|
||||
children: Vec::new(),
|
||||
semantic_span: None,
|
||||
body: Vec::new(),
|
||||
});
|
||||
if let Some(owner) = located.owner {
|
||||
tree.controls[owner.control].children.push(index);
|
||||
source.nonempty_bodies.insert(owner);
|
||||
}
|
||||
located.control = Some(index);
|
||||
stack.push(BodyOwner {
|
||||
control: index,
|
||||
arm: (kind == ControlKind::Branch).then_some(0),
|
||||
});
|
||||
}
|
||||
Keyword::Arm(role) => {
|
||||
let Some(open) = stack.last_mut() else {
|
||||
tree.issues
|
||||
.push(at(carrier.span, "else/else if 没有对应的 if"));
|
||||
continue;
|
||||
};
|
||||
let control = &mut tree.controls[open.control];
|
||||
if control.kind != ControlKind::Branch
|
||||
|| control
|
||||
.arms
|
||||
.last()
|
||||
.is_some_and(|arm| arm.role == ArmRole::Else)
|
||||
{
|
||||
tree.issues
|
||||
.push(at(carrier.span, "else/else if 与当前分支无法对齐"));
|
||||
continue;
|
||||
}
|
||||
open.arm = Some(control.arms.len());
|
||||
control.arms.push(branch_arm(role, carrier));
|
||||
}
|
||||
Keyword::End => {
|
||||
let Some(open) = stack.pop() else {
|
||||
tree.issues.push(at(carrier.span, "end 没有对应的控制头"));
|
||||
continue;
|
||||
};
|
||||
tree.controls[open.control].end = Some(carrier.clone());
|
||||
}
|
||||
keyword => {
|
||||
if let Some(owner) = located.owner {
|
||||
source.nonempty_bodies.insert(owner);
|
||||
}
|
||||
if let Keyword::Jump(kind) = keyword {
|
||||
located.jump = Some(kind);
|
||||
source.jumps.push(carrier);
|
||||
} else {
|
||||
located.ordinary = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
source
|
||||
.carriers
|
||||
.entry(carrier.span)
|
||||
.or_default()
|
||||
.push(located);
|
||||
}
|
||||
if let Some(open) = stack.last() {
|
||||
tree.issues.push(at(
|
||||
tree.controls[open.control].opener.span,
|
||||
"控制载体没有完整的 end 配对",
|
||||
));
|
||||
}
|
||||
source
|
||||
}
|
||||
|
||||
fn branch_arm(role: ArmRole, carrier: &Carrier) -> BranchArm {
|
||||
BranchArm {
|
||||
role,
|
||||
carrier: carrier.clone(),
|
||||
analysis_index: None,
|
||||
body: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
enum Keyword {
|
||||
Open(ControlKind),
|
||||
Arm(ArmRole),
|
||||
End,
|
||||
Jump(JumpKind),
|
||||
Other,
|
||||
}
|
||||
|
||||
impl Keyword {
|
||||
fn classify(payload: &str) -> Self {
|
||||
match payload.trim() {
|
||||
"else" => Self::Arm(ArmRole::Else),
|
||||
"end" => Self::End,
|
||||
"break" => Self::Jump(JumpKind::Break),
|
||||
"continue" => Self::Jump(JumpKind::Continue),
|
||||
trimmed => {
|
||||
let mut words = trimmed.split_whitespace();
|
||||
match (words.next(), words.next()) {
|
||||
(Some("if"), Some(_)) => Self::Open(ControlKind::Branch),
|
||||
(Some("while"), Some(_)) => Self::Open(ControlKind::Loop),
|
||||
(Some("else"), Some("if")) if words.next().is_some() => {
|
||||
Self::Arm(ArmRole::ElseIf)
|
||||
}
|
||||
_ => Self::Other,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user