feat: apply layout rules and safe fixes to RC.2 control flow
This commit is contained in:
1 parent
7282918c50
commit
81fcab0e3a
11 files changed
+621
-323
No files matched your search
@@ -2,7 +2,7 @@
|
||||
|
||||
## 先让阅读结构与执行结构互相对应
|
||||
|
||||
Marqdo 的执行语义来自载体内的 `if`、`else`、`while`、`end`、`return` 等关键字。`1.`、`-` 和 `>` 只是 Markdown 容器。推荐风格是在有序列表项开头直接写 `if`/`else`,在无序列表项开头直接写 `while`,让读者看到的层级与解释器执行层级一致。
|
||||
Marqdo 的执行语义来自载体内的 `if`、`else if`、`else`、`while`、`end`、`break`、`continue`、`return` 等关键字。`1.`、`-` 和 `>` 只是 Markdown 容器。推荐风格是在有序列表项开头分别写 `if`、`else if` 或 `else`,在无序列表项开头直接写 `while`,让读者看到的层级与解释器执行层级一致。
|
||||
|
||||
```markdown
|
||||
1. `if 是否会员`:会员采用整数九折计算。
|
||||
@@ -16,7 +16,7 @@ Marqdo 的执行语义来自载体内的 `if`、`else`、`while`、`end`、`retu
|
||||
`end`
|
||||
```
|
||||
|
||||
不要把整个分支装入一个名为“开始判断”的列表项,也不要在列表项之后很远才写真正的控制语句。当前语言没有 `elif`,多条件链应使用真实的嵌套 `else` 与 `if`。
|
||||
不要把整个分支装入一个名为“开始判断”的列表项,也不要在列表项之后很远才写真正的控制语句。从 Marqdo RC.2 起,同组条件可以依次写多个 `else if`,再按需写一个 `else`。整组只用一个 `end`。若 `else` 和后续 `if` 分别占用两个载体,则第二个 `if` 开启嵌套分支,需要自己的 `end`。
|
||||
|
||||
## 在 Exec 中自然解释
|
||||
|
||||
@@ -28,7 +28,9 @@ Exec 中的粗体、斜体和行内代码都是执行载体。`这是 **特别
|
||||
|
||||
H3+ 是函数内的阅读章节,不创建新函数。一个控制块及其 `end` 必须位于同一 heading 执行段,不能通过插入标题跨段闭合。
|
||||
|
||||
分支组的 `end` 推荐放在有序列表之后;循环的 `end` 推荐留在对应无序列表项末尾。所有嵌套以真实 CommonMark AST 为准,不能只按空格数量猜测。
|
||||
分支组的 `end` 推荐放在有序列表之后,循环的 `end` 推荐留在对应无序列表项末尾。嵌套以 CommonMark AST 的容器为准。
|
||||
|
||||
`break` 跳到最近循环之后,`continue` 返回最近循环的条件,`return` 退出整个函数。用行内代码标记 `break` 和 `continue`,并把它们放在实际所属的循环项或分支臂内。[RC.2 读数扫描示例](../examples/good/control-flow-rc2.mq.md) 展示了这两种跳转。
|
||||
|
||||
## 自动修复边界
|
||||
|
||||
|
||||
+7
-5
@@ -9,20 +9,22 @@
|
||||
| MQD-DOC-003 | warning | 复杂函数的叙述占比低于阈值 | 自然叙述达到门槛,短小平凡函数仅提示。运行 `long_functions_use_warning_ratio_and_h3_reading_sections` 和 `t23_trivial_short_functions_only_receive_info_ratio_diagnostics` |
|
||||
| MQD-DOC-004 | info | 长函数无小节 | 在完整控制块之间按业务阶段分段。运行 `long_functions_use_warning_ratio_and_h3_reading_sections` |
|
||||
| MQD-BRANCH-001 | warning | [同项包含 if/else](../examples/bad/branch-single-item.mq.md) | [推荐分支](../examples/good/branches.mq.md) |
|
||||
| MQD-BRANCH-002 | warning | [不使用列表](../examples/bad/branches-unlisted.mq.md) 或列表先写说明再写 if | 让 if 和 else 分别成为有序项首个载体。运行 `prose_before_first_carrier_does_not_form_a_branch_head` 与 `t01_and_t19_branch_siblings_pass_in_h2_and_h3_segments` |
|
||||
| MQD-BRANCH-003 | warning | 条件臂分属不同列表 | 使用同一有序列表中的相邻兄弟项。运行 `t05_branch_arms_in_different_lists_are_not_siblings` |
|
||||
| MQD-BRANCH-002 | warning | [不使用列表](../examples/bad/branches-unlisted.mq.md) 或列表先写说明再写 if | 让每个 `if`、`else if` 和 `else` 成为各自有序项的首个载体。运行 `prose_before_first_carrier_does_not_form_a_branch_head` 与 `t01_and_t19_branch_siblings_pass_in_h2_and_h3_segments` |
|
||||
| MQD-BRANCH-003 | warning | 条件臂分属不同列表或中间有其他项 | 使用同一有序列表中的相邻兄弟项。运行 `t05_branch_arms_in_different_lists_are_not_siblings` |
|
||||
| MQD-BRANCH-004 | info | 非空分支的列表项中缺少解释 | [推荐分支](../examples/good/branches.mq.md) 在臂内写原因。运行 `branch_loop_and_end_diagnostics_are_reported_independently` |
|
||||
| MQD-LOOP-001 | warning | 编号项承载 while | [嵌套示例](../examples/nested/inventory.mq.md) 的循环使用无序项。运行 `t07_ordered_item_is_not_the_recommended_loop_container` |
|
||||
| MQD-LOOP-002 | info | 循环项缺少叙述 | [嵌套示例](../examples/nested/inventory.mq.md) 说明处理对象和终止条件。运行 `branch_loop_and_end_diagnostics_are_reported_independently` |
|
||||
| MQD-LOOP-003 | warning | 语义控制体脱离对应项或嵌套层级不一致 | 依据真实列表子树缩进。运行 `a_branch_body_outside_its_item_is_a_layout_mismatch` 与 `t06_loop_item_and_t08_branch_containing_loop_pass` |
|
||||
| MQD-CTRL-001 | warning | 循环 end 在项外,或分支 end 仍在分支项内 | 分支 end 在列表后,循环 end 在项末尾。运行 `branch_loop_and_end_diagnostics_are_reported_independently` 与 `t06_loop_item_and_t08_branch_containing_loop_pass` |
|
||||
| MQD-LOOP-003 | warning | 分支体或跳转脱离所属项,或子循环嵌套到错误的臂 | 依据真实列表子树缩进。运行 `a_branch_body_outside_its_item_is_a_layout_mismatch` 与 `t06_loop_item_and_t08_branch_containing_loop_pass` |
|
||||
| MQD-CTRL-001 | warning | 循环 end 在项外,或分支 end 仍在分支项内 | 整个分支组只检查一个 `end`,放在列表后。循环 `end` 放在项末尾。运行 `branch_loop_and_end_diagnostics_are_reported_independently` 与 `t06_loop_item_and_t08_branch_containing_loop_pass` |
|
||||
| MQD-PROSE-001 | warning | 句中的粗体、斜体或反引号成为执行载体 | 普通文字留在 Exec,富文本可进入 [Knowledge](../examples/knowledge/discount.mq.md)。运行 `t16_exec_emphasis_inside_prose_is_not_a_comment` |
|
||||
| MQD-PROSE-002 | info | 已绑定的 I/O 调用或索引写入缺少相邻叙述 | 说明权限、后果或失败处理。运行 `supplemental_rules_use_bound_calls_and_allow_rich_knowledge` |
|
||||
| MQD-PARAM-001 | info | 显式签名附近没有自然文字 | 说明单位、范围和用途。运行 `supplemental_rules_use_bound_calls_and_allow_rich_knowledge` |
|
||||
| MQD-STYLE-001 | info | 用行内代码承载 return | [推荐分支](../examples/good/branches.mq.md) 用斜体表示返回,粗体表示赋值。运行 `supplemental_rules_use_bound_calls_and_allow_rich_knowledge` |
|
||||
| MQD-STYLE-001 | info | 用行内代码承载 `return`,或用斜体承载 `else if` 和循环跳转 | [推荐分支](../examples/good/branches.mq.md) 用斜体表示返回,粗体表示赋值。[RC.2 读数扫描](../examples/good/control-flow-rc2.mq.md) 用行内代码表示控制头、`break` 和 `continue`。运行 `supplemental_rules_use_bound_calls_and_allow_rich_knowledge` |
|
||||
| MQD-KNOW-001 | warning | 在两个执行段之间切出一段纯文字,或出现 [跨段控制](../tests/fixtures/golden/invalid-control.mq.md) | 普通说明留在 Exec,同段关闭控制,公式和富文本可留在 Knowledge。运行 `supplemental_rules_use_bound_calls_and_allow_rich_knowledge` |
|
||||
| MQD-SAFETY-001 | error | AST、执行载荷或 Analysis 不等价,或无法取得可靠验证输入 | 放弃写回。运行 `safe_fix_rejects_changes_to_inert_payload_and_unavailable_analysis` 与 `safe_fix_previews_then_persists_verified_whitespace_in_a_manifest_project` |
|
||||
|
||||
自动检测可以判断结构、覆盖和位置。对叙述内容的业务正确性仍须由作者和评审者判断。当前副作用识别使用公开 Analysis 中已绑定的资源、外部执行、标准库 I/O、插件调用和索引写入。未知绑定和普通本地函数不被猜测为副作用。
|
||||
|
||||
多臂与跳转的正反例由 `rc2_branch_rules_anchor_each_affected_arm` 和 `rc2_jump_rules_check_the_arm_container_and_carrier_style` 复现。度量把每个分支组和每个跳转分别计作一个语句。
|
||||
|
||||
渲染对照位于 [examples/rendered](../examples/rendered)。使用 `cargo run --locked --example render_fixtures` 按冻结 Markdown Profile 重新生成。
|
||||
@@ -0,0 +1,39 @@
|
||||
# @knowledge 读数扫描
|
||||
|
||||
## @exec main
|
||||
|
||||
按顺序扫描读数。忽略负数,遇到停止标记时结束,返回已接收读数的总和。
|
||||
|
||||
**读数 = [2, -1, 3, 0, 9]**
|
||||
|
||||
**位置 = 0**
|
||||
|
||||
**合计 = 0**
|
||||
|
||||
位置始终指向下一条待读取的记录。每轮先读取当前位置,再向前移一格。即使当前读数无效,本轮也已经推进位置,下一轮会读取下一条记录。
|
||||
|
||||
- `while 位置 < 长度(读数)`:每轮前进一步,直到读完或遇到停止标记。
|
||||
|
||||
**当前 = 读数[位置]**
|
||||
|
||||
**位置 = 位置 + 1**
|
||||
|
||||
1. `if 当前 < 0`:无效读数跳过本轮。
|
||||
|
||||
`continue`
|
||||
|
||||
2. `else if 当前 == 0`:停止标记结束扫描。
|
||||
|
||||
`break`
|
||||
|
||||
3. `else`:将有效读数计入总和。
|
||||
|
||||
**合计 = 合计 + 当前**
|
||||
|
||||
`end`
|
||||
|
||||
`end`
|
||||
|
||||
*return 合计*
|
||||
|
||||
总和只包含停止标记前的有效读数。
|
||||
@@ -54,15 +54,6 @@ pub struct ControlLayout {
|
||||
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,
|
||||
|
||||
+7
-1
@@ -5,7 +5,7 @@ use crate::{
|
||||
input::{MarkdownOrigin, SourceDocument},
|
||||
metrics::{measure_module_function, FunctionNarrative},
|
||||
rules::{
|
||||
check_aligned, check_ast_document, check_entry_without_analysis,
|
||||
check_aligned, check_ast_document, check_entry_for_heading, check_entry_without_analysis,
|
||||
check_function_documentation, check_supplemental_function,
|
||||
},
|
||||
};
|
||||
@@ -35,6 +35,12 @@ pub fn analyze_document(document: &SourceDocument, config: &EffectiveConfig) ->
|
||||
.iter()
|
||||
.map(|issue| format!("{}:{}", function.local_name, issue)),
|
||||
);
|
||||
if let Some(heading) = tree
|
||||
.function
|
||||
.and_then(|function| markdown.heading(function))
|
||||
{
|
||||
diagnostics.extend(check_entry_for_heading(markdown, heading));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
diagnostics.extend(check_aligned(markdown, &tree));
|
||||
|
||||
+67
-2
@@ -41,6 +41,16 @@ pub fn fix_project(
|
||||
(candidate != original).then(|| (document.source.path.clone(), candidate))
|
||||
})
|
||||
.collect::<Candidates>();
|
||||
apply_candidates(project, runner, &candidates, dry_run, output)
|
||||
}
|
||||
|
||||
fn apply_candidates(
|
||||
project: &ProjectInput,
|
||||
runner: &MarqdoRunner,
|
||||
candidates: &Candidates,
|
||||
dry_run: bool,
|
||||
output: &mut impl Write,
|
||||
) -> Result<FixOutcome> {
|
||||
if candidates.is_empty() {
|
||||
return Ok(FixOutcome {
|
||||
changed: false,
|
||||
@@ -48,7 +58,7 @@ pub fn fix_project(
|
||||
});
|
||||
}
|
||||
|
||||
if let Err(error) = verify(project, runner, &candidates) {
|
||||
if let Err(error) = verify(project, runner, candidates) {
|
||||
return Ok(FixOutcome {
|
||||
changed: false,
|
||||
diagnostic: Some(
|
||||
@@ -204,7 +214,7 @@ fn verify(project: &ProjectInput, runner: &MarqdoRunner, candidates: &Candidates
|
||||
|
||||
fn require_complete(project: &ProjectInput) -> Result<()> {
|
||||
if project.analysis_status != AnalysisStatus::Complete || project.analysis.is_none() {
|
||||
return Err(refusal("无法取得完整的 Analysis v2"));
|
||||
return Err(refusal("无法取得完整的 Analysis v2/v3"));
|
||||
}
|
||||
for document in &project.documents {
|
||||
if document.markdown_origin != MarkdownOrigin::MarqdoInspect
|
||||
@@ -328,4 +338,59 @@ mod tests {
|
||||
assert!(error.to_string().contains("Markdown"), "{error}");
|
||||
assert_eq!(fs::read_to_string(file).unwrap(), original);
|
||||
}
|
||||
#[test]
|
||||
fn safe_fix_checks_whitespace_and_refuses_reassigned_control_bodies() {
|
||||
let Some(core) = std::env::var_os("MARQDO_BIN") else {
|
||||
return;
|
||||
};
|
||||
let runner = MarqdoRunner::discover(Some(Path::new(&core))).unwrap();
|
||||
let rc2 = std::process::Command::new(runner.binary())
|
||||
.arg("--version")
|
||||
.output()
|
||||
.unwrap()
|
||||
.stdout
|
||||
.ends_with(b"3.0.0-rc.2\n");
|
||||
let v2 = "## @exec main\n\n`if false`\n\n*return 1*\n\n`else`\n\n*return 2*\n\n`end`\n";
|
||||
let v3 = "## @exec main\n\n`while false`\n\n`while false`\n\n`break`\n\n`end`\n\n`end`\n";
|
||||
let cases = [
|
||||
(
|
||||
2,
|
||||
v2,
|
||||
v2.replace("`else`\n\n*return 2*", "*return 2*\n\n`else`"),
|
||||
),
|
||||
(3, v3, v3.replace("`break`\n\n`end`", "`end`\n\n`break`")),
|
||||
];
|
||||
for (major, source, different_body) in
|
||||
cases.into_iter().filter(|(major, _, _)| *major == 2 || rc2)
|
||||
{
|
||||
let dir = tempdir().unwrap();
|
||||
let file = dir.path().join("case.mq.md");
|
||||
let original = source.replace("## @exec main\n\n", "## @exec main\n \t\n");
|
||||
fs::write(&file, &original).unwrap();
|
||||
let project = ProjectInput::load(&file, &runner).unwrap();
|
||||
assert_eq!(project.analysis.as_ref().unwrap().schema_version, major);
|
||||
let mut diff = Vec::new();
|
||||
let dry_run = fix_project(&project, &runner, true, &mut diff).unwrap();
|
||||
assert!(!dry_run.changed && dry_run.diagnostic.is_none() && !diff.is_empty());
|
||||
assert_eq!(fs::read(&file).unwrap(), original.as_bytes());
|
||||
let candidates = Candidates::from([(project.entry.clone(), different_body)]);
|
||||
for dry_run in [true, false] {
|
||||
let refused =
|
||||
apply_candidates(&project, &runner, &candidates, dry_run, &mut Vec::new())
|
||||
.unwrap();
|
||||
assert!(!refused.changed);
|
||||
let diagnostic = refused.diagnostic.unwrap();
|
||||
assert_eq!(diagnostic.id, "MQD-SAFETY-001");
|
||||
assert!(
|
||||
diagnostic.message.contains("Analysis 中"),
|
||||
"{}",
|
||||
diagnostic.message
|
||||
);
|
||||
assert_eq!(fs::read(&file).unwrap(), original.as_bytes());
|
||||
}
|
||||
let applied = fix_project(&project, &runner, false, &mut Vec::new()).unwrap();
|
||||
assert!(applied.changed && applied.diagnostic.is_none());
|
||||
assert_eq!(fs::read(&file).unwrap(), source.as_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-12
@@ -5,11 +5,11 @@ use unicode_general_category::{get_general_category, GeneralCategory};
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
|
||||
use crate::{
|
||||
alignment::{node_span, statement_count},
|
||||
alignment::statement_count,
|
||||
input::SourceDocument,
|
||||
model::{
|
||||
effect_sites, semantic_nodes, AnalysisFunction, Carrier, HeadingMode, MarkdownTree, NodeId,
|
||||
ProseFragment, Span,
|
||||
effect_sites, statements, AnalysisFunction, Carrier, HeadingMode, MarkdownTree, NodeId,
|
||||
ProseFragment, Span, StatementKind,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -139,9 +139,9 @@ pub fn measure_function(
|
||||
})
|
||||
.map(|fragment| fragment.span)
|
||||
.min_by_key(|span| span.start);
|
||||
let last_return = semantic_nodes(&analysis.body)
|
||||
.filter(|node| node.get("kind").and_then(serde_json::Value::as_str) == Some("return"))
|
||||
.filter_map(|node| node_span(node))
|
||||
let last_return = statements(&analysis.body)
|
||||
.filter(|statement| statement.kind == StatementKind::Return)
|
||||
.map(|statement| statement.span)
|
||||
.max_by_key(|span| span.start);
|
||||
let mut coverage_complete = !carriers.is_empty();
|
||||
let result_anchor = if let Some(return_span) = last_return {
|
||||
@@ -164,12 +164,8 @@ pub fn measure_function(
|
||||
.iter()
|
||||
.filter(|heading| heading.function == Some(function) && heading.level > 2)
|
||||
.count();
|
||||
let has_control_flow = semantic_nodes(&analysis.body).any(|node| {
|
||||
matches!(
|
||||
node.get("kind").and_then(serde_json::Value::as_str),
|
||||
Some("branch" | "loop")
|
||||
)
|
||||
});
|
||||
let has_control_flow = statements(&analysis.body)
|
||||
.any(|statement| matches!(statement.kind, StatementKind::Branch | StatementKind::Loop));
|
||||
let has_explicit_effects = analysis
|
||||
.effects
|
||||
.iter()
|
||||
|
||||
+271
-228
@@ -1,9 +1,14 @@
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use crate::{
|
||||
alignment::{align_function, BodyStatement, ControlKind, ControlLayout, ReadableControlTree},
|
||||
alignment::{
|
||||
align_function, BodyOwner, BodyStatement, ControlKind, ControlLayout, JumpLayout,
|
||||
ReadableControlTree,
|
||||
},
|
||||
diagnostics::Diagnostic,
|
||||
input::SourceDocument,
|
||||
metrics::narrative_count,
|
||||
model::{AnalysisFunction, Carrier, MarkdownTree, NodeId, StatementKind},
|
||||
model::{AnalysisFunction, Carrier, MarkdownTree, NodeId, Span, StatementKind},
|
||||
};
|
||||
|
||||
pub fn check_document(document: &SourceDocument) -> Vec<Diagnostic> {
|
||||
@@ -14,13 +19,7 @@ pub fn check_document(document: &SourceDocument) -> Vec<Diagnostic> {
|
||||
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,
|
||||
))
|
||||
});
|
||||
sort_diagnostics(&mut diagnostics);
|
||||
diagnostics
|
||||
}
|
||||
|
||||
@@ -36,201 +35,284 @@ pub(crate) fn check_aligned(
|
||||
markdown: &MarkdownTree,
|
||||
tree: &ReadableControlTree,
|
||||
) -> Vec<Diagnostic> {
|
||||
let Some(function) = tree.function else {
|
||||
return Vec::new();
|
||||
};
|
||||
let layout = FunctionLayout::new(markdown, function);
|
||||
let mut diagnostics = Vec::new();
|
||||
for (index, control) in tree.controls.iter().enumerate() {
|
||||
for control in &tree.controls {
|
||||
match control.kind {
|
||||
ControlKind::Branch => branch_rules(markdown, tree, control, &mut diagnostics),
|
||||
ControlKind::Loop => loop_rules(markdown, tree, control, &mut diagnostics),
|
||||
ControlKind::Branch => branch_rules(&layout, tree, control, &mut diagnostics),
|
||||
ControlKind::Loop => loop_rules(&layout, tree, control, &mut diagnostics),
|
||||
}
|
||||
nesting_rule(markdown, tree, index, &mut diagnostics);
|
||||
body_rule(markdown, tree, control, &mut diagnostics);
|
||||
end_rule(markdown, tree, control, &mut diagnostics);
|
||||
nesting_rule(&layout, tree, control, &mut diagnostics);
|
||||
body_rule(&layout, tree, control, &mut diagnostics);
|
||||
end_rule(&layout, 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,
|
||||
))
|
||||
});
|
||||
for jump in &tree.jumps {
|
||||
jump_rule(&layout, tree, jump, &mut diagnostics);
|
||||
}
|
||||
sort_diagnostics(&mut diagnostics);
|
||||
diagnostics
|
||||
}
|
||||
|
||||
fn sort_diagnostics(diagnostics: &mut [Diagnostic]) {
|
||||
diagnostics.sort_by(|left, right| (left.span, &left.id).cmp(&(right.span, &right.id)));
|
||||
}
|
||||
|
||||
struct FunctionLayout<'a> {
|
||||
markdown: &'a MarkdownTree,
|
||||
items: HashMap<NodeId, NodeId>,
|
||||
next_ordered_item: HashMap<NodeId, NodeId>,
|
||||
last_carrier: HashMap<NodeId, NodeId>,
|
||||
prose: HashMap<NodeId, Vec<Span>>,
|
||||
}
|
||||
|
||||
impl<'a> FunctionLayout<'a> {
|
||||
fn new(markdown: &'a MarkdownTree, function: NodeId) -> Self {
|
||||
let mut items = HashMap::new();
|
||||
let mut last_carrier = HashMap::new();
|
||||
for carrier in markdown
|
||||
.carriers
|
||||
.iter()
|
||||
.filter(|carrier| carrier.function == Some(function))
|
||||
{
|
||||
if let Some(item) = markdown.nearest(carrier.node, "item") {
|
||||
items.insert(carrier.node, item);
|
||||
last_carrier.insert(item, carrier.node);
|
||||
}
|
||||
}
|
||||
let mut next_ordered_item = HashMap::new();
|
||||
for (node, list) in markdown.nodes.iter().enumerate() {
|
||||
if list.kind == "list"
|
||||
&& list.ordered == Some(true)
|
||||
&& markdown.function_of(node) == Some(function)
|
||||
{
|
||||
let children = list
|
||||
.children
|
||||
.iter()
|
||||
.filter(|&&node| markdown.nodes[node].kind == "item");
|
||||
next_ordered_item.extend(
|
||||
children
|
||||
.clone()
|
||||
.zip(children.skip(1))
|
||||
.map(|(&left, &right)| (left, right)),
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut prose: HashMap<NodeId, Vec<Span>> = HashMap::new();
|
||||
for fragment in markdown.prose_fragments(function) {
|
||||
if narrative_count(&fragment.text) > 0 {
|
||||
if let Some(item) = markdown.nearest(fragment.node, "item") {
|
||||
prose.entry(item).or_default().push(fragment.span);
|
||||
}
|
||||
}
|
||||
}
|
||||
Self {
|
||||
markdown,
|
||||
items,
|
||||
next_ordered_item,
|
||||
last_carrier,
|
||||
prose,
|
||||
}
|
||||
}
|
||||
|
||||
fn item(&self, carrier: &Carrier) -> Option<NodeId> {
|
||||
self.items.get(&carrier.node).copied()
|
||||
}
|
||||
|
||||
fn list(&self, item: NodeId) -> Option<NodeId> {
|
||||
self.markdown.nearest(item, "list")
|
||||
}
|
||||
|
||||
fn is_item_head(&self, item: NodeId, carrier: &Carrier) -> bool {
|
||||
self.markdown.nodes[item]
|
||||
.children
|
||||
.first()
|
||||
.is_some_and(|first| {
|
||||
let paragraph = &self.markdown.nodes[*first];
|
||||
paragraph.kind == "paragraph" && paragraph.children.first() == Some(&carrier.node)
|
||||
})
|
||||
}
|
||||
|
||||
fn has_prose(&self, item: NodeId, from: usize, to: usize) -> bool {
|
||||
self.prose.get(&item).is_some_and(|spans| {
|
||||
spans
|
||||
.iter()
|
||||
.any(|span| from <= span.start && span.end <= to)
|
||||
})
|
||||
}
|
||||
|
||||
fn container(&self, carrier: &Carrier) -> Option<NodeId> {
|
||||
self.item(carrier)
|
||||
.or_else(|| self.markdown.nearest(carrier.node, "block_quote"))
|
||||
}
|
||||
}
|
||||
|
||||
fn branch_rules(
|
||||
markdown: &MarkdownTree,
|
||||
layout: &FunctionLayout<'_>,
|
||||
tree: &ReadableControlTree,
|
||||
control: &ControlLayout,
|
||||
diagnostics: &mut Vec<Diagnostic>,
|
||||
) {
|
||||
let opener_item = markdown.nearest(control.opener.node, "item");
|
||||
let else_item = control
|
||||
.else_carrier()
|
||||
.and_then(|carrier| markdown.nearest(carrier.node, "item"));
|
||||
if let (Some(item), Some(else_carrier), Some(other)) =
|
||||
(opener_item, control.else_carrier(), 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;
|
||||
let arms: Vec<_> = control
|
||||
.arms
|
||||
.iter()
|
||||
.map(|arm| (&arm.carrier, layout.item(&arm.carrier)))
|
||||
.collect();
|
||||
let mut by_item: BTreeMap<NodeId, Vec<Span>> = BTreeMap::new();
|
||||
for &(carrier, item) in &arms {
|
||||
if let Some(item) = item {
|
||||
by_item.entry(item).or_default().push(carrier.span);
|
||||
}
|
||||
}
|
||||
|
||||
for carrier in std::iter::once(&control.opener).chain(control.else_carrier()) {
|
||||
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))
|
||||
&& is_item_head(markdown, item, carrier)
|
||||
let mut collision = false;
|
||||
for (item, heads) in by_item.into_iter().filter(|(_, heads)| heads.len() > 1) {
|
||||
collision = true;
|
||||
let mut diagnostic = Diagnostic::new("MQD-BRANCH-001", layout.markdown.nodes[item].span)
|
||||
.with_function(&tree.function_name);
|
||||
for head in heads {
|
||||
diagnostic = diagnostic.with_related(head);
|
||||
}
|
||||
diagnostics.push(diagnostic);
|
||||
}
|
||||
// Keep the existing diagnostic priority for a two-arm group in one item.
|
||||
if collision && arms.len() == 2 {
|
||||
return;
|
||||
}
|
||||
for &(carrier, item) in &arms {
|
||||
let valid = item.is_some_and(|item| {
|
||||
layout
|
||||
.list(item)
|
||||
.is_some_and(|list| layout.markdown.nodes[list].ordered == Some(true))
|
||||
&& layout.is_item_head(item, carrier)
|
||||
});
|
||||
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);
|
||||
if let Some(item) = item {
|
||||
diagnostic = diagnostic.with_related(layout.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) {
|
||||
for pair in arms.windows(2) {
|
||||
let [(left, Some(left_item)), (right, Some(right_item))] = pair else {
|
||||
continue;
|
||||
};
|
||||
if left_item != right_item && layout.next_ordered_item.get(left_item) != Some(right_item) {
|
||||
diagnostics.push(
|
||||
Diagnostic::new("MQD-BRANCH-003", left.span)
|
||||
.with_related(right.span)
|
||||
.with_function(&tree.function_name),
|
||||
);
|
||||
}
|
||||
}
|
||||
if control.arms.iter().any(|arm| !arm.body.is_empty()) {
|
||||
for (index, &(carrier, item)) in arms.iter().enumerate() {
|
||||
let Some(item) = item else { continue };
|
||||
let next = arms
|
||||
.get(index + 1)
|
||||
.map(|(head, _)| *head)
|
||||
.or(control.end.as_ref());
|
||||
let until = next.map_or(usize::MAX, |next| next.span.start);
|
||||
if !layout.has_prose(item, carrier.span.end, until) {
|
||||
diagnostics.push(
|
||||
Diagnostic::new("MQD-BRANCH-003", control.opener.span)
|
||||
.with_related(else_carrier.span)
|
||||
Diagnostic::new("MQD-BRANCH-004", carrier.span)
|
||||
.with_related(layout.markdown.nodes[item].span)
|
||||
.with_function(&tree.function_name),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !control.arms.iter().any(|arm| !arm.body.is_empty()) {
|
||||
return;
|
||||
}
|
||||
for carrier in std::iter::once(&control.opener).chain(control.else_carrier()) {
|
||||
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,
|
||||
layout: &FunctionLayout<'_>,
|
||||
tree: &ReadableControlTree,
|
||||
control: &ControlLayout,
|
||||
diagnostics: &mut Vec<Diagnostic>,
|
||||
) {
|
||||
let item = markdown.nearest(control.opener.node, "item");
|
||||
let item = layout.item(&control.opener);
|
||||
let valid = item.is_some_and(|item| {
|
||||
markdown
|
||||
.nearest(item, "list")
|
||||
.is_some_and(|list| markdown.nodes[list].ordered == Some(false))
|
||||
&& is_item_head(markdown, item, &control.opener)
|
||||
layout
|
||||
.list(item)
|
||||
.is_some_and(|list| layout.markdown.nodes[list].ordered == Some(false))
|
||||
&& layout.is_item_head(item, &control.opener)
|
||||
});
|
||||
if !valid {
|
||||
diagnostics.push(
|
||||
Diagnostic::new("MQD-LOOP-001", control.opener.span).with_function(&tree.function_name),
|
||||
);
|
||||
}
|
||||
let Some(item) = item else {
|
||||
return;
|
||||
};
|
||||
if !control.body.is_empty()
|
||||
&& !item_has_prose_after(markdown, control.function, item, control.opener.span.end)
|
||||
{
|
||||
let Some(item) = item else { return };
|
||||
if !control.body.is_empty() && !layout.has_prose(item, control.opener.span.end, usize::MAX) {
|
||||
diagnostics.push(
|
||||
Diagnostic::new("MQD-LOOP-002", control.opener.span)
|
||||
.with_related(markdown.nodes[item].span)
|
||||
.with_related(layout.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_arm(markdown, parent, control.opener.span.start).is_some_and(
|
||||
|container| {
|
||||
markdown
|
||||
.nearest(control.opener.node, "item")
|
||||
.is_some_and(|item| {
|
||||
item != container && markdown.is_descendant(item, container)
|
||||
})
|
||||
},
|
||||
)
|
||||
})
|
||||
.max_by_key(|(_, parent)| parent.opener.span.start)
|
||||
.map(|(candidate, _)| candidate);
|
||||
if visual_parent != control.parent.map(|parent| parent.control) {
|
||||
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.control].opener.span);
|
||||
}
|
||||
diagnostics.push(diagnostic);
|
||||
fn body_opener(tree: &ReadableControlTree, owner: BodyOwner) -> &Carrier {
|
||||
let control = tree.control(owner.control);
|
||||
match owner.arm {
|
||||
Some(arm) => &control.arms[arm].carrier,
|
||||
None => &control.opener,
|
||||
}
|
||||
}
|
||||
|
||||
fn end_rule(
|
||||
markdown: &MarkdownTree,
|
||||
fn nesting_rule(
|
||||
layout: &FunctionLayout<'_>,
|
||||
tree: &ReadableControlTree,
|
||||
control: &ControlLayout,
|
||||
diagnostics: &mut Vec<Diagnostic>,
|
||||
) {
|
||||
let Some(end) = &control.end else {
|
||||
return;
|
||||
};
|
||||
let Some(parent) = control.parent else { return };
|
||||
let parent = body_opener(tree, parent);
|
||||
let nested = layout
|
||||
.item(parent)
|
||||
.zip(layout.item(&control.opener))
|
||||
.is_some_and(|(parent, item)| {
|
||||
item != parent && layout.markdown.is_descendant(item, parent)
|
||||
});
|
||||
if !nested {
|
||||
diagnostics.push(
|
||||
Diagnostic::new("MQD-LOOP-003", control.opener.span)
|
||||
.with_related(parent.span)
|
||||
.with_function(&tree.function_name),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn end_rule(
|
||||
layout: &FunctionLayout<'_>,
|
||||
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()
|
||||
.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))
|
||||
}
|
||||
let items: Vec<_> = control
|
||||
.arms
|
||||
.iter()
|
||||
.map(|arm| layout.item(&arm.carrier))
|
||||
.collect();
|
||||
let same_item =
|
||||
items.len() > 1 && items[0].is_some() && items.iter().all(|item| *item == items[0]);
|
||||
let ancestors = layout.markdown.ancestors(end.node);
|
||||
!same_item
|
||||
&& items
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|item| layout.list(item))
|
||||
.any(|list| ancestors.contains(&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)
|
||||
}),
|
||||
ControlKind::Loop => layout
|
||||
.item(&control.opener)
|
||||
.is_some_and(|item| layout.last_carrier.get(&item) != Some(&end.node)),
|
||||
};
|
||||
if detached {
|
||||
diagnostics.push(
|
||||
@@ -241,101 +323,62 @@ fn end_rule(
|
||||
}
|
||||
}
|
||||
|
||||
fn is_item_head(markdown: &MarkdownTree, item: NodeId, carrier: &Carrier) -> bool {
|
||||
markdown.nodes[item].children.first().is_some_and(|first| {
|
||||
let paragraph = &markdown.nodes[*first];
|
||||
paragraph.kind == "paragraph" && paragraph.children.first() == Some(&carrier.node)
|
||||
})
|
||||
}
|
||||
|
||||
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_arm(markdown: &MarkdownTree, control: &ControlLayout, offset: usize) -> Option<NodeId> {
|
||||
let owner = control
|
||||
.else_carrier()
|
||||
.filter(|carrier| carrier.span.start < offset)
|
||||
.unwrap_or(&control.opener);
|
||||
markdown.nearest(owner.node, "item")
|
||||
}
|
||||
|
||||
fn body_rule(
|
||||
markdown: &MarkdownTree,
|
||||
layout: &FunctionLayout<'_>,
|
||||
tree: &ReadableControlTree,
|
||||
control: &ControlLayout,
|
||||
diagnostics: &mut Vec<Diagnostic>,
|
||||
) {
|
||||
let check_body =
|
||||
|body: &[BodyStatement], opener: &Carrier, diagnostics: &mut Vec<Diagnostic>| {
|
||||
let Some(item) = markdown.nearest(opener.node, "item") else {
|
||||
return;
|
||||
};
|
||||
if !is_item_head(markdown, item, opener) {
|
||||
return;
|
||||
}
|
||||
for statement in body {
|
||||
// Nested control headers are checked separately by nesting_rule.
|
||||
if matches!(statement.kind, StatementKind::Branch | StatementKind::Loop) {
|
||||
continue;
|
||||
}
|
||||
if !markdown.is_descendant(statement.carrier.node, item) {
|
||||
diagnostics.push(
|
||||
Diagnostic::new("MQD-LOOP-003", statement.carrier.span)
|
||||
.with_message("执行语句位于其控制项的 Markdown 子树之外")
|
||||
.with_related(opener.span)
|
||||
.with_function(&tree.function_name),
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut check_body = |body: &[BodyStatement], opener: &Carrier| {
|
||||
let Some(item) = layout
|
||||
.item(opener)
|
||||
.filter(|&item| layout.is_item_head(item, opener))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
for statement in body {
|
||||
if matches!(
|
||||
statement.kind,
|
||||
StatementKind::Assign | StatementKind::Expression | StatementKind::Return
|
||||
) && !layout.markdown.is_descendant(statement.carrier.node, item)
|
||||
{
|
||||
diagnostics.push(
|
||||
Diagnostic::new("MQD-LOOP-003", statement.carrier.span)
|
||||
.with_message("执行语句位于其控制项的 Markdown 子树之外")
|
||||
.with_related(opener.span)
|
||||
.with_function(&tree.function_name),
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
match control.kind {
|
||||
ControlKind::Branch => {
|
||||
for arm in &control.arms {
|
||||
check_body(&arm.body, &arm.carrier, diagnostics);
|
||||
check_body(&arm.body, &arm.carrier);
|
||||
}
|
||||
}
|
||||
ControlKind::Loop => check_body(&control.body, &control.opener, diagnostics),
|
||||
ControlKind::Loop => check_body(&control.body, &control.opener),
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
&& narrative_count(&fragment.text) > 0
|
||||
})
|
||||
fn jump_rule(
|
||||
layout: &FunctionLayout<'_>,
|
||||
tree: &ReadableControlTree,
|
||||
jump: &JumpLayout,
|
||||
diagnostics: &mut Vec<Diagnostic>,
|
||||
) {
|
||||
let body = body_opener(tree, jump.parent);
|
||||
let target = &tree.control(jump.target_loop).opener;
|
||||
if let Some(opener) = [body, target].into_iter().find(|opener| {
|
||||
layout
|
||||
.container(opener)
|
||||
.is_some_and(|container| !layout.markdown.is_descendant(jump.carrier.node, container))
|
||||
}) {
|
||||
diagnostics.push(
|
||||
Diagnostic::new("MQD-LOOP-003", jump.carrier.span)
|
||||
.with_message("循环跳转位于所属分支臂或目标循环的 Markdown 容器之外")
|
||||
.with_related(opener.span)
|
||||
.with_function(&tree.function_name),
|
||||
);
|
||||
}
|
||||
}
|
||||
+12
-12
@@ -7,7 +7,7 @@ pub use control::{check_document, check_function};
|
||||
pub use documentation::{check_documentation, check_function_documentation};
|
||||
pub use supplemental::{check_ast_document, check_entry_without_analysis, check_heading_boundary};
|
||||
|
||||
pub(crate) use supplemental::check_supplemental_function;
|
||||
pub(crate) use supplemental::{check_entry_for_heading, check_supplemental_function};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -92,10 +92,10 @@ pub const CATALOG: &[RuleSpec] = &[
|
||||
rule!(
|
||||
"MQD-BRANCH-001",
|
||||
Warning,
|
||||
"一个编号项包含整段分支",
|
||||
"一个列表项包含多个同组分支头",
|
||||
"读者看不到互相对等的分支臂。",
|
||||
"把 if 与 else 分别放入同一有序列表的相邻兄弟项。",
|
||||
"IR Branch 与 AST Item 子树中的 if/else 载体。",
|
||||
"把 if、各个 else if 和 else 分别放入同一有序列表的相邻兄弟项。",
|
||||
"Analysis 分支臂及共享 Markdown Item 的头部载体。",
|
||||
Manual
|
||||
),
|
||||
rule!(
|
||||
@@ -103,8 +103,8 @@ pub const CATALOG: &[RuleSpec] = &[
|
||||
Warning,
|
||||
"分支头不在有序列表项开头",
|
||||
"视觉分支与实际执行分支不一致。",
|
||||
"让 if/else 成为对应有序项的首个执行载体。",
|
||||
"IR 控制节点、最近 Item 和项内首个载体。",
|
||||
"让每个 if、else if、else 成为对应有序项的首个执行载体。",
|
||||
"Analysis 分支臂、最近 Item 和项内首个载体。",
|
||||
Manual
|
||||
),
|
||||
rule!(
|
||||
@@ -112,8 +112,8 @@ pub const CATALOG: &[RuleSpec] = &[
|
||||
Warning,
|
||||
"分支臂不属于同一列表的相邻项",
|
||||
"读者无法把条件臂与默认臂作为一组扫描。",
|
||||
"将 if/else 放入同一有序列表的相邻兄弟 Item。",
|
||||
"匹配 Branch 的 if/else 载体及其 List 祖先。",
|
||||
"将同组分支臂按源码顺序放入同一有序列表的相邻兄弟 Item。",
|
||||
"已关联的分支臂载体及其 List 祖先。",
|
||||
Manual
|
||||
),
|
||||
rule!(
|
||||
@@ -131,7 +131,7 @@ pub const CATALOG: &[RuleSpec] = &[
|
||||
"循环头不在无序列表项开头",
|
||||
"读者看不到循环体的视觉边界。",
|
||||
"让 while 成为无序列表项的首个执行载体。",
|
||||
"IR Loop、最近 Item、List ordered 属性及首个载体。",
|
||||
"Analysis 循环、最近 Item、List ordered 属性及首个载体。",
|
||||
Manual
|
||||
),
|
||||
rule!(
|
||||
@@ -149,7 +149,7 @@ pub const CATALOG: &[RuleSpec] = &[
|
||||
"执行嵌套与列表嵌套不一致",
|
||||
"视觉层级会误导实际控制范围。",
|
||||
"按真实 AST 调整嵌套项,使控制体属于对应容器。",
|
||||
"语义控制树与 Markdown Item 祖先链对照。",
|
||||
"语义父体、最近循环目标与 Markdown 容器祖先链对照。",
|
||||
Manual
|
||||
),
|
||||
rule!(
|
||||
@@ -192,8 +192,8 @@ pub const CATALOG: &[RuleSpec] = &[
|
||||
"MQD-STYLE-001",
|
||||
Info,
|
||||
"执行载体不符合推荐视觉约定",
|
||||
"一致的载体风格有助于扫描赋值和返回。",
|
||||
"可为 return 使用斜体、普通赋值使用粗体;不得借此改变语义。",
|
||||
"一致的载体风格有助于扫描控制、赋值和返回。",
|
||||
"以行内代码标记控制头、end、break 和 continue,以斜体标记 return,以粗体标记普通赋值。",
|
||||
"载体 AST 类型与已确认的语句类型。",
|
||||
Manual
|
||||
),
|
||||
|
||||
+53
-51
@@ -3,13 +3,13 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
alignment::{node_span, ControlKind, ReadableControlTree},
|
||||
alignment::{node_span, ReadableControlTree},
|
||||
diagnostics::Diagnostic,
|
||||
input::{CheckDiagnostic, SourceDocument},
|
||||
metrics::narrative_count,
|
||||
model::{
|
||||
effect_sites, semantic_nodes, AnalysisFunction, Carrier, CarrierKind, HeadingMode,
|
||||
MarkdownTree, NodeId, ProseFragment,
|
||||
effect_sites, statements, AnalysisFunction, Carrier, CarrierKind, HeadingMode,
|
||||
HeadingSegment, MarkdownTree, ProseFragment, Span, StatementKind,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -34,34 +34,33 @@ pub(crate) fn check_supplemental_function(
|
||||
|
||||
pub fn check_entry_without_analysis(document: &SourceDocument) -> Vec<Diagnostic> {
|
||||
let markdown = &document.markdown;
|
||||
let mut diagnostics = Vec::new();
|
||||
for heading in markdown
|
||||
markdown
|
||||
.headings
|
||||
.iter()
|
||||
.filter(|heading| heading.function == Some(heading.node))
|
||||
{
|
||||
let carriers: Vec<_> = markdown
|
||||
.carriers
|
||||
.iter()
|
||||
.filter(|carrier| carrier.function == Some(heading.node))
|
||||
.collect();
|
||||
let has_entry = markdown
|
||||
.prose_fragments(heading.node)
|
||||
.iter()
|
||||
.any(|fragment| {
|
||||
narrative_count(&fragment.text) > 0
|
||||
&& carriers
|
||||
.first()
|
||||
.is_none_or(|carrier| fragment.span.end <= carrier.span.start)
|
||||
});
|
||||
if !has_entry {
|
||||
diagnostics.push(
|
||||
Diagnostic::new("MQD-DOC-001", markdown.nodes[heading.node].span)
|
||||
.with_function(&heading.name),
|
||||
);
|
||||
}
|
||||
}
|
||||
diagnostics
|
||||
.filter_map(|heading| check_entry_for_heading(markdown, heading))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn check_entry_for_heading(
|
||||
markdown: &MarkdownTree,
|
||||
heading: &HeadingSegment,
|
||||
) -> Option<Diagnostic> {
|
||||
let first = markdown
|
||||
.carriers
|
||||
.iter()
|
||||
.find(|carrier| carrier.function == Some(heading.node));
|
||||
let has_entry = markdown
|
||||
.prose_fragments(heading.node)
|
||||
.iter()
|
||||
.any(|fragment| {
|
||||
narrative_count(&fragment.text) > 0
|
||||
&& first.is_none_or(|carrier| fragment.span.end <= carrier.span.start)
|
||||
});
|
||||
(!has_entry).then(|| {
|
||||
Diagnostic::new("MQD-DOC-001", markdown.nodes[heading.node].span)
|
||||
.with_function(&heading.name)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn check_heading_boundary(
|
||||
@@ -277,40 +276,43 @@ fn style_rule(
|
||||
tree: &ReadableControlTree,
|
||||
) -> Vec<Diagnostic> {
|
||||
let carriers = function_carriers(markdown, analysis);
|
||||
let mut expected: BTreeMap<NodeId, CarrierKind> = BTreeMap::new();
|
||||
let mut expected: BTreeMap<Span, CarrierKind> = statements(&analysis.body)
|
||||
.filter_map(|statement| {
|
||||
let kind = match statement.kind {
|
||||
StatementKind::Assign => CarrierKind::Strong,
|
||||
StatementKind::Return => CarrierKind::Emph,
|
||||
_ => return None,
|
||||
};
|
||||
Some((statement.span, kind))
|
||||
})
|
||||
.collect();
|
||||
if analysis.signature.get("kind").and_then(Value::as_str) == Some("explicit") {
|
||||
if let Some(signature) = carriers.first() {
|
||||
expected.insert(signature.node, CarrierKind::Code);
|
||||
}
|
||||
}
|
||||
for node in semantic_nodes(&analysis.body) {
|
||||
let Some(span) = node_span(node) else {
|
||||
continue;
|
||||
};
|
||||
let kind = match node.get("kind").and_then(Value::as_str) {
|
||||
Some("assign") => CarrierKind::Strong,
|
||||
Some("return") => CarrierKind::Emph,
|
||||
_ => continue,
|
||||
};
|
||||
if let Some(carrier) = carriers.iter().find(|carrier| carrier.span == span) {
|
||||
expected.insert(carrier.node, kind);
|
||||
expected.insert(signature.span, CarrierKind::Code);
|
||||
}
|
||||
}
|
||||
for control in &tree.controls {
|
||||
expected.insert(control.opener.node, CarrierKind::Code);
|
||||
if control.kind == ControlKind::Branch {
|
||||
if let Some(carrier) = control.else_carrier() {
|
||||
expected.insert(carrier.node, CarrierKind::Code);
|
||||
}
|
||||
}
|
||||
expected.insert(control.opener.span, CarrierKind::Code);
|
||||
expected.extend(
|
||||
control
|
||||
.arms
|
||||
.iter()
|
||||
.skip(1)
|
||||
.map(|arm| (arm.carrier.span, CarrierKind::Code)),
|
||||
);
|
||||
if let Some(carrier) = &control.end {
|
||||
expected.insert(carrier.node, CarrierKind::Code);
|
||||
expected.insert(carrier.span, CarrierKind::Code);
|
||||
}
|
||||
}
|
||||
expected.extend(
|
||||
tree.jumps
|
||||
.iter()
|
||||
.map(|jump| (jump.carrier.span, CarrierKind::Code)),
|
||||
);
|
||||
carriers
|
||||
.iter()
|
||||
.filter_map(|carrier| {
|
||||
let expected_kind = expected.get(&carrier.node)?;
|
||||
let expected_kind = expected.get(&carrier.span)?;
|
||||
if carrier.kind == *expected_kind {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -291,3 +291,155 @@ fn a_branch_body_outside_its_item_is_a_layout_mismatch() {
|
||||
assert_complete(&project);
|
||||
assert_has(&project, "MQD-LOOP-003");
|
||||
}
|
||||
|
||||
fn rc2_available() -> bool {
|
||||
std::env::var_os("MARQDO_BIN").is_some_and(|binary| {
|
||||
std::process::Command::new(binary)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.unwrap()
|
||||
.stdout
|
||||
.ends_with(b"3.0.0-rc.2\n")
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rc2_branch_rules_anchor_each_affected_arm() {
|
||||
if !rc2_available() {
|
||||
return;
|
||||
}
|
||||
let good = include_str!("fixtures/rc2/multi-arm.mq.md");
|
||||
assert_no_control_rules(&load(good).unwrap());
|
||||
for (source, rule, anchor, related) in [
|
||||
(
|
||||
good.replace("3. `else if false`", " `else if false`"),
|
||||
"MQD-BRANCH-001",
|
||||
"2. `else if true`",
|
||||
"`else if false`",
|
||||
),
|
||||
(
|
||||
good.replace("3. `else if false`", "3. 先解释 `else if false`"),
|
||||
"MQD-BRANCH-002",
|
||||
"`else if false`",
|
||||
"3. 先解释",
|
||||
),
|
||||
(
|
||||
good.replace(
|
||||
"3. `else if false`",
|
||||
"3. 提供阅读间隔。\n4. `else if false`",
|
||||
),
|
||||
"MQD-BRANCH-003",
|
||||
"`else if true`",
|
||||
"`else if false`",
|
||||
),
|
||||
(
|
||||
good.replace(
|
||||
"3. `else if false`",
|
||||
"\n这里结束前一个列表。\n\n1. `else if false`",
|
||||
),
|
||||
"MQD-BRANCH-003",
|
||||
"`else if true`",
|
||||
"`else if false`",
|
||||
),
|
||||
(
|
||||
good.replace(":最后一个条件。", ""),
|
||||
"MQD-BRANCH-004",
|
||||
"`else if false`",
|
||||
"3. `else if false`",
|
||||
),
|
||||
(
|
||||
good.replace(" *return 3*", "\n*return 3*\n"),
|
||||
"MQD-LOOP-003",
|
||||
"*return 3*",
|
||||
"`else if false`",
|
||||
),
|
||||
(
|
||||
good.replace("\n`end`", "\n `end`"),
|
||||
"MQD-CTRL-001",
|
||||
"`end`",
|
||||
"`if false`",
|
||||
),
|
||||
] {
|
||||
let project = load(&source).unwrap();
|
||||
assert_complete(&project);
|
||||
let document = &project.documents[0];
|
||||
let diagnostics = check_document(document);
|
||||
assert!(
|
||||
diagnostics.iter().any(|diagnostic| {
|
||||
diagnostic.id == rule
|
||||
&& document
|
||||
.source
|
||||
.slice(diagnostic.span)
|
||||
.unwrap()
|
||||
.starts_with(anchor)
|
||||
&& diagnostic
|
||||
.related_spans
|
||||
.iter()
|
||||
.any(|span| document.source.slice(*span).unwrap().starts_with(related))
|
||||
}),
|
||||
"未找到 {rule} 的 {anchor} / {related}: {diagnostics:?}"
|
||||
);
|
||||
if rule == "MQD-CTRL-001" {
|
||||
assert_eq!(
|
||||
diagnostics
|
||||
.iter()
|
||||
.filter(|diagnostic| diagnostic.id == rule)
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rc2_jump_rules_check_the_arm_container_and_carrier_style() {
|
||||
if !rc2_available() {
|
||||
return;
|
||||
}
|
||||
let good = include_str!("fixtures/rc2/loop-jumps.mq.md");
|
||||
assert_no_control_rules(&load(good).unwrap());
|
||||
let styled = good
|
||||
.replace(" `continue`", " *continue*")
|
||||
.replace("`else if true`", "**else if true**");
|
||||
let detached = "## @exec main\n\n根据条件停止扫描。\n\n`while true`\n\n1. `if false`:忽略本轮。\n\n `continue`\n\n2. `else if true`:结束扫描。\n\n*break*\n\n`end`\n\n`end`\n\n*return 1*\n";
|
||||
let config = marqdo_lint::config::LintConfig::default()
|
||||
.resolve(None)
|
||||
.unwrap();
|
||||
for (source, expected) in [
|
||||
(
|
||||
styled.as_str(),
|
||||
vec![
|
||||
("MQD-STYLE-001", "*continue*"),
|
||||
("MQD-STYLE-001", "**else if true**"),
|
||||
],
|
||||
),
|
||||
(
|
||||
detached,
|
||||
vec![("MQD-LOOP-003", "*break*"), ("MQD-STYLE-001", "*break*")],
|
||||
),
|
||||
] {
|
||||
let project = load(source).unwrap();
|
||||
assert_complete(&project);
|
||||
let document = &project.documents[0];
|
||||
let result = marqdo_lint::engine::analyze_document(document, &config);
|
||||
assert!(
|
||||
result.alignment_issues.is_empty(),
|
||||
"{:?}",
|
||||
result.alignment_issues
|
||||
);
|
||||
let diagnostics = result.diagnostics;
|
||||
for (id, payload) in expected {
|
||||
assert!(
|
||||
diagnostics.iter().any(|diagnostic| {
|
||||
diagnostic.id == id
|
||||
&& document.source.slice(diagnostic.span).unwrap() == payload
|
||||
}),
|
||||
"缺少 {id} {payload}: {diagnostics:?}"
|
||||
);
|
||||
}
|
||||
if source == styled {
|
||||
assert_eq!(result.metrics[0].statement_count, 9);
|
||||
}
|
||||
assert!(!result.metrics[0].has_explicit_effects);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user