feat: align executable control flow with markdown
This commit is contained in:
1 parent
e67697be06
commit
0717216c9d
10 files changed
+922
No files matched your search
@@ -6,6 +6,8 @@
|
||||
|
||||
`params(原价: Int, 是否会员: Bool)`
|
||||
|
||||
**最终价格 = 原价**
|
||||
|
||||
1. 首先判断用户是否有会员资格。
|
||||
|
||||
`if 是否会员`
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
|
||||
`params(原价: Int, 是否会员: Bool)`
|
||||
|
||||
**最终价格 = 原价**
|
||||
|
||||
1. `if 是否会员`:会员享受九折优惠。
|
||||
|
||||
为保持金额计算的确定性,先乘以九,再进行整数除法。
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
<h2>@exec 计算会员价格</h2>
|
||||
<p>根据用户的会员身份计算最终支付金额。</p>
|
||||
<p><code>params(原价: Int, 是否会员: Bool)</code></p>
|
||||
<p><strong>最终价格 = 原价</strong></p>
|
||||
<ol>
|
||||
<li>
|
||||
<p>首先判断用户是否有会员资格。</p>
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
<p>根据用户的会员身份计算最终支付金额。会员享受九折优惠,
|
||||
非会员维持原价。采用整数运算,避免金额处理中的浮点误差。</p>
|
||||
<p><code>params(原价: Int, 是否会员: Bool)</code></p>
|
||||
<p><strong>最终价格 = 原价</strong></p>
|
||||
<ol>
|
||||
<li>
|
||||
<p><code>if 是否会员</code>:会员享受九折优惠。</p>
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
pub mod alignment;
|
||||
pub mod diagnostics;
|
||||
pub mod error;
|
||||
pub mod input;
|
||||
pub mod model;
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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)]
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
use std::{fs, path::Path};
|
||||
|
||||
use marqdo_lint::{
|
||||
input::{AnalysisStatus, MarqdoRunner, ProjectInput},
|
||||
rules::check_document,
|
||||
};
|
||||
|
||||
fn load(source: &str) -> Option<ProjectInput> {
|
||||
let binary = std::env::var("MARQDO_BIN").ok().or_else(|| {
|
||||
eprintln!("MARQDO_BIN 未设置,跳过冻结核心控制规则测试");
|
||||
None
|
||||
})?;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("case.mq.md");
|
||||
fs::write(&path, source).unwrap();
|
||||
let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap();
|
||||
Some(ProjectInput::load(path, &runner).unwrap())
|
||||
}
|
||||
|
||||
fn load_example(path: &str) -> Option<ProjectInput> {
|
||||
let binary = std::env::var("MARQDO_BIN").ok().or_else(|| {
|
||||
eprintln!("MARQDO_BIN 未设置,跳过冻结核心控制规则测试");
|
||||
None
|
||||
})?;
|
||||
let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap();
|
||||
Some(
|
||||
ProjectInput::load(
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join(path),
|
||||
&runner,
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
fn ids(project: &ProjectInput) -> Vec<String> {
|
||||
let mut ids: Vec<_> = project
|
||||
.documents
|
||||
.iter()
|
||||
.flat_map(|document| check_document(document))
|
||||
.map(|diagnostic| diagnostic.id)
|
||||
.collect();
|
||||
ids.sort();
|
||||
ids
|
||||
}
|
||||
|
||||
fn assert_complete(project: &ProjectInput) {
|
||||
assert_eq!(
|
||||
project.analysis_status,
|
||||
AnalysisStatus::Complete,
|
||||
"{}",
|
||||
project.core_output
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_has(project: &ProjectInput, expected: &str) {
|
||||
assert_complete(project);
|
||||
assert!(
|
||||
ids(project).iter().any(|id| id == expected),
|
||||
"缺少 {expected},实际为 {:?}",
|
||||
ids(project)
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_no_control_rules(project: &ProjectInput) {
|
||||
assert_complete(project);
|
||||
assert_eq!(ids(project), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_core_analysis_golden_passes_without_running_core() {
|
||||
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/golden");
|
||||
let source = marqdo_lint::model::SourceSnapshot::load(directory.join("branches.mq.md"))
|
||||
.unwrap();
|
||||
let ast: serde_json::Value =
|
||||
serde_json::from_slice(&fs::read(directory.join("branches.ast.json")).unwrap()).unwrap();
|
||||
let markdown = marqdo_lint::model::MarkdownTree::from_json(ast["ast"].clone(), &source)
|
||||
.unwrap();
|
||||
let raw = serde_json::from_slice(&fs::read(directory.join("branches.analysis.json")).unwrap())
|
||||
.unwrap();
|
||||
let analysis = marqdo_lint::model::ExecutionProjection::from_json(raw).unwrap();
|
||||
let module = analysis
|
||||
.modules
|
||||
.into_iter()
|
||||
.find(|module| module.source_digest == source.digest_hex())
|
||||
.unwrap();
|
||||
let document = marqdo_lint::input::SourceDocument {
|
||||
source,
|
||||
markdown,
|
||||
markdown_origin: marqdo_lint::input::MarkdownOrigin::MarqdoInspect,
|
||||
module: Some(module),
|
||||
};
|
||||
assert!(check_document(&document).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t01_and_t19_branch_siblings_pass_in_h2_and_h3_segments() {
|
||||
for heading in ["## @exec 判断", "## @exec 判断\n\n### 处理分支"] {
|
||||
let source = format!(
|
||||
"{heading}\n\n说明判断含义。\n\n`params(x: Int)`\n\n**结果 = 0**\n\n1. `if x > 0`:正数返回一。\n\n **结果 = 1**\n\n2. `else`:其他返回零。\n\n **结果 = 0**\n\n`end`\n\n*return 结果*\n"
|
||||
);
|
||||
let Some(project) = load(&source) else { return };
|
||||
assert_no_control_rules(&project);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t02_one_item_wrapping_whole_branch_is_branch_001() {
|
||||
let Some(project) = load_example("examples/bad/branch-single-item.mq.md") else {
|
||||
return;
|
||||
};
|
||||
assert_has(&project, "MQD-BRANCH-001");
|
||||
let document = &project.documents[0];
|
||||
let function = &document.module.as_ref().unwrap().functions[0];
|
||||
let tree = marqdo_lint::alignment::align_function(&document.markdown, function);
|
||||
let branch = tree
|
||||
.controls
|
||||
.iter()
|
||||
.find(|control| control.kind == marqdo_lint::alignment::ControlKind::Branch)
|
||||
.unwrap();
|
||||
let item = document.markdown.nearest(branch.opener.node, "item").unwrap();
|
||||
let diagnostic = check_document(document)
|
||||
.into_iter()
|
||||
.find(|diagnostic| diagnostic.id == "MQD-BRANCH-001")
|
||||
.unwrap();
|
||||
assert_eq!(diagnostic.span, document.markdown.nodes[item].span);
|
||||
assert_eq!(diagnostic.related_spans.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t03_and_t25_plain_text_markers_never_become_branch_items() {
|
||||
let source = "## @exec 判断\n\n`params(x: Int)`\n\n**结果 = 0**\n\n1\\. 这段文字不是列表。\n\n`if x > 0`\n\n**结果 = 1**\n\n`else`\n\n**结果 = 0**\n\n`end`\n\n*return 结果*\n";
|
||||
let Some(project) = load(source) else { return };
|
||||
assert_has(&project, "MQD-BRANCH-002");
|
||||
let ids = ids(&project);
|
||||
assert!(!ids.contains(&"MQD-BRANCH-001".into()));
|
||||
assert!(!ids.contains(&"MQD-BRANCH-003".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t04_branch_opener_must_be_first_item_carrier() {
|
||||
let source = "## @exec 判断\n\n`params(x: Int)`\n\n**结果 = 0**\n\n1. **结果 = 0**\n\n `if x > 0`:先初始化再判断。\n\n **结果 = 1**\n\n2. `else`:其他保持零。\n\n`end`\n\n*return 结果*\n";
|
||||
let Some(project) = load(source) else { return };
|
||||
assert_has(&project, "MQD-BRANCH-002");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t05_branch_arms_in_different_lists_are_not_siblings() {
|
||||
let source = "## @exec 判断\n\n`params(x: Int)`\n\n**结果 = 0**\n\n1. `if x > 0`:正数返回一。\n\n **结果 = 1**\n\n这里把两个列表分开。\n\n1. `else`:其他返回零。\n\n **结果 = 0**\n\n`end`\n\n*return 结果*\n";
|
||||
let Some(project) = load(source) else { return };
|
||||
assert_has(&project, "MQD-BRANCH-003");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t06_loop_item_and_t08_branch_containing_loop_pass() {
|
||||
let Some(project) = load_example("examples/nested/inventory.mq.md") else {
|
||||
return;
|
||||
};
|
||||
assert_no_control_rules(&project);
|
||||
|
||||
let source = "## @exec 循环\n\n`params()`\n\n**位置 = 0**\n\n- `while 位置 < 1`:每轮前进一步,到达一时终止。\n\n **位置 = 位置 + 1**\n\n `end`\n\n*return 位置*\n";
|
||||
let Some(project) = load(source) else { return };
|
||||
assert_no_control_rules(&project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t07_ordered_item_is_not_the_recommended_loop_container() {
|
||||
let source = "## @exec 循环\n\n`params()`\n\n**位置 = 0**\n\n1. `while 位置 < 1`:每轮前进一步。\n\n **位置 = 位置 + 1**\n\n `end`\n\n*return 位置*\n";
|
||||
let Some(project) = load(source) else { return };
|
||||
assert_has(&project, "MQD-LOOP-001");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t09_loop_containing_branch_preserves_both_container_kinds() {
|
||||
let source = "## @exec 嵌套\n\n`params()`\n\n**位置 = 0**\n\n**结果 = 0**\n\n- `while 位置 < 1`:只处理一轮,随后终止。\n\n 1. `if 位置 == 0`:第一轮写入一。\n\n **结果 = 1**\n\n 2. `else`:后续轮次写入零。\n\n **结果 = 0**\n\n `end`\n\n **位置 = 位置 + 1**\n\n `end`\n\n*return 结果*\n";
|
||||
let Some(project) = load(source) else { return };
|
||||
assert_no_control_rules(&project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t10_sequential_loops_remain_independent() {
|
||||
let source = "## @exec 两段循环\n\n`params()`\n\n**位置 = 0**\n\n- `while 位置 < 1`:第一段处理到一。\n\n **位置 = 位置 + 1**\n\n `end`\n\n- `while 位置 < 2`:第二段处理到二。\n\n **位置 = 位置 + 1**\n\n `end`\n\n*return 位置*\n";
|
||||
let Some(project) = load(source) else { return };
|
||||
assert_no_control_rules(&project);
|
||||
let module = project.documents[0].module.as_ref().unwrap();
|
||||
let loops = marqdo_lint::model::semantic_nodes(&module.functions[0].body)
|
||||
.filter(|node| node.get("kind").and_then(serde_json::Value::as_str) == Some("loop"))
|
||||
.count();
|
||||
assert_eq!(loops, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t11_and_t12_inert_code_regions_do_not_supply_control_or_hidden_statements() {
|
||||
let source = "## @exec 惰性代码\n\n`params(x: Int)`\n\n**结果 = 0**\n\n```text\nend\n**结果 = 99**\n```\n\n`if x > 0`\n\n **结果 = 1**\n\n`else`\n\n**结果 = 0**\n\n`end`\n\n*return 结果*\n";
|
||||
let Some(project) = load(source) else { return };
|
||||
assert_complete(&project);
|
||||
let ids = ids(&project);
|
||||
assert!(!ids.contains(&"MQD-CTRL-001".into()));
|
||||
assert!(project.documents[0]
|
||||
.markdown
|
||||
.nodes
|
||||
.iter()
|
||||
.any(|node| node.kind == "code_block"
|
||||
&& node.literal.as_deref().is_some_and(|text| text.contains("end"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t20_cross_heading_control_is_incomplete_and_never_visually_repaired() {
|
||||
let source = "## @exec 跨段\n\n`params(x: Int)`\n\n`if x > 0`\n\n### 另一段\n\n**结果 = 1**\n\n`end`\n\n*return 结果*\n";
|
||||
let Some(project) = load(source) else { return };
|
||||
assert_eq!(project.analysis_status, AnalysisStatus::AnalysisIncomplete);
|
||||
assert!(ids(&project).is_empty());
|
||||
assert!(project.core_output.contains("sem.unclosed_control"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn t26_task_checkbox_and_t32_legacy_keywordless_items_add_no_control_semantics() {
|
||||
let source = "## @exec 旧版外观\n\n- [ ] 这只是待办,不是 while 条件。\n\n1. 这段文字没有 if 关键字。\n\n **结果 = 1**\n\n2. 这段文字也没有 else 关键字。\n\n **结果 = 0**\n\n*return 结果*\n";
|
||||
let Some(project) = load(source) else { return };
|
||||
assert_no_control_rules(&project);
|
||||
let module = project.documents[0].module.as_ref().unwrap();
|
||||
assert!(!marqdo_lint::model::semantic_nodes(&module.functions[0].body).any(|node| {
|
||||
matches!(
|
||||
node.get("kind").and_then(serde_json::Value::as_str),
|
||||
Some("branch" | "loop")
|
||||
)
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semantic_nesting_outside_the_parent_list_is_loop_003() {
|
||||
let source = "## @exec 错位嵌套\n\n`params(启用: Bool)`\n\n**位置 = 0**\n\n**结果 = 0**\n\n1. `if 启用`:启用后处理。\n\n2. `else`:未启用也保持确定结果。\n\n- `while 位置 < 1`:视觉上脱离了父分支。\n\n **位置 = 位置 + 1**\n\n **结果 = 位置**\n\n `end`\n\n`end`\n\n*return 结果*\n";
|
||||
let Some(project) = load(source) else { return };
|
||||
assert_has(&project, "MQD-LOOP-003");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn branch_loop_and_end_diagnostics_are_reported_independently() {
|
||||
let missing_prose = "## @exec 分支说明\n\n`params(x: Int)`\n\n**结果 = 0**\n\n1. `if x > 0`\n\n **结果 = 1**\n\n2. `else`\n\n **结果 = 0**\n\n`end`\n\n*return 结果*\n";
|
||||
let Some(project) = load(missing_prose) else { return };
|
||||
assert_has(&project, "MQD-BRANCH-004");
|
||||
|
||||
let missing_loop_prose = "## @exec 循环说明\n\n`params()`\n\n**位置 = 0**\n\n- `while 位置 < 1`\n\n **位置 = 位置 + 1**\n\n `end`\n\n*return 位置*\n";
|
||||
let Some(project) = load(missing_loop_prose) else { return };
|
||||
assert_has(&project, "MQD-LOOP-002");
|
||||
|
||||
let detached_end = "## @exec 循环结束\n\n`params()`\n\n**位置 = 0**\n\n- `while 位置 < 1`:每轮前进一步。\n\n **位置 = 位置 + 1**\n\n`end`\n\n*return 位置*\n";
|
||||
let Some(project) = load(detached_end) else { return };
|
||||
assert_has(&project, "MQD-CTRL-001");
|
||||
|
||||
let branch_end_in_list = "## @exec 分支结束\n\n`params(x: Int)`\n\n**结果 = 0**\n\n1. `if x > 0`:正数返回一。\n\n **结果 = 1**\n\n2. `else`:其他返回零。\n\n **结果 = 0**\n\n `end`\n\n*return 结果*\n";
|
||||
let Some(project) = load(branch_end_in_list) else { return };
|
||||
assert_has(&project, "MQD-CTRL-001");
|
||||
}
|
||||
Reference in new issue
Block a user