From 344ef28870941dd003874cb122e5c3c14faae1cd Mon Sep 17 00:00:00 2001 From: cflmy Date: Mon, 23 Nov 2026 19:10:56 +0800 Subject: [PATCH] feat: complete rule evidence and frozen review fixtures --- docs/ARCHITECTURE.md | 1 + docs/PROTOCOL_BASELINE.md | 2 +- docs/RULES.md | 28 ++ examples/bad/branches-unlisted.mq.md | 21 + examples/render_fixtures.rs | 35 +- examples/rendered/branches-unlisted.html | 18 + schemas/marqdo-lint-v1.schema.json | 40 +- src/alignment/mod.rs | 36 +- src/cli/mod.rs | 40 +- src/config/mod.rs | 11 +- src/diagnostics/report.rs | 25 +- src/engine.rs | 68 +-- src/fix/mod.rs | 110 +++-- src/input/marqdo.rs | 77 +++- src/input/mod.rs | 4 +- src/input/project.rs | 16 +- src/metrics/mod.rs | 63 ++- src/model/analysis.rs | 46 +- src/model/mod.rs | 6 +- src/rules/control.rs | 160 +++++-- src/rules/documentation.rs | 11 +- src/rules/mod.rs | 186 +++++++- src/rules/supplemental.rs | 236 +++++++--- tests/cli.rs | 213 ++++++++- tests/control_rules.rs | 120 +++-- tests/fixtures/golden/inventory.analysis.json | 346 ++++++++++++++ tests/fixtures/golden/inventory.ast.json | 429 ++++++++++++++++++ 27 files changed, 1992 insertions(+), 356 deletions(-) create mode 100644 docs/RULES.md create mode 100644 examples/bad/branches-unlisted.mq.md create mode 100644 examples/rendered/branches-unlisted.html create mode 100644 tests/fixtures/golden/inventory.analysis.json create mode 100644 tests/fixtures/golden/inventory.ast.json diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 67d96f7..839429f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -14,6 +14,7 @@ SourceSnapshot ── MarkdownTree ──┐ - `input`:调用公开 CLI、校验协议、读取真实 AST/Analysis,并在 AST 不可用时提供严格同配置的文档级 comrak 降级。 - `model`:保存精确字节、半开 byte span、标题段、列表项、执行载体和静态语义节点。 - `alignment`:通过 span、文档顺序和语义嵌套对齐执行与阅读结构;关联不唯一时停止相关判断。 +- `engine`:为每个函数复用同一份结构对齐和度量,并组装诊断。 - `rules`:稳定 ID、元数据与纯检测逻辑。规则不各自调用 CLI,也不分别实现输出。 - `metrics`:函数级叙述比例和解释覆盖,不把文字长度当成正确性证明。 - `diagnostics`:统一 human/JSON 渲染、排序、失败阈值和退出码。 diff --git a/docs/PROTOCOL_BASELINE.md b/docs/PROTOCOL_BASELINE.md index 830fbe1..b67a289 100644 --- a/docs/PROTOCOL_BASELINE.md +++ b/docs/PROTOCOL_BASELINE.md @@ -11,7 +11,7 @@ | 外部工具 | `marqdo.cli-tool`,schema version 1 | | Lint 输出 | `marqdo.lint`,schema version 1 | -实现只读取源码并调用 `marqdo inspect --ast --json`、`marqdo check --emit`。不得链接核心私有 crate,不得使用 `inspect --ir` 代替公开 Analysis,也不得根据旧版列表规则推断控制流。 +实现只读取源码并调用 `marqdo inspect --ast --json`、`marqdo check --json --emit`。不得链接核心私有 crate,不得使用 `inspect --ir` 代替公开 Analysis,也不得根据旧版列表规则推断控制流。 验收使用从上述提交构建并冻结的核心二进制。PATH 中较早的核心不能代替该二进制。核心二进制、源码提交和所有验证输入的摘要记录在验证报告中。 diff --git a/docs/RULES.md b/docs/RULES.md new file mode 100644 index 0000000..f8f8eb3 --- /dev/null +++ b/docs/RULES.md @@ -0,0 +1,28 @@ +# 规则与可复现样例 + +运行 `marqdo-lint explain RULE_ID` 可查看稳定 ID、损失、依据和建议。除安全守卫外,表中条目均为人工修复。所有样例可用冻结核心静态检查,文件路径相对于仓库根目录。 + +| 规则 | 默认级别 | 报告示例 | 对照示例和验证 | +|---|---|---|---| +| MQD-DOC-001 | warning | 直接返回且缺少入口说明 | 在首个载体前说明目标。运行 `doc_001_and_doc_002_check_explanation_existence_and_position` | +| MQD-DOC-002 | info | 返回附近没有结果或限制说明 | 在返回处说明单位或失败结果。同上 | +| 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-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-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-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、插件调用和索引写入。未知绑定和普通本地函数不被猜测为副作用。 + +渲染对照位于 [examples/rendered](../examples/rendered)。使用 `cargo run --locked --example render_fixtures` 按冻结 Markdown Profile 重新生成。 diff --git a/examples/bad/branches-unlisted.mq.md b/examples/bad/branches-unlisted.mq.md new file mode 100644 index 0000000..0b68b85 --- /dev/null +++ b/examples/bad/branches-unlisted.mq.md @@ -0,0 +1,21 @@ +## @exec 判断 + +根据整数是否为正,返回 1 或 0。 + +`params(x: Int)` + +**结果 = 0** + +`if x > 0` + +**结果 = 1** + +`else` + +**结果 = 0** + +`end` + +返回表示正数与否的整数。 + +*return 结果* diff --git a/examples/render_fixtures.rs b/examples/render_fixtures.rs index 65340c8..0d99e93 100644 --- a/examples/render_fixtures.rs +++ b/examples/render_fixtures.rs @@ -1,22 +1,33 @@ use std::{fs, path::Path}; -use comrak::{markdown_to_html, Options}; +use comrak::markdown_to_html; +use marqdo_lint::input::profile_options; fn main() { let manifest = Path::new(env!("CARGO_MANIFEST_DIR")); let fixtures = [ - ("examples/good/branches.mq.md", "examples/rendered/branches.html"), - ("examples/bad/branch-single-item.mq.md", "examples/rendered/branch-single-item.html"), - ("examples/nested/inventory.mq.md", "examples/rendered/inventory.html"), - ("examples/knowledge/discount.mq.md", "examples/rendered/discount.html"), + ( + "examples/good/branches.mq.md", + "examples/rendered/branches.html", + ), + ( + "examples/bad/branch-single-item.mq.md", + "examples/rendered/branch-single-item.html", + ), + ( + "examples/bad/branches-unlisted.mq.md", + "examples/rendered/branches-unlisted.html", + ), + ( + "examples/nested/inventory.mq.md", + "examples/rendered/inventory.html", + ), + ( + "examples/knowledge/discount.mq.md", + "examples/rendered/discount.html", + ), ]; - let mut options = Options::default(); - options.extension.table = true; - options.extension.strikethrough = true; - options.extension.tasklist = true; - options.extension.math_dollars = true; - options.extension.math_dollars_block = true; - options.extension.front_matter_delimiter = Some("---".to_string()); + let options = profile_options(); for (source, target) in fixtures { let source_path = manifest.join(source); diff --git a/examples/rendered/branches-unlisted.html b/examples/rendered/branches-unlisted.html new file mode 100644 index 0000000..dee6616 --- /dev/null +++ b/examples/rendered/branches-unlisted.html @@ -0,0 +1,18 @@ + + + +Marqdo Lint Review Fixture + +

@exec 判断

+

根据整数是否为正,返回 1 或 0。

+

params(x: Int)

+

结果 = 0

+

if x > 0

+

结果 = 1

+

else

+

结果 = 0

+

end

+

返回表示正数与否的整数。

+

return 结果

+ + diff --git a/schemas/marqdo-lint-v1.schema.json b/schemas/marqdo-lint-v1.schema.json index 514095b..0e45440 100644 --- a/schemas/marqdo-lint-v1.schema.json +++ b/schemas/marqdo-lint-v1.schema.json @@ -32,13 +32,51 @@ }, "additionalProperties": false }, + "nullable_span": { + "oneOf": [{"$ref": "#/$defs/span"}, {"type": "null"}] + }, + "coverage": { + "type": "object", + "required": ["entry_span", "result_anchor_span", "result_span", "repeated_prose_spans"], + "properties": { + "entry_span": {"$ref": "#/$defs/nullable_span"}, + "result_anchor_span": {"$ref": "#/$defs/nullable_span"}, + "result_span": {"$ref": "#/$defs/nullable_span"}, + "repeated_prose_spans": {"type": "array", "items": {"$ref": "#/$defs/span"}} + }, + "additionalProperties": false + }, + "function_metrics": { + "type": "object", + "required": ["function_id", "function_name", "heading_span", "n", "e", "table_n", + "statement_count", "threshold", "ratio", "status", "measurement_version", + "has_control_flow", "has_explicit_effects", "heading_segment_count", "coverage"], + "properties": { + "function_id": {"type": "string"}, + "function_name": {"type": "string"}, + "heading_span": {"$ref": "#/$defs/span"}, + "n": {"type": "integer", "minimum": 0}, + "e": {"type": "integer", "minimum": 0}, + "table_n": {"type": "integer", "minimum": 0}, + "statement_count": {"type": "integer", "minimum": 0}, + "threshold": {"type": "number", "minimum": 0, "maximum": 1}, + "ratio": {"type": ["number", "null"], "minimum": 0, "maximum": 1}, + "status": {"enum": ["applicable", "not_applicable"]}, + "measurement_version": {"const": 1}, + "has_control_flow": {"type": "boolean"}, + "has_explicit_effects": {"type": "boolean"}, + "heading_segment_count": {"type": "integer", "minimum": 0}, + "coverage": {"$ref": "#/$defs/coverage"} + }, + "additionalProperties": false + }, "metrics": { "type": "object", "required": ["narrative_ratio", "measurement_version", "functions"], "properties": { "narrative_ratio": {"type": ["number", "null"], "minimum": 0, "maximum": 1}, "measurement_version": {"const": 1}, - "functions": {"type": "array", "items": {"type": "object"}} + "functions": {"type": "array", "items": {"$ref": "#/$defs/function_metrics"}} }, "additionalProperties": false }, diff --git a/src/alignment/mod.rs b/src/alignment/mod.rs index d936520..7345a6c 100644 --- a/src/alignment/mod.rs +++ b/src/alignment/mod.rs @@ -143,13 +143,25 @@ pub fn align_function(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> R if candidates.len() != 1 { tree.issues.push(format!( "{:?} opener [{}, {}) 与 Analysis 关联数量为 {}", - expected, control.opener.span.start, control.opener.span.end, candidates.len() + expected, + control.opener.span.start, + control.opener.span.end, + candidates.len() )); continue; } 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()); + tree.issues + .push("多个载体复用了同一 Analysis 控制节点".into()); continue; } semantic_to_control[index] = Some(control_index); @@ -166,7 +178,8 @@ pub fn align_function(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> R .parent .and_then(|parent| semantic_to_control[parent]); if semantic_parent != tree.controls[*control_index].parent { - tree.issues.push("源载体嵌套与 Analysis 控制嵌套不一致".into()); + tree.issues + .push("源载体嵌套与 Analysis 控制嵌套不一致".into()); } } tree.complete = tree.issues.is_empty(); @@ -178,6 +191,7 @@ struct SemanticControl { kind: ControlKind, span: Span, condition_span: Option, + arm_count: Option, parent: Option, } @@ -192,7 +206,7 @@ fn semantic_controls(analysis: &AnalysisFunction) -> Vec { } let (Some(span), condition_span) = ( node_span(node), - node.get("condition_span").and_then(node_span), + node.get("condition_span").and_then(span_value), ) else { continue; }; @@ -205,6 +219,7 @@ fn semantic_controls(analysis: &AnalysisFunction) -> Vec { }, span, condition_span, + arm_count: node.get("arms").and_then(Value::as_array).map(Vec::len), parent, }); if kind == "branch" { @@ -230,7 +245,10 @@ fn semantic_controls(analysis: &AnalysisFunction) -> Vec { } pub fn node_span(node: &Value) -> Option { - let span = node.get("span")?; + span_value(node.get("span")?) +} + +fn span_value(span: &Value) -> Option { Some(Span::new( span.get("start")?.as_u64()? as usize, span.get("end")?.as_u64()? as usize, @@ -267,9 +285,11 @@ impl Keyword { 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") - }) + node.get("kind") + .and_then(Value::as_str) + .is_some_and(|kind| { + matches!(kind, "assign" | "expression" | "branch" | "loop" | "return") + }) }) .count() } diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 3d4f24e..2e517b7 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -14,7 +14,11 @@ use crate::{ }; #[derive(Debug, Parser)] -#[command(name = "marqdo-lint", version, about = "检查 Marqdo 可执行文档的阅读结构与说明")] +#[command( + name = "marqdo-lint", + version, + about = "检查 Marqdo 可执行文档的阅读结构与说明" +)] pub struct Cli { #[command(subcommand)] command: Option, @@ -112,7 +116,12 @@ pub fn run() -> Result { } let mut project = ProjectInput::load(&entry, &runner)?; let refusal = if cli.fix.is_some() { - let outcome = fix_project(&project, &runner, cli.dry_run, &mut std::io::stderr().lock())?; + let outcome = fix_project( + &project, + &runner, + cli.dry_run, + &mut std::io::stderr().lock(), + )?; if outcome.changed { project = ProjectInput::load(&entry, &runner)?; } @@ -127,7 +136,14 @@ pub fn run() -> Result { let path = logical_path(&project, index); let mut analysis = analyze_document(document, &effective); if document.source.path == project.entry { - analysis.diagnostics.splice(0..0, refusal.clone()); + analysis.diagnostics.extend(refusal.clone()); + analysis.diagnostics.extend(rules::check_heading_boundary( + document, + &project.core_diagnostics, + )); + analysis + .diagnostics + .sort_by(|left, right| (left.span, &left.id).cmp(&(right.span, &right.id))); } run.reports.push(DocumentReport::new( document, @@ -154,8 +170,7 @@ pub fn run() -> Result { } fn explain(id: &str, format: OutputFormat) -> Result { - let rule = rules::find(id) - .ok_or_else(|| LintError::Config(format!("未知 Rule ID:{id}")))?; + let rule = rules::find(id).ok_or_else(|| LintError::Config(format!("未知 Rule ID:{id}")))?; match format { OutputFormat::Human => println!( "{}\n级别:{:?}\n{}\n损失:{}\n建议:{}\n依据:{}\n修复:{:?}", @@ -235,11 +250,17 @@ fn discover_entries(paths: &[PathBuf]) -> Result> { if entries.is_empty() { return Err(LintError::Config("没有找到 .mq.md 输入".into())); } - let mut entries = entries.into_iter() + let mut entries = entries + .into_iter() .map(|path| fs::canonicalize(&path).map_err(|error| io(path, error))) .collect::>>()?; // Load conventional entry points before modules that they may already cover. - entries.sort_by_key(|path| (path.file_name().is_none_or(|name| name != "index.mq.md"), path.clone())); + entries.sort_by_key(|path| { + ( + path.file_name().is_none_or(|name| name != "index.mq.md"), + path.clone(), + ) + }); entries.dedup(); Ok(entries) } @@ -256,7 +277,10 @@ fn logical_path(project: &ProjectInput, index: usize) -> String { .map(|path| path.to_string_lossy().into_owned()) }) .or_else(|| { - document.module.as_ref().map(|module| module.relative_path.clone()) + document + .module + .as_ref() + .map(|module| module.relative_path.clone()) }) .unwrap_or_else(|| document.source.path.to_string_lossy().into_owned()) } diff --git a/src/config/mod.rs b/src/config/mod.rs index 504d702..12c828c 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -133,9 +133,7 @@ impl EffectiveConfig { .function .as_ref() .is_none_or(|function| Some(function) == diagnostic.function.as_ref()) - && suppression - .span - .is_none_or(|span| span == diagnostic.span) + && suppression.span.is_none_or(|span| span == diagnostic.span) }) } } @@ -222,8 +220,7 @@ impl LintConfig { self.schema_version ))); } - if !self.min_narrative_ratio.is_finite() - || !(0.0..=1.0).contains(&self.min_narrative_ratio) + if !self.min_narrative_ratio.is_finite() || !(0.0..=1.0).contains(&self.min_narrative_ratio) { return Err(LintError::Config( "min_narrative_ratio 必须位于 0.0..=1.0".into(), @@ -262,9 +259,7 @@ impl LintConfig { } fn normalize_path(path: &str) -> String { - path.replace('\\', "/") - .trim_start_matches("./") - .to_string() + path.replace('\\', "/").trim_start_matches("./").to_string() } #[cfg(test)] diff --git a/src/diagnostics/report.rs b/src/diagnostics/report.rs index 35946d5..c699471 100644 --- a/src/diagnostics/report.rs +++ b/src/diagnostics/report.rs @@ -71,7 +71,8 @@ impl DocumentReport { .iter() .map(|diagnostic| document.source.line_column(diagnostic.span.start)) .collect::>>()?; - let narrative_ratio = (analysis.metrics.len() == 1) + let narrative_ratio = (analysis_status == AnalysisStatus::Complete + && analysis.metrics.len() == 1) .then(|| analysis.metrics[0].ratio) .flatten(); Ok(Self { @@ -208,22 +209,26 @@ impl LintRun { } pub fn exit_code(&self, fail_on: FailOn) -> i32 { - if self.reports.iter().any(|report| report.analysis_status == AnalysisStatus::AnalysisIncomplete) { + if self + .reports + .iter() + .any(|report| report.analysis_status == AnalysisStatus::AnalysisIncomplete) + { return 2; } let failed = self.reports.iter().any(|report| { report.diagnostics.iter().any(|diagnostic| { - if diagnostic.id == "MQD-SAFETY-001" { + if diagnostic.id == "MQD-SAFETY-001" { return true; } match (fail_on, diagnostic.severity) { - (FailOn::Never, _) => false, - (FailOn::Info, _) => true, - (FailOn::Warning, Severity::Warning | Severity::Error) => true, - (FailOn::Error, Severity::Error) => true, - _ => false, - } - }) + (FailOn::Never, _) => false, + (FailOn::Info, _) => true, + (FailOn::Warning, Severity::Warning | Severity::Error) => true, + (FailOn::Error, Severity::Error) => true, + _ => false, + } + }) }); i32::from(failed) } diff --git a/src/engine.rs b/src/engine.rs index 7e38e98..1937bc5 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -3,10 +3,10 @@ use crate::{ config::EffectiveConfig, diagnostics::Diagnostic, input::{MarkdownOrigin, SourceDocument}, - metrics::{measure_document, FunctionNarrative}, + metrics::{measure_module_function, FunctionNarrative}, rules::{ - check_aligned, check_ast_document, check_documentation, check_entry_without_analysis, - check_semantic_document, + check_aligned, check_ast_document, check_entry_without_analysis, + check_function_documentation, check_supplemental_function, }, }; @@ -18,41 +18,47 @@ pub struct DocumentAnalysis { } pub fn analyze_document(document: &SourceDocument, config: &EffectiveConfig) -> DocumentAnalysis { + let markdown = &document.markdown; + let mut diagnostics = check_ast_document(document); + let mut metrics = Vec::new(); let mut alignment_issues = Vec::new(); - let module = document.module.as_ref() + let module = document + .module + .as_ref() .filter(|_| document.markdown_origin == MarkdownOrigin::MarqdoInspect); - let mut diagnostics = if let Some(module) = module { - let mut diagnostics = Vec::new(); + if let Some(module) = module { for function in &module.functions { - let tree = align_function(&document.markdown, function); - if tree.complete { - diagnostics.extend(check_aligned(&document.markdown, function, &tree)); - } else { - alignment_issues.extend(tree.issues.iter().map(|issue| { - format!("{}:{}", function.local_name, issue) - })); + let tree = align_function(markdown, function); + if !tree.complete { + alignment_issues.extend( + tree.issues + .iter() + .map(|issue| format!("{}:{}", function.local_name, issue)), + ); + continue; + } + diagnostics.extend(check_aligned(markdown, function, &tree)); + diagnostics.extend(check_supplemental_function( + markdown, + function, + &module.calls, + &tree, + )); + if let Some(narrative) = + measure_module_function(markdown, function, &module.calls, config.narrative) + { + diagnostics.extend(check_function_documentation( + markdown, + &narrative, + config.narrative, + )); + metrics.push(narrative); } } - diagnostics.extend(check_documentation(document, config.narrative)); - diagnostics.extend(check_semantic_document(document)); - diagnostics } else { - let mut diagnostics = check_ast_document(document); diagnostics.extend(check_entry_without_analysis(document)); - diagnostics - }; - diagnostics.sort_by(|left, right| { - (left.span.start, left.span.end, &left.id).cmp(&( - right.span.start, - right.span.end, - &right.id, - )) - }); - let metrics = if module.is_some() { - measure_document(document, config.narrative) - } else { - Vec::new() - }; + } + diagnostics.sort_by(|left, right| (left.span, &left.id).cmp(&(right.span, &right.id))); DocumentAnalysis { diagnostics, metrics, diff --git a/src/fix/mod.rs b/src/fix/mod.rs index f9de285..cd47dd9 100644 --- a/src/fix/mod.rs +++ b/src/fix/mod.rs @@ -42,7 +42,10 @@ pub fn fix_project( }) .collect::(); if candidates.is_empty() { - return Ok(FixOutcome { changed: false, diagnostic: None }); + return Ok(FixOutcome { + changed: false, + diagnostic: None, + }); } if let Err(error) = verify(project, runner, &candidates) { @@ -59,12 +62,19 @@ pub fn fix_project( let mut pending = Vec::new(); for document in &project.documents { let path = &document.source.path; - let Some(candidate) = candidates.get(path) else { continue }; + let Some(candidate) = candidates.get(path) else { + continue; + }; let diff = TextDiff::from_lines(document.source.text(), candidate); - writeln!(output, "{}", diff.unified_diff().header( - &format!("{} (原文)", path.display()), - &format!("{} (候选)", path.display()), - )).map_err(|error| io("diff 输出", error))?; + writeln!( + output, + "{}", + diff.unified_diff().header( + &format!("{} (原文)", path.display()), + &format!("{} (候选)", path.display()), + ) + ) + .map_err(|error| io("diff 输出", error))?; if !dry_run { pending.push((path, prepare_replacement(path, candidate)?)); } @@ -73,7 +83,10 @@ pub fn fix_project( for (path, file) in pending { file.persist(path).map_err(|error| io(path, error.error))?; } - Ok(FixOutcome { changed: !dry_run, diagnostic: None }) + Ok(FixOutcome { + changed: !dry_run, + diagnostic: None, + }) } fn whitespace_candidate(original: &str) -> String { @@ -92,9 +105,11 @@ fn whitespace_candidate(original: &str) -> String { candidate.push_str(ending); } if !candidate.is_empty() && !candidate.ends_with('\n') { - let ending = if original.lines().next().is_some_and(|line| { - original[line.len()..].starts_with("\r\n") - }) { + let ending = if original + .lines() + .next() + .is_some_and(|line| original[line.len()..].starts_with("\r\n")) + { "\r\n" } else { "\n" @@ -112,7 +127,9 @@ fn verify(project: &ProjectInput, runner: &MarqdoRunner, candidates: &Candidates for name in ["marqdo.yaml", "marqdo.lock"] { let file = root.join(name); match fs::read(&file) { - Ok(bytes) => fs::write(staged.path().join(name), bytes).map_err(|error| io(&file, error))?, + Ok(bytes) => { + fs::write(staged.path().join(name), bytes).map_err(|error| io(&file, error))? + } Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(io(&file, error)), } @@ -123,17 +140,28 @@ fn verify(project: &ProjectInput, runner: &MarqdoRunner, candidates: &Candidates let shadow = staged.path().join(relative_to(path, &root)?); let parent = shadow.parent().expect("staging file has a parent"); fs::create_dir_all(parent).map_err(|error| io(parent, error))?; - let bytes = candidates.get(path) - .map_or(document.source.bytes.as_slice(), |candidate| candidate.as_bytes()); + let bytes = candidates + .get(path) + .map_or(document.source.bytes.as_slice(), |candidate| { + candidate.as_bytes() + }); fs::write(&shadow, bytes).map_err(|error| io(&shadow, error))?; } let entry = staged.path().join(relative_to(&project.entry, &root)?); let checked = ProjectInput::load(entry, runner)?; require_complete(&checked)?; - let original = project.analysis.as_ref().expect("checked by require_complete"); - let revised = checked.analysis.as_ref().expect("checked by require_complete"); - let changed_modules: Vec<_> = project.documents.iter() + let original = project + .analysis + .as_ref() + .expect("checked by require_complete"); + let revised = checked + .analysis + .as_ref() + .expect("checked by require_complete"); + let changed_modules: Vec<_> = project + .documents + .iter() .filter(|document| candidates.contains_key(&document.source.path)) .filter_map(|document| document.module.as_ref().map(|module| module.id.as_str())) .collect(); @@ -149,10 +177,17 @@ fn verify(project: &ProjectInput, runner: &MarqdoRunner, candidates: &Candidates continue; } let shadow = staged.path().join(relative_to(path, &root)?); - let revised = checked.documents.iter().find(|candidate| candidate.source.path == shadow) + let revised = checked + .documents + .iter() + .find(|candidate| candidate.source.path == shadow) .ok_or_else(|| refusal("候选文档缺少 Analysis 模块"))?; let payloads = |document: &crate::input::SourceDocument| { - document.markdown.carriers.iter().map(|carrier| (carrier.kind, carrier.payload.clone())) + document + .markdown + .carriers + .iter() + .map(|carrier| (carrier.kind, carrier.payload.clone())) .collect::>() }; @@ -174,9 +209,10 @@ fn require_complete(project: &ProjectInput) -> Result<()> { for document in &project.documents { if document.markdown_origin != MarkdownOrigin::MarqdoInspect || document.module.as_ref().is_none_or(|module| { - module.functions.iter().any(|function| { - !align_function(&document.markdown, function).complete - }) + module + .functions + .iter() + .any(|function| !align_function(&document.markdown, function).complete) }) { return Err(refusal("公开 AST 与 Analysis 无法完整对齐")); @@ -195,8 +231,14 @@ fn analysis_fingerprint(analysis: &Value, changed_modules: &[&str]) -> Value { } if let Some(modules) = normalized["modules"].as_array_mut() { for module in modules { - if module["id"].as_str().is_some_and(|id| changed_modules.contains(&id)) { - module.as_object_mut().expect("module id is a field").remove("source_digest"); + if module["id"] + .as_str() + .is_some_and(|id| changed_modules.contains(&id)) + { + module + .as_object_mut() + .expect("module id is a field") + .remove("source_digest"); } } } @@ -214,9 +256,13 @@ fn strip_spans(value: &mut Value) { match value { Value::Object(fields) => { fields.retain(|key, field| { - let position = matches!(key.as_str(), "span" | "heading_span" | "condition_span" | "key_span"); + let position = matches!( + key.as_str(), + "span" | "heading_span" | "condition_span" | "key_span" + ); let span = field.as_object().is_some_and(|object| { - object.len() == 2 && object.get("start").and_then(Value::as_u64).is_some() + object.len() == 2 + && object.get("start").and_then(Value::as_u64).is_some() && object.get("end").and_then(Value::as_u64).is_some() }); !(position && (span || field.is_null())) @@ -247,8 +293,11 @@ fn prepare_replacement(path: &Path, candidate: &str) -> Result { let mut file = NamedTempFile::new_in(path.parent().expect("canonical path has parent")) .map_err(|error| io(path, error))?; let metadata = fs::metadata(path).map_err(|error| io(path, error))?; - file.write_all(candidate.as_bytes()).map_err(|error| io(path, error))?; - file.as_file().set_permissions(metadata.permissions()).map_err(|error| io(path, error))?; + file.write_all(candidate.as_bytes()) + .map_err(|error| io(path, error))?; + file.as_file() + .set_permissions(metadata.permissions()) + .map_err(|error| io(path, error))?; file.as_file().sync_all().map_err(|error| io(path, error))?; Ok(file) } @@ -263,11 +312,14 @@ mod tests { #[test] fn t27_verifier_rejects_a_list_layout_change_even_with_unchanged_execution() { - let Some(core) = std::env::var_os("MARQDO_BIN") else { return }; + let Some(core) = std::env::var_os("MARQDO_BIN") else { + return; + }; let runner = MarqdoRunner::discover(Some(Path::new(&core))).unwrap(); let dir = tempdir().unwrap(); let file = dir.path().join("index.mq.md"); - let original = "## @exec choice\n\n**x = 0**\n\n1. `if true`\n\n **x = 1**\n\n`end`\n\n*return x*\n"; + let original = + "## @exec choice\n\n**x = 0**\n\n1. `if true`\n\n **x = 1**\n\n`end`\n\n*return x*\n"; let revised = original.replace("1. ", "").replace(" **", "**"); fs::write(&file, original).unwrap(); let project = ProjectInput::load(&file, &runner).unwrap(); diff --git a/src/input/marqdo.rs b/src/input/marqdo.rs index 7854442..b7108c8 100644 --- a/src/input/marqdo.rs +++ b/src/input/marqdo.rs @@ -4,6 +4,7 @@ use std::{ process::{Command, Output}, }; +use serde::Deserialize; use serde_json::Value; use tempfile::NamedTempFile; @@ -19,6 +20,44 @@ pub struct CheckOutcome { pub success: bool, pub analysis: Option, pub output: String, + pub diagnostics: Vec, +} + +#[derive(Debug, Deserialize)] +pub struct CheckDiagnostic { + pub code: String, + pub severity: String, + pub file: Option, + pub line: Option, + pub column: Option, + pub message: String, + #[serde(default)] + pub hints: Vec, +} + +impl CheckDiagnostic { + fn render(&self) -> String { + let location = self + .file + .as_ref() + .map(|path| { + format!( + "{}:{}:{}: ", + path.display(), + self.line.unwrap_or(1), + self.column.unwrap_or(1) + ) + }) + .unwrap_or_default(); + let mut text = format!( + "{}[{}]: {location}{}", + self.severity, self.code, self.message + ); + for hint in &self.hints { + text.push_str(&format!("\n hint: {hint}")); + } + text + } } impl MarqdoRunner { @@ -42,7 +81,10 @@ impl MarqdoRunner { return Err(LintError::Core(format_output(&output))); } let version = String::from_utf8_lossy(&output.stdout); - let version = version.trim().strip_prefix("marqdo ").unwrap_or(version.trim()); + let version = version + .trim() + .strip_prefix("marqdo ") + .unwrap_or(version.trim()); let major = version .split('.') .next() @@ -69,7 +111,9 @@ impl MarqdoRunner { let value: Value = serde_json::from_slice(&output.stdout) .map_err(|error| LintError::Protocol(format!("inspect AST JSON 无效:{error}")))?; if value.get("command").and_then(Value::as_str) != Some("inspect") { - return Err(LintError::Protocol("inspect 输出缺少 command=inspect".into())); + return Err(LintError::Protocol( + "inspect 输出缺少 command=inspect".into(), + )); } value .get("ast") @@ -82,16 +126,27 @@ impl MarqdoRunner { let output = Command::new(&self.binary) .arg("check") .arg(file) + .arg("--json") .arg("--emit") .arg(temporary.path()) .output() .map_err(|error| io(&self.binary, error))?; - let text = format_output(&output); if !output.status.success() { + let diagnostics = check_diagnostics(&output.stdout); + let text = if diagnostics.is_empty() { + format_output(&output) + } else { + diagnostics + .iter() + .map(CheckDiagnostic::render) + .collect::>() + .join("\n") + }; return Ok(CheckOutcome { success: false, analysis: None, output: text, + diagnostics, }); } let bytes = fs::read(temporary.path()).map_err(|error| io(temporary.path(), error))?; @@ -100,7 +155,8 @@ impl MarqdoRunner { Ok(CheckOutcome { success: true, analysis: Some(analysis), - output: text, + output: String::new(), + diagnostics: Vec::new(), }) } @@ -122,3 +178,16 @@ fn format_output(output: &Output) -> String { (true, true) => format!("核心退出状态 {}", output.status), } } + +fn check_diagnostics(stdout: &[u8]) -> Vec { + #[derive(Deserialize)] + struct CheckJson { + command: String, + diagnostics: Vec, + } + + serde_json::from_slice::(stdout) + .ok() + .filter(|report| report.command == "check") + .map_or_else(Vec::new, |report| report.diagnostics) +} diff --git a/src/input/mod.rs b/src/input/mod.rs index 26e31c6..7b67024 100644 --- a/src/input/mod.rs +++ b/src/input/mod.rs @@ -3,6 +3,6 @@ mod marqdo; mod project; pub use fallback::{fallback_ast, profile_options}; -pub use marqdo::{CheckOutcome, MarqdoRunner}; -pub use project::{AnalysisStatus, MarkdownOrigin, ProjectInput, SourceDocument}; +pub use marqdo::{CheckDiagnostic, CheckOutcome, MarqdoRunner}; pub(crate) use project::project_root; +pub use project::{AnalysisStatus, MarkdownOrigin, ProjectInput, SourceDocument}; diff --git a/src/input/project.rs b/src/input/project.rs index 20df0c1..1154e13 100644 --- a/src/input/project.rs +++ b/src/input/project.rs @@ -10,7 +10,7 @@ use crate::{ model::{AnalysisModule, ExecutionProjection, MarkdownTree, SourceSnapshot}, }; -use super::{fallback_ast, MarqdoRunner}; +use super::{fallback_ast, CheckDiagnostic, MarqdoRunner}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] @@ -41,6 +41,7 @@ pub struct ProjectInput { pub analysis: Option, pub analysis_status: AnalysisStatus, pub core_output: String, + pub core_diagnostics: Vec, pub notices: Vec, } @@ -57,12 +58,13 @@ impl ProjectInput { analysis: None, analysis_status: AnalysisStatus::AnalysisIncomplete, core_output: check.output, + core_diagnostics: check.diagnostics, notices, }); } - let raw = check.analysis.ok_or_else(|| { - LintError::Protocol("核心 check 成功但没有生成 Analysis".into()) - })?; + let raw = check + .analysis + .ok_or_else(|| LintError::Protocol("核心 check 成功但没有生成 Analysis".into()))?; let analysis = ExecutionProjection::from_json(raw).map_err(LintError::Protocol)?; let root = project_root(&entry); let mut documents = Vec::new(); @@ -81,7 +83,9 @@ impl ProjectInput { } for function in &module.functions { function.span.validate(document.source.bytes.len())?; - function.heading_span.validate(document.source.bytes.len())?; + function + .heading_span + .validate(document.source.bytes.len())?; } document.module = Some(module.clone()); documents.push(document); @@ -103,6 +107,7 @@ impl ProjectInput { analysis: Some(analysis), analysis_status: AnalysisStatus::Complete, core_output: String::new(), + core_diagnostics: Vec::new(), notices, }) } @@ -117,6 +122,7 @@ impl ProjectInput { analysis: None, analysis_status: AnalysisStatus::AnalysisIncomplete, core_output: String::new(), + core_diagnostics: Vec::new(), notices, }) } diff --git a/src/metrics/mod.rs b/src/metrics/mod.rs index 9fe7906..6977ded 100644 --- a/src/metrics/mod.rs +++ b/src/metrics/mod.rs @@ -8,8 +8,8 @@ use crate::{ alignment::{node_span, statement_count}, input::SourceDocument, model::{ - semantic_nodes, AnalysisFunction, Carrier, HeadingMode, MarkdownTree, NodeId, ProseFragment, - Span, + effect_sites, semantic_nodes, AnalysisFunction, Carrier, HeadingMode, MarkdownTree, NodeId, + ProseFragment, Span, }, }; @@ -84,10 +84,23 @@ pub fn measure_document( module .functions .iter() - .filter_map(|function| measure_function(&document.markdown, function, config)) + .filter_map(|function| { + measure_module_function(&document.markdown, function, &module.calls, config) + }) .collect() } +pub(crate) fn measure_module_function( + markdown: &MarkdownTree, + function: &AnalysisFunction, + calls: &[serde_json::Value], + config: NarrativeConfig, +) -> Option { + let mut metrics = measure_function(markdown, function, config)?; + metrics.has_explicit_effects |= effect_sites(function, calls).next().is_some(); + Some(metrics) +} + pub fn measure_function( markdown: &MarkdownTree, analysis: &AnalysisFunction, @@ -115,17 +128,17 @@ pub fn measure_function( .sum(); let table_n = table_narrative_count(markdown, function); let denominator = n + e; - let entry_span = carriers.first().and_then(|first| { - prose - .iter() - .filter(|fragment| { - fragment.span.start >= markdown.nodes[function].span.end - && fragment.span.end <= first.span.start - && narrative_count(&fragment.text) > 0 - }) - .map(|fragment| fragment.span) - .min_by_key(|span| span.start) - }); + let entry_span = prose + .iter() + .filter(|fragment| { + fragment.span.start >= markdown.nodes[function].span.end + && carriers + .first() + .is_none_or(|first| fragment.span.end <= first.span.start) + && narrative_count(&fragment.text) > 0 + }) + .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)) @@ -143,9 +156,8 @@ pub fn measure_function( } else { carriers.last().copied() }; - let result_span = result_anchor.and_then(|anchor| { - result_explanation(markdown, &carriers, &prose, function, anchor) - }); + let result_span = result_anchor + .and_then(|anchor| result_explanation(markdown, &carriers, &prose, function, anchor)); let repeated_prose_spans = repeated_prose(&prose); let heading_segment_count = markdown .headings @@ -158,9 +170,10 @@ pub fn measure_function( Some("branch" | "loop") ) }); - let has_explicit_effects = analysis.effects.iter().any(|effect| { - !matches!(effect.trim(), "" | "unknown" | "none" | "pure") - }); + let has_explicit_effects = analysis + .effects + .iter() + .any(|effect| !matches!(effect.trim(), "" | "unknown" | "none" | "pure")); Some(FunctionNarrative { function_id: analysis.id.clone(), function_name: analysis.local_name.clone(), @@ -197,7 +210,9 @@ fn result_explanation( function: NodeId, anchor: &Carrier, ) -> Option { - let index = carriers.iter().position(|carrier| carrier.node == anchor.node)?; + let index = carriers + .iter() + .position(|carrier| carrier.node == anchor.node)?; let before_start = index .checked_sub(1) .map(|previous| carriers[previous].span.end) @@ -211,10 +226,8 @@ fn result_explanation( .filter(|fragment| { fragment.heading == anchor.heading && narrative_count(&fragment.text) > 0 - && ((fragment.span.start >= before_start - && fragment.span.end <= anchor.span.start) - || (fragment.span.start >= anchor.span.end - && fragment.span.end <= after_end)) + && ((fragment.span.start >= before_start && fragment.span.end <= anchor.span.start) + || (fragment.span.start >= anchor.span.end && fragment.span.end <= after_end)) }) .map(|fragment| fragment.span) .min_by_key(|span| span.start) diff --git a/src/model/analysis.rs b/src/model/analysis.rs index 67cf6d6..9d25faa 100644 --- a/src/model/analysis.rs +++ b/src/model/analysis.rs @@ -89,11 +89,20 @@ impl ExecutionProjection { } for module in &wire.modules { if module.source_digest.len() != 64 - || !module.source_digest.bytes().all(|byte| byte.is_ascii_hexdigit()) + || !module + .source_digest + .bytes() + .all(|byte| byte.is_ascii_hexdigit()) { return Err(format!("模块 {} 的 source_digest 无效", module.id)); } - if module.relative_path.starts_with('/') || module.relative_path.contains("..") { + let path = std::path::Path::new(&module.relative_path); + if module.relative_path.is_empty() + || module.relative_path.contains('\\') + || !path + .components() + .all(|component| matches!(component, std::path::Component::Normal(_))) + { return Err(format!("模块 {} 的 relative_path 不安全", module.id)); } } @@ -124,7 +133,34 @@ fn walk_node(node: &Value) -> Box + '_> { } } } - Box::new( - std::iter::once(node).chain(nested.into_iter().flat_map(|value| walk_node(value))), - ) + Box::new(std::iter::once(node).chain(nested.into_iter().flat_map(|value| walk_node(value)))) +} + +/// Spans with external effects known from public bound targets or indexed writes. +pub(crate) fn effect_sites<'a>( + function: &'a AnalysisFunction, + calls: &'a [Value], +) -> impl Iterator + 'a { + let writes = semantic_nodes(&function.body) + .filter(|node| node["kind"] == "assign" && node["target"]["kind"] == "index"); + let external = calls.iter().filter(|call| { + call["function"] == function.id.as_str() + && match call["state"].as_str() { + Some("plugin") => true, + Some("builtin") => call["target"].as_str().is_some_and(|target| { + target.starts_with("resource.") + || matches!(target, "foreign.call" | "foreign.run") + }), + Some("function") => call["target"].as_str().is_some_and(|target| { + target.starts_with("std:marqdo-stdlib@") + && (target.contains("::io.mq.md::io.") + || target.contains("::io/stream.mq.md::stream.") + || target.contains("::io/console.mq.md::console.")) + }), + _ => false, + } + }); + writes + .chain(external) + .filter_map(crate::alignment::node_span) } diff --git a/src/model/mod.rs b/src/model/mod.rs index afa4615..8d4fec3 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -3,10 +3,14 @@ mod markdown; mod source; mod span; -pub use analysis::{semantic_nodes, AnalysisFunction, AnalysisModule, CoreDiagnostic, ExecutionProjection}; +pub use analysis::{ + semantic_nodes, AnalysisFunction, AnalysisModule, CoreDiagnostic, ExecutionProjection, +}; pub use markdown::{ Carrier, CarrierKind, HeadingMode, HeadingSegment, MarkdownNode, MarkdownTree, NodeId, ProseFragment, }; pub use source::SourceSnapshot; pub use span::{LineColumn, Span}; + +pub(crate) use analysis::effect_sites; diff --git a/src/rules/control.rs b/src/rules/control.rs index ef8412b..edc6242 100644 --- a/src/rules/control.rs +++ b/src/rules/control.rs @@ -4,7 +4,8 @@ use crate::{ alignment::{align_function, node_span, ControlKind, ControlLayout, ReadableControlTree}, diagnostics::Diagnostic, input::SourceDocument, - model::{AnalysisFunction, MarkdownTree, NodeId}, + metrics::narrative_count, + model::{AnalysisFunction, Carrier, MarkdownTree, NodeId}, }; pub fn check_document(document: &SourceDocument) -> Vec { @@ -44,11 +45,10 @@ pub(crate) fn check_aligned( ControlKind::Branch => { branch_rules(markdown, analysis, tree, control, &mut diagnostics) } - ControlKind::Loop => { - loop_rules(markdown, analysis, tree, control, &mut diagnostics) - } + ControlKind::Loop => loop_rules(markdown, analysis, tree, control, &mut diagnostics), } nesting_rule(markdown, tree, index, &mut diagnostics); + body_rule(markdown, analysis, tree, control, &mut diagnostics); end_rule(markdown, tree, control, &mut diagnostics); } diagnostics.sort_by(|left, right| { @@ -73,11 +73,9 @@ fn branch_rules( .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 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) @@ -94,12 +92,11 @@ fn branch_rules( 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) + && is_item_head(markdown, item, carrier) }); if !valid { - let mut diagnostic = Diagnostic::new("MQD-BRANCH-002", carrier.span) - .with_function(&tree.function_name); + 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); } @@ -148,13 +145,11 @@ fn loop_rules( 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) + && is_item_head(markdown, item, &control.opener) }); if !valid { diagnostics.push( - Diagnostic::new("MQD-LOOP-001", control.opener.span) - .with_function(&tree.function_name), + Diagnostic::new("MQD-LOOP-001", control.opener.span).with_function(&tree.function_name), ); } let Some(item) = item else { @@ -188,15 +183,21 @@ fn nesting_rule( 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) - }) + && 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 { - let mut diagnostic = Diagnostic::new("MQD-LOOP-003", control.opener.span) - .with_function(&tree.function_name); + 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); } @@ -228,15 +229,17 @@ fn end_rule( .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) - }), + 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( @@ -247,6 +250,13 @@ 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, @@ -276,17 +286,74 @@ fn are_adjacent_ordered_siblings( else_index == if_index + 1 } -fn visual_container(markdown: &MarkdownTree, control: &ControlLayout) -> Option { - 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"); +fn visual_arm(markdown: &MarkdownTree, control: &ControlLayout, offset: usize) -> Option { + let owner = control + .else_carrier + .as_ref() + .filter(|carrier| carrier.span.start < offset) + .unwrap_or(&control.opener); + markdown.nearest(owner.node, "item") +} + +fn body_rule( + markdown: &MarkdownTree, + analysis: &AnalysisFunction, + tree: &ReadableControlTree, + control: &ControlLayout, + diagnostics: &mut Vec, +) { + let Some(semantic) = semantic_control(analysis, control) else { + return; + }; + let check_body = + |segment: &Value, opener: &Carrier, diagnostics: &mut Vec| { + let Some(item) = markdown.nearest(opener.node, "item") else { + return; + }; + if !is_item_head(markdown, item, opener) { + return; + } + for statement in segment + .get("body") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + // Nested control headers are checked separately by nesting_rule. + if !matches!( + statement["kind"].as_str(), + Some("assign" | "expression" | "return") + ) { + continue; + } + let Some(span) = node_span(statement) else { + continue; + }; + if markdown.carriers.iter().any(|carrier| { + carrier.span == span && !markdown.is_descendant(carrier.node, item) + }) { + diagnostics.push( + Diagnostic::new("MQD-LOOP-003", span) + .with_message("执行语句位于其控制项的 Markdown 子树之外") + .with_related(opener.span) + .with_function(&tree.function_name), + ); + } + } + }; + match control.kind { + ControlKind::Branch => { + if let Some(arms) = semantic.get("arms").and_then(Value::as_array) { + for (arm, opener) in arms + .iter() + .zip(std::iter::once(&control.opener).chain(control.else_carrier.iter())) + { + check_body(arm, opener, diagnostics); + } } } + ControlKind::Loop => check_body(semantic, &control.opener, diagnostics), } - Some(item) } fn item_has_prose_after( @@ -295,11 +362,14 @@ fn item_has_prose_after( 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() - }) + 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 semantic_control<'a>( @@ -334,4 +404,4 @@ fn loop_contains_statements(analysis: &AnalysisFunction, control: &ControlLayout .and_then(|node| node.get("body")) .and_then(Value::as_array) .is_some_and(|body| !body.is_empty()) -} \ No newline at end of file +} diff --git a/src/rules/documentation.rs b/src/rules/documentation.rs index 0f4cb2e..5a57304 100644 --- a/src/rules/documentation.rs +++ b/src/rules/documentation.rs @@ -1,21 +1,20 @@ use crate::{ diagnostics::Diagnostic, input::SourceDocument, - metrics::{measure_function, FunctionNarrative, NarrativeConfig}, + metrics::{measure_module_function, FunctionNarrative, NarrativeConfig}, model::MarkdownTree, rules::Severity, }; -pub fn check_documentation( - document: &SourceDocument, - config: NarrativeConfig, -) -> Vec { +pub fn check_documentation(document: &SourceDocument, config: NarrativeConfig) -> Vec { let Some(module) = &document.module else { return Vec::new(); }; let mut diagnostics = Vec::new(); for function in &module.functions { - if let Some(metrics) = measure_function(&document.markdown, function, config) { + if let Some(metrics) = + measure_module_function(&document.markdown, function, &module.calls, config) + { diagnostics.extend(check_function_documentation( &document.markdown, &metrics, diff --git a/src/rules/mod.rs b/src/rules/mod.rs index 0bf7a26..edcd9ba 100644 --- a/src/rules/mod.rs +++ b/src/rules/mod.rs @@ -5,9 +5,9 @@ mod supplemental; pub(crate) use control::check_aligned; 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_semantic_document, -}; +pub use supplemental::{check_ast_document, check_entry_without_analysis, check_heading_boundary}; + +pub(crate) use supplemental::check_supplemental_function; use serde::{Deserialize, Serialize}; @@ -53,24 +53,168 @@ macro_rules! rule { } pub const CATALOG: &[RuleSpec] = &[ - rule!("MQD-DOC-001", Warning, "公开函数缺少入口目的说明", "读者无法在语句开始前确认函数目标。", "在首个执行载体前说明函数做什么及产生什么结果。", "Exec H2 与首个执行载体之间的普通文本节点。", Manual), - rule!("MQD-DOC-002", Info, "缺少结果或异常边界说明", "读者难以确认返回单位、失败结果或不可用情形。", "在返回语句附近说明结果与限制。", "函数末尾 Exec 段的普通叙述和 return 节点。", Manual), - rule!("MQD-DOC-003", Warning, "复杂函数叙述比例低于阈值", "执行载荷缺少必要叙述,阅读负担过高。", "解释关键控制和设计理由,不堆砌空洞文字。", "函数 Exec 段的 N/E 代码点计数及语句规模。", Manual), - rule!("MQD-DOC-004", Info, "长函数章节组织不合适", "长函数缺少业务阶段,或章节过碎影响连续阅读。", "按自然业务阶段组织 H3+ 阅读章节。", "函数语句规模和 Exec H3+ 分段分布。", Manual), - rule!("MQD-BRANCH-001", Warning, "一个编号项包含整段分支", "读者看不到互相对等的分支臂。", "把 if 与 else 分别放入同一有序列表的相邻兄弟项。", "IR Branch 与 AST Item 子树中的 if/else 载体。", Manual), - rule!("MQD-BRANCH-002", Warning, "分支头不在有序列表项开头", "视觉分支与实际执行分支不一致。", "让 if/else 成为对应有序项的首个执行载体。", "IR 控制节点、最近 Item 和项内首个载体。", Manual), - rule!("MQD-BRANCH-003", Warning, "分支臂不属于同一列表的相邻项", "读者无法把条件臂与默认臂作为一组扫描。", "将 if/else 放入同一有序列表的相邻兄弟 Item。", "匹配 Branch 的 if/else 载体及其 List 祖先。", Manual), - rule!("MQD-BRANCH-004", Info, "非平凡分支缺少说明", "条件表达式本身不能解释业务意义。", "在分支项头后说明判断意义和该臂作用。", "分支 Item 中控制载体之外的普通叙述。", Manual), - rule!("MQD-LOOP-001", Warning, "循环头不在无序列表项开头", "读者看不到循环体的视觉边界。", "让 while 成为无序列表项的首个执行载体。", "IR Loop、最近 Item、List ordered 属性及首个载体。", Manual), - rule!("MQD-LOOP-002", Info, "循环缺少处理或终止说明", "读者需要自行推断每轮工作和终止条件。", "在循环项附近说明处理对象与终止方式。", "循环 Item 的普通叙述与 Loop 条件。", Manual), - rule!("MQD-LOOP-003", Warning, "执行嵌套与列表嵌套不一致", "视觉层级会误导实际控制范围。", "按真实 AST 调整嵌套项,使控制体属于对应容器。", "语义控制树与 Markdown Item 祖先链对照。", Manual), - rule!("MQD-CTRL-001", Warning, "end 与控制块视觉边界脱节", "读者难以判断控制块在哪里关闭。", "把分支 end 放在列表后,把循环 end 放在对应循环项末尾。", "唯一匹配的 end 载体及其控制节点和 Item 祖先。", Manual), - rule!("MQD-PROSE-001", Warning, "解释文字混入意外执行载体", "粗体、斜体和行内代码在 Exec 中可能执行而非强调。", "改成普通叙述,或把富文本移到 Knowledge。", "Exec AST 载体、周边叙述及核心载荷诊断。", Manual), - rule!("MQD-PROSE-002", Info, "显式副作用缺少临近说明", "读者无法确认授权、失败情形和后果。", "在副作用载体附近说明效果与约束。", "Analysis 可证明的调用绑定或内存写入及邻近叙述。", Manual), - rule!("MQD-PARAM-001", Info, "公开输入缺少含义或约束", "调用者难以确认参数单位、范围和用途。", "在签名前后解释公开输入。", "显式 params 与相邻普通叙述的确定性覆盖检查。", Manual), - rule!("MQD-STYLE-001", Info, "执行载体不符合推荐视觉约定", "一致的载体风格有助于扫描赋值和返回。", "可为 return 使用斜体、普通赋值使用粗体;不得借此改变语义。", "载体 AST 类型与已确认的语句类型。", Manual), - rule!("MQD-KNOW-001", Warning, "Knowledge/Exec 切分破坏连续阅读", "过度切分会割裂说明,跨段控制则无法正确闭合。", "简单说明留在 Exec;控制块在同一 heading 段闭合。", "heading 模式序列及核心控制边界诊断。", Manual), - rule!("MQD-SAFETY-001", Error, "自动修复无法证明语义等价", "不确定的写回可能改变程序行为。", "拒绝写回并按人工建议修改。", "修复前后规范化 AST、载荷序列和 Analysis 指纹比较。", NotApplicable), + rule!( + "MQD-DOC-001", + Warning, + "公开函数缺少入口目的说明", + "读者无法在语句开始前确认函数目标。", + "在首个执行载体前说明函数做什么及产生什么结果。", + "Exec H2 与首个执行载体之间的普通文本节点。", + Manual + ), + rule!( + "MQD-DOC-002", + Info, + "缺少结果或异常边界说明", + "读者难以确认返回单位、失败结果或不可用情形。", + "在返回语句附近说明结果与限制。", + "函数末尾 Exec 段的普通叙述和 return 节点。", + Manual + ), + rule!( + "MQD-DOC-003", + Warning, + "复杂函数叙述比例低于阈值", + "执行载荷缺少必要叙述,阅读负担过高。", + "解释关键控制和设计理由,不堆砌空洞文字。", + "函数 Exec 段的 N/E 代码点计数及语句规模。", + Manual + ), + rule!( + "MQD-DOC-004", + Info, + "长函数章节组织不合适", + "长函数缺少业务阶段,或章节过碎影响连续阅读。", + "按自然业务阶段组织 H3+ 阅读章节。", + "函数语句规模和 Exec H3+ 分段分布。", + Manual + ), + rule!( + "MQD-BRANCH-001", + Warning, + "一个编号项包含整段分支", + "读者看不到互相对等的分支臂。", + "把 if 与 else 分别放入同一有序列表的相邻兄弟项。", + "IR Branch 与 AST Item 子树中的 if/else 载体。", + Manual + ), + rule!( + "MQD-BRANCH-002", + Warning, + "分支头不在有序列表项开头", + "视觉分支与实际执行分支不一致。", + "让 if/else 成为对应有序项的首个执行载体。", + "IR 控制节点、最近 Item 和项内首个载体。", + Manual + ), + rule!( + "MQD-BRANCH-003", + Warning, + "分支臂不属于同一列表的相邻项", + "读者无法把条件臂与默认臂作为一组扫描。", + "将 if/else 放入同一有序列表的相邻兄弟 Item。", + "匹配 Branch 的 if/else 载体及其 List 祖先。", + Manual + ), + rule!( + "MQD-BRANCH-004", + Info, + "非平凡分支缺少说明", + "条件表达式本身不能解释业务意义。", + "在分支项头后说明判断意义和该臂作用。", + "分支 Item 中控制载体之外的普通叙述。", + Manual + ), + rule!( + "MQD-LOOP-001", + Warning, + "循环头不在无序列表项开头", + "读者看不到循环体的视觉边界。", + "让 while 成为无序列表项的首个执行载体。", + "IR Loop、最近 Item、List ordered 属性及首个载体。", + Manual + ), + rule!( + "MQD-LOOP-002", + Info, + "循环缺少处理或终止说明", + "读者需要自行推断每轮工作和终止条件。", + "在循环项附近说明处理对象与终止方式。", + "循环 Item 的普通叙述与 Loop 条件。", + Manual + ), + rule!( + "MQD-LOOP-003", + Warning, + "执行嵌套与列表嵌套不一致", + "视觉层级会误导实际控制范围。", + "按真实 AST 调整嵌套项,使控制体属于对应容器。", + "语义控制树与 Markdown Item 祖先链对照。", + Manual + ), + rule!( + "MQD-CTRL-001", + Warning, + "end 与控制块视觉边界脱节", + "读者难以判断控制块在哪里关闭。", + "把分支 end 放在列表后,把循环 end 放在对应循环项末尾。", + "唯一匹配的 end 载体及其控制节点和 Item 祖先。", + Manual + ), + rule!( + "MQD-PROSE-001", + Warning, + "解释文字混入意外执行载体", + "粗体、斜体和行内代码在 Exec 中可能执行而非强调。", + "改成普通叙述,或把富文本移到 Knowledge。", + "Exec AST 载体、周边叙述及核心载荷诊断。", + Manual + ), + rule!( + "MQD-PROSE-002", + Info, + "显式副作用缺少临近说明", + "读者无法确认授权、失败情形和后果。", + "在副作用载体附近说明效果与约束。", + "Analysis 可证明的调用绑定或内存写入及邻近叙述。", + Manual + ), + rule!( + "MQD-PARAM-001", + Info, + "公开输入缺少含义或约束", + "调用者难以确认参数单位、范围和用途。", + "在签名前后解释公开输入。", + "显式 params 与相邻普通叙述的确定性覆盖检查。", + Manual + ), + rule!( + "MQD-STYLE-001", + Info, + "执行载体不符合推荐视觉约定", + "一致的载体风格有助于扫描赋值和返回。", + "可为 return 使用斜体、普通赋值使用粗体;不得借此改变语义。", + "载体 AST 类型与已确认的语句类型。", + Manual + ), + rule!( + "MQD-KNOW-001", + Warning, + "Knowledge/Exec 切分破坏连续阅读", + "过度切分会割裂说明,跨段控制则无法正确闭合。", + "简单说明留在 Exec;控制块在同一 heading 段闭合。", + "heading 模式序列及核心控制边界诊断。", + Manual + ), + rule!( + "MQD-SAFETY-001", + Error, + "自动修复无法证明语义等价", + "不确定的写回可能改变程序行为。", + "拒绝写回并按人工建议修改。", + "修复前后规范化 AST、载荷序列和 Analysis 指纹比较。", + NotApplicable + ), ]; pub fn find(id: &str) -> Option<&'static RuleSpec> { diff --git a/src/rules/supplemental.rs b/src/rules/supplemental.rs index 4f7d296..0a96653 100644 --- a/src/rules/supplemental.rs +++ b/src/rules/supplemental.rs @@ -1,15 +1,15 @@ -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use serde_json::Value; use crate::{ - alignment::{align_function, node_span, ControlKind}, + alignment::{node_span, ControlKind, ReadableControlTree}, diagnostics::Diagnostic, - input::SourceDocument, + input::{CheckDiagnostic, SourceDocument}, metrics::narrative_count, model::{ - semantic_nodes, AnalysisFunction, Carrier, CarrierKind, HeadingMode, MarkdownTree, NodeId, - ProseFragment, + effect_sites, semantic_nodes, AnalysisFunction, Carrier, CarrierKind, HeadingMode, + MarkdownTree, NodeId, ProseFragment, }, }; @@ -20,16 +20,15 @@ pub fn check_ast_document(document: &SourceDocument) -> Vec { diagnostics } -pub fn check_semantic_document(document: &SourceDocument) -> Vec { - let mut diagnostics = check_ast_document(document); - let Some(module) = &document.module else { - return diagnostics; - }; - for function in &module.functions { - diagnostics.extend(effect_rule(&document.markdown, function)); - diagnostics.extend(parameter_rule(&document.markdown, function)); - diagnostics.extend(style_rule(&document.markdown, function)); - } +pub(crate) fn check_supplemental_function( + markdown: &MarkdownTree, + function: &AnalysisFunction, + calls: &[Value], + tree: &ReadableControlTree, +) -> Vec { + let mut diagnostics = effect_rule(markdown, function, calls); + diagnostics.extend(parameter_rule(markdown, function)); + diagnostics.extend(style_rule(markdown, function, tree)); diagnostics } @@ -46,12 +45,15 @@ pub fn check_entry_without_analysis(document: &SourceDocument) -> Vec 0 - && carriers - .first() - .is_none_or(|carrier| fragment.span.end <= carrier.span.start) - }); + 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) @@ -62,6 +64,70 @@ pub fn check_entry_without_analysis(document: &SourceDocument) -> Vec Vec { + let markdown = &document.markdown; + let on_line = |diagnostic: &CheckDiagnostic, carrier: &Carrier| { + diagnostic.file.as_deref() == Some(document.source.path.as_path()) + && document + .source + .line_column(carrier.span.start) + .ok() + .map(|point| point.line) + == diagnostic.line + }; + let mut diagnostics = Vec::new(); + for unclosed in core + .iter() + .filter(|diagnostic| diagnostic.code == "sem.unclosed_control") + { + let Some(opener) = markdown + .carriers + .iter() + .find(|carrier| on_line(unclosed, carrier)) + else { + continue; + }; + let Some(function) = opener.function else { + continue; + }; + let related = core + .iter() + .filter(|diagnostic| { + matches!( + diagnostic.code.as_str(), + "sem.unmatched_else" | "sem.unmatched_end" + ) + }) + .find_map(|diagnostic| { + markdown.carriers.iter().find(|carrier| { + carrier.span.start > opener.span.start + && carrier.function == Some(function) + && carrier.heading != opener.heading + && on_line(diagnostic, carrier) + }) + }); + if let Some((related, heading)) = + related.and_then(|carrier| Some((carrier, markdown.heading(carrier.heading?)?))) + { + let name = &markdown + .heading(function) + .expect("indexed function heading") + .name; + diagnostics.push( + Diagnostic::new("MQD-KNOW-001", markdown.nodes[heading.node].span) + .with_message("核心报告控制块未闭合,后续标题段的 else/end 无法关闭它") + .with_related(opener.span) + .with_related(related.span) + .with_function(name), + ); + } + } + diagnostics +} + fn prose_rule(markdown: &MarkdownTree) -> Vec { let mut diagnostics = Vec::new(); for carrier in &markdown.carriers { @@ -101,27 +167,60 @@ fn prose_rule(markdown: &MarkdownTree) -> Vec { fn knowledge_rule(markdown: &MarkdownTree) -> Vec { markdown .headings - .iter() - .filter(|heading| { - heading.level > 2 - && heading.function.is_some() - && heading.mode == HeadingMode::Knowledge - }) - .map(|heading| { - let function = heading.function.and_then(|function| markdown.heading(function)); - let mut diagnostic = Diagnostic::new( - "MQD-KNOW-001", - markdown.nodes[heading.node].span, - ); - if let Some(function) = function { - diagnostic = diagnostic.with_function(&function.name); + .windows(3) + .filter_map(|window| { + let [before, heading, after] = window else { + return None; + }; + let function = heading.function?; + if heading.level <= 2 + || heading.mode != HeadingMode::Knowledge + || before.mode != HeadingMode::Exec + || after.mode != HeadingMode::Exec + || before.function != Some(function) + || after.function != Some(function) + || ![before.node, after.node].iter().all(|node| { + markdown + .carriers + .iter() + .any(|carrier| carrier.heading == Some(*node)) + }) + { + return None; } - diagnostic + // A single plain paragraph between two executable sections is better + // kept inline. A real knowledge section may hold rich, inert content. + let body: Vec<_> = markdown.nodes[markdown.root] + .children + .iter() + .copied() + .skip_while(|node| *node != heading.node) + .skip(1) + .take_while(|node| *node != after.node) + .collect(); + let [node] = body.as_slice() else { return None }; + let paragraph = &markdown.nodes[*node]; + if paragraph.kind != "paragraph" + || !paragraph.children.iter().all(|child| { + matches!(markdown.nodes[*child].kind.as_str(), "text" | "softbreak") + }) + { + return None; + } + let name = &markdown.heading(function)?.name; + Some( + Diagnostic::new("MQD-KNOW-001", markdown.nodes[heading.node].span) + .with_function(name), + ) }) .collect() } -fn effect_rule(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> Vec { +fn effect_rule( + markdown: &MarkdownTree, + analysis: &AnalysisFunction, + calls: &[Value], +) -> Vec { let carriers = function_carriers(markdown, analysis); let prose = markdown .headings @@ -129,22 +228,14 @@ fn effect_rule(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> Vec = effect_sites(analysis, calls) + .filter_map(|span| carriers.iter().find(|carrier| carrier.span.contains(span))) + .filter(|carrier| !has_nearby_prose(markdown, &carriers, &prose, carrier)) + .map(|carrier| carrier.span) + .collect(); + anchors + .into_iter() + .map(|span| Diagnostic::new("MQD-PROSE-002", span).with_function(&analysis.local_name)) .collect() } @@ -180,7 +271,11 @@ fn parameter_rule(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> Vec Vec { +fn style_rule( + markdown: &MarkdownTree, + analysis: &AnalysisFunction, + tree: &ReadableControlTree, +) -> Vec { let carriers = function_carriers(markdown, analysis); let mut expected: BTreeMap = BTreeMap::new(); if analysis.signature.get("kind").and_then(Value::as_str) == Some("explicit") { @@ -201,19 +296,16 @@ fn style_rule(markdown: &MarkdownTree, analysis: &AnalysisFunction) -> Vec Vec bool { - let Some(index) = carriers.iter().position(|carrier| carrier.node == anchor.node) else { + let Some(index) = carriers + .iter() + .position(|carrier| carrier.node == anchor.node) + else { return false; }; let before_start = index @@ -276,9 +368,7 @@ fn has_nearby_prose( prose.iter().any(|fragment| { fragment.heading == anchor.heading && narrative_count(&fragment.text) > 0 - && ((fragment.span.start >= before_start - && fragment.span.end <= anchor.span.start) - || (fragment.span.start >= anchor.span.end - && fragment.span.end <= after_end)) + && ((fragment.span.start >= before_start && fragment.span.end <= anchor.span.start) + || (fragment.span.start >= anchor.span.end && fragment.span.end <= after_end)) }) } diff --git a/tests/cli.rs b/tests/cli.rs index 0c3d4f4..bb0f510 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -48,31 +48,66 @@ fn reports_and_exit_codes_distinguish_style_from_unavailable_analysis() { .output() .unwrap(); assert!(output.stderr.is_empty(), "{:?}", output); - (output.status.code().unwrap(), serde_json::from_slice::(&output.stdout).unwrap()) + ( + output.status.code().unwrap(), + serde_json::from_slice::(&output.stdout).unwrap(), + ) }; let (code, result) = report(&[]); assert_eq!(code, 1, "{result}"); assert_eq!(result["analysis_status"], "complete"); assert_eq!(result["diagnostics"][0]["id"], "MQD-DOC-001"); - assert!(result["diagnostics"].as_array().unwrap().iter().any(|diagnostic| { - diagnostic["id"] == "MQD-DOC-003" && diagnostic["severity"] == "info" - })); + assert!(result["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|diagnostic| { + diagnostic["id"] == "MQD-DOC-003" && diagnostic["severity"] == "info" + })); assert_eq!(report(&["--fail-on", "error"]).0, 0); - fs::write(temp.path().join("marqdo-lint.toml"), r#" + fs::write( + temp.path().join("marqdo-lint.toml"), + r#" [[suppress]] path = "index.mq.md" rule = "MQD-DOC-001" reason = "Fixture for a deliberately short helper" -"#).unwrap(); +"#, + ) + .unwrap(); assert_eq!(report(&[]).0, 0); + let config_path = temp.path().join("marqdo-lint.toml"); + let config = fs::read_to_string(&config_path).unwrap(); + fs::write( + &config_path, + format!("{config}\n[rules]\n\"MQD-DOC-003\" = \"warning\"\n"), + ) + .unwrap(); + assert_eq!(report(&[]).0, 1); fs::copy(fixtures().join("golden/invalid-control.mq.md"), source).unwrap(); let (code, result) = report(&["--fail-on", "never"]); assert_eq!(code, 2, "{result}"); assert_eq!(result["analysis_status"], "analysis_incomplete"); assert!(result["metrics"]["narrative_ratio"].is_null()); - assert!(result["core_output"].as_str().unwrap().contains("sem.unclosed_control")); + assert!(result["core_output"] + .as_str() + .unwrap() + .contains("sem.unclosed_control")); + assert!(result["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|d| d["id"] == "MQD-KNOW-001")); + let invalid_signature = "## @exec x\n\n- `params(n: Int)`\n\n*return 1*"; + fs::write(temp.path().join("index.mq.md"), invalid_signature).unwrap(); + let (code, result) = report(&[]); + assert_eq!(code, 2, "{result}"); + assert!( + result["core_output"].as_str().unwrap().contains("params"), + "{result}" + ); } #[test] @@ -82,7 +117,15 @@ fn multi_module_run_reports_each_source_once() { } let output = lint() .current_dir(fixtures().join("multi")) - .args(["index.mq.md", "geometry.mq.md", ".", "--format", "json", "--fail-on", "never"]) + .args([ + "index.mq.md", + "geometry.mq.md", + ".", + "--format", + "json", + "--fail-on", + "never", + ]) .output() .unwrap(); assert!(output.status.success(), "{:?}", output); @@ -101,21 +144,38 @@ fn t30_frozen_core_installs_and_dispatches_lint() { let temp = tempfile::tempdir().unwrap(); let bundle = temp.path().join("bundle"); fs::create_dir_all(bundle.join("bin")).unwrap(); - fs::copy(env!("CARGO_BIN_EXE_marqdo-lint"), bundle.join("bin/marqdo-lint")).unwrap(); + fs::copy( + env!("CARGO_BIN_EXE_marqdo-lint"), + bundle.join("bin/marqdo-lint"), + ) + .unwrap(); let manifest = bundle.join("tool.json"); fs::write(&manifest, include_bytes!("../tool.json")).unwrap(); let marqdo = || { let mut command = Command::new(&core); - command.env("MARQDO_TOOL_HOME", temp.path().join("registry")) + command + .env("MARQDO_TOOL_HOME", temp.path().join("registry")) .env_remove("MARQDO_BIN"); command }; - let install = marqdo().args(["tool", "install"]).arg(manifest).output().unwrap(); + let install = marqdo() + .args(["tool", "install"]) + .arg(manifest) + .output() + .unwrap(); assert!(install.status.success(), "{:?}", install); let output = marqdo() .current_dir(fixtures().join("golden")) - .args(["lint", "branches.mq.md", "--format", "json", "--fail-on", "never"]) - .output().unwrap(); + .args([ + "lint", + "branches.mq.md", + "--format", + "json", + "--fail-on", + "never", + ]) + .output() + .unwrap(); assert!(output.status.success(), "{:?}", output); let report: Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(report["analysis_status"], "complete"); @@ -130,7 +190,11 @@ fn safe_fix_previews_then_persists_verified_whitespace_in_a_manifest_project() { let source = temp.path().join("index.mq.md"); let multi = fixtures().join("multi"); fs::copy(multi.join("marqdo.yaml"), temp.path().join("marqdo.yaml")).unwrap(); - fs::copy(multi.join("geometry.mq.md"), temp.path().join("geometry.mq.md")).unwrap(); + fs::copy( + multi.join("geometry.mq.md"), + temp.path().join("geometry.mq.md"), + ) + .unwrap(); let clean = fs::read_to_string(multi.join("index.mq.md")).unwrap(); let original = clean.replace("## @exec main\n\n", "## @exec main\n \t\n"); assert_ne!(original, clean); @@ -138,7 +202,15 @@ fn safe_fix_previews_then_persists_verified_whitespace_in_a_manifest_project() { let fix = |args: &[&str]| { lint() .current_dir(temp.path()) - .args(["index.mq.md", "--fix", "safe", "--format", "json", "--fail-on", "never"]) + .args([ + "index.mq.md", + "--fix", + "safe", + "--format", + "json", + "--fail-on", + "never", + ]) .args(args) .output() .unwrap() @@ -151,7 +223,11 @@ fn safe_fix_previews_then_persists_verified_whitespace_in_a_manifest_project() { assert!(applied.status.success(), "{:?}", applied); assert_eq!(fs::read_to_string(&source).unwrap(), clean); let repeated = fix(&[]); - assert!(repeated.status.success() && repeated.stderr.is_empty(), "{:?}", repeated); + assert!( + repeated.status.success() && repeated.stderr.is_empty(), + "{:?}", + repeated + ); } #[test] @@ -168,13 +244,108 @@ fn safe_fix_rejects_changes_to_inert_payload_and_unavailable_analysis() { fs::write(&source, original).unwrap(); let output = lint() .current_dir(temp.path()) - .args(["index.mq.md", "--fix", "safe", "--format", "json", "--fail-on", "never"]) - .output().unwrap(); + .args([ + "index.mq.md", + "--fix", + "safe", + "--format", + "json", + "--fail-on", + "never", + ]) + .output() + .unwrap(); let report: Value = serde_json::from_slice(&output.stdout).unwrap(); assert_eq!(output.status.code(), Some(code), "{report}"); - assert!(report["diagnostics"].as_array().unwrap().iter().any(|diagnostic| { - diagnostic["id"] == "MQD-SAFETY-001" - }), "{report}"); + assert!( + report["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|diagnostic| { diagnostic["id"] == "MQD-SAFETY-001" }), + "{report}" + ); assert_eq!(fs::read_to_string(&source).unwrap(), original); } } + +#[test] +fn supplemental_rules_use_bound_calls_and_allow_rich_knowledge() { + if std::env::var_os("MARQDO_BIN").is_none() { + return; + } + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("index.mq.md"); + let original = "## @exec output\n\n`params(x: Int)`\n\n**打印(x)**\n\n### @knowledge 说明\n\n这一段说明输出用途。\n\n### @exec 结果\n\n`return x`\n"; + let report = |text: &str| { + fs::write(&source, text).unwrap(); + let result = lint() + .current_dir(temp.path()) + .args(["index.mq.md", "--format", "json", "--fail-on", "never"]) + .output() + .unwrap(); + assert!(result.status.success(), "{:?}", result); + serde_json::from_slice::(&result.stdout).unwrap() + }; + let result = report(original); + assert_eq!( + result["metrics"]["functions"][0]["has_explicit_effects"], + true + ); + let has = |result: &Value, id: &str| { + result["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|diagnostic| diagnostic["id"] == id) + }; + for id in [ + "MQD-PROSE-002", + "MQD-PARAM-001", + "MQD-KNOW-001", + "MQD-STYLE-001", + ] { + assert!(has(&result, id), "{id} {result}"); + } + let improved = original + .replace( + "`params(x: Int)`", + "输入 x 使用最小货币单位。\n\n`params(x: Int)`", + ) + .replace("**打印(x)**", "向控制台写入整数以便核对。\n\n**打印(x)**") + .replace("这一段说明输出用途。", "这里的**输出**指控制台记录。") + .replace("`return x`", "*return x*"); + let result = report(&improved); + for id in [ + "MQD-PROSE-002", + "MQD-PARAM-001", + "MQD-KNOW-001", + "MQD-STYLE-001", + ] { + assert!(!has(&result, id), "{id} {result}"); + } +} + +#[test] +fn t16_exec_emphasis_inside_prose_is_not_a_comment() { + if std::env::var_os("MARQDO_BIN").is_none() { + return; + } + let temp = tempfile::tempdir().unwrap(); + fs::write( + temp.path().join("index.mq.md"), + "## @exec 示例\n\n这是 **特别重要** 的处理。\n\n*return 1*\n", + ) + .unwrap(); + let output = lint() + .current_dir(temp.path()) + .args(["index.mq.md", "--format", "json"]) + .output() + .unwrap(); + let report: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert!(report["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|d| d["id"] == "MQD-PROSE-001")); +} diff --git a/tests/control_rules.rs b/tests/control_rules.rs index d4eb997..ba1d132 100644 --- a/tests/control_rules.rs +++ b/tests/control_rules.rs @@ -23,13 +23,7 @@ fn load_example(path: &str) -> Option { None })?; let runner = MarqdoRunner::discover(Some(Path::new(&binary))).unwrap(); - Some( - ProjectInput::load( - Path::new(env!("CARGO_MANIFEST_DIR")).join(path), - &runner, - ) - .unwrap(), - ) + Some(ProjectInput::load(Path::new(env!("CARGO_MANIFEST_DIR")).join(path), &runner).unwrap()) } fn ids(project: &ProjectInput) -> Vec { @@ -68,28 +62,40 @@ fn assert_no_control_rules(project: &ProjectInput) { #[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")) + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + let directory = root.join("tests/fixtures/golden"); + for (stem, input) in [ + ("branches", directory.join("branches.mq.md")), + ("inventory", root.join("examples/nested/inventory.mq.md")), + ] { + let source = marqdo_lint::model::SourceSnapshot::load(input).unwrap(); + let ast: serde_json::Value = + serde_json::from_slice(&fs::read(directory.join(format!("{stem}.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(format!("{stem}.analysis.json"))).unwrap(), + ) .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()); + 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(); + for function in &module.functions { + let tree = marqdo_lint::alignment::align_function(&markdown, function); + assert!(tree.complete, "{stem}: {:?}", tree.issues); + } + let document = marqdo_lint::input::SourceDocument { + source, + markdown, + markdown_origin: marqdo_lint::input::MarkdownOrigin::MarqdoInspect, + module: Some(module), + }; + assert!(check_document(&document).is_empty(), "{stem}"); + } } #[test] @@ -117,7 +123,10 @@ fn t02_one_item_wrapping_whole_branch_is_branch_001() { .iter() .find(|control| control.kind == marqdo_lint::alignment::ControlKind::Branch) .unwrap(); - let item = document.markdown.nearest(branch.opener.node, "item").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") @@ -200,7 +209,10 @@ fn t11_and_t12_inert_code_regions_do_not_supply_control_or_hidden_statements() { .nodes .iter() .any(|node| node.kind == "code_block" - && node.literal.as_deref().is_some_and(|text| text.contains("end")))); + && node + .literal + .as_deref() + .is_some_and(|text| text.contains("end")))); } #[test] @@ -218,12 +230,14 @@ fn t26_task_checkbox_and_t32_legacy_keywordless_items_add_no_control_semantics() 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") - ) - })); + 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] @@ -236,18 +250,44 @@ fn semantic_nesting_outside_the_parent_list_is_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 }; + 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 }; + 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 }; + 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 }; + let Some(project) = load(branch_end_in_list) else { + return; + }; assert_has(&project, "MQD-CTRL-001"); } + +#[test] +fn prose_before_first_carrier_does_not_form_a_branch_head() { + let Some(project) = load("## @exec choose\n\n**x = 0**\n\n1. Check the input.\n\n `if true`\n\n **x = 1**\n\n`end`\n\n*return x*\n") else { return }; + assert_complete(&project); + assert_has(&project, "MQD-BRANCH-002"); +} + +#[test] +fn a_branch_body_outside_its_item_is_a_layout_mismatch() { + let Some(project) = + load("## @exec choose\n\n**x = 0**\n\n1. `if true`\n\n**x = 1**\n\n`end`\n\n*return x*\n") + else { + return; + }; + assert_complete(&project); + assert_has(&project, "MQD-LOOP-003"); +} diff --git a/tests/fixtures/golden/inventory.analysis.json b/tests/fixtures/golden/inventory.analysis.json new file mode 100644 index 0000000..44f2b71 --- /dev/null +++ b/tests/fixtures/golden/inventory.analysis.json @@ -0,0 +1,346 @@ +{ + "diagnostics": [], + "modules": [ + { + "calls": [ + { + "callee": { + "kind": "ident", + "name": "长度" + }, + "function": "root:default::inventory.mq.md::库存示例.检查库存并累计可用量", + "span": { + "end": 393, + "start": 373 + }, + "state": "builtin", + "target": "长度" + } + ], + "functions": [ + { + "body": [ + { + "kind": "assign", + "span": { + "end": 273, + "start": 259 + }, + "target": "总量", + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "0" + } + }, + { + "kind": "assign", + "span": { + "end": 289, + "start": 275 + }, + "target": "位置", + "value": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "0" + } + }, + { + "arms": [ + { + "body": [ + { + "body": [ + { + "kind": "assign", + "span": { + "end": 500, + "start": 458 + }, + "target": "总量", + "value": { + "kind": "binary", + "left": { + "kind": "variable", + "name": "总量", + "span": { + "end": 475, + "start": 469 + } + }, + "op": "add", + "right": { + "base": { + "kind": "variable", + "name": "数量列表", + "span": { + "end": 490, + "start": 478 + } + }, + "index": { + "kind": "variable", + "name": "位置", + "span": { + "end": 497, + "start": 491 + } + }, + "kind": "index", + "span": { + "end": 498, + "start": 478 + } + }, + "span": { + "end": 498, + "start": 469 + } + } + }, + { + "kind": "assign", + "span": { + "end": 530, + "start": 507 + }, + "target": "位置", + "value": { + "kind": "binary", + "left": { + "kind": "variable", + "name": "位置", + "span": { + "end": 524, + "start": 518 + } + }, + "op": "add", + "right": { + "kind": "literal", + "span": { + "end": 0, + "start": 0 + }, + "type": "int", + "value": "1" + }, + "span": { + "end": 528, + "start": 518 + } + } + } + ], + "condition": { + "kind": "binary", + "left": { + "kind": "variable", + "name": "位置", + "span": { + "end": 370, + "start": 364 + } + }, + "op": "lt", + "right": { + "args": [ + { + "name": null, + "span": { + "end": 392, + "start": 380 + }, + "value": { + "kind": "variable", + "name": "数量列表", + "span": { + "end": 392, + "start": 380 + } + } + } + ], + "callee": { + "kind": "variable", + "name": "长度", + "span": { + "end": 379, + "start": 373 + } + }, + "kind": "call", + "span": { + "end": 393, + "start": 373 + } + }, + "span": { + "end": 393, + "start": 364 + } + }, + "condition_span": { + "end": 394, + "start": 357 + }, + "kind": "loop", + "span": { + "end": 394, + "start": 357 + } + } + ], + "condition": { + "kind": "variable", + "name": "仓库启用", + "span": { + "end": 310, + "start": 298 + } + }, + "condition_span": { + "end": 311, + "start": 294 + }, + "span": { + "end": 311, + "start": 294 + } + } + ], + "kind": "branch", + "span": { + "end": 311, + "start": 294 + } + }, + { + "kind": "return", + "span": { + "end": 716, + "start": 701 + }, + "value": { + "kind": "variable", + "name": "总量", + "span": { + "end": 715, + "start": 709 + } + } + } + ], + "effects": [ + "unknown" + ], + "heading_span": { + "end": 66, + "start": 27 + }, + "id": "root:default::inventory.mq.md::库存示例.检查库存并累计可用量", + "local_name": "检查库存并累计可用量", + "namespace": "库存示例", + "signature": { + "kind": "explicit", + "params": [ + { + "default": null, + "name": "仓库启用", + "required": true, + "span": { + "end": 234, + "start": 216 + }, + "type": "Bool" + }, + { + "default": null, + "name": "数量列表", + "required": true, + "span": { + "end": 254, + "start": 235 + }, + "type": "List" + } + ] + }, + "span": { + "end": 716, + "start": 27 + }, + "unit_id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量" + } + ], + "id": "root:default::inventory.mq.md", + "imports": [], + "package_instance_id": "root:default", + "references": [], + "relative_path": "inventory.mq.md", + "resources": [], + "source_digest": "66dc7850263390ec1778dbc1c0040a02c31e4e856cc76eefefb24c0b39d98866", + "units": [ + { + "function": null, + "id": "root:default::inventory.mq.md#", + "kind": "root", + "level": 0, + "name": "", + "span": { + "end": 716, + "start": 0 + } + }, + { + "function": null, + "id": "root:default::inventory.mq.md#库存示例", + "kind": "namespace", + "level": 1, + "name": "库存示例", + "span": { + "end": 25, + "start": 0 + } + }, + { + "function": "root:default::inventory.mq.md::库存示例.检查库存并累计可用量", + "id": "root:default::inventory.mq.md#库存示例/检查库存并累计可用量", + "kind": "function", + "level": 2, + "name": "检查库存并累计可用量", + "span": { + "end": 66, + "start": 27 + } + } + ] + } + ], + "producer": { + "markdown_profile": "marqdo.md.v1", + "name": "marqdo", + "version": "3.0.0-rc.1" + }, + "project": { + "identity_kind": "workspace_snapshot", + "lock_digest": "", + "root_id": "sha256:b2759c5675439148434dad009dbf4042eebefc2dfbc3595f714dc7c26131b248", + "stdlib": { + "digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "instance_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713", + "version": "0.1.0" + } + }, + "schema": "marqdo.analysis", + "schema_version": 2 +} \ No newline at end of file diff --git a/tests/fixtures/golden/inventory.ast.json b/tests/fixtures/golden/inventory.ast.json new file mode 100644 index 0000000..579c85b --- /dev/null +++ b/tests/fixtures/golden/inventory.ast.json @@ -0,0 +1,429 @@ +{ + "ast": { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "@knowledge 库存示例", + "span": { + "end": 25, + "start": 2 + } + } + ], + "kind": "heading", + "level": 1, + "setext": false, + "span": { + "end": 25, + "start": 0 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "@exec 检查库存并累计可用量", + "span": { + "end": 66, + "start": 30 + } + } + ], + "kind": "heading", + "level": 2, + "setext": false, + "span": { + "end": 66, + "start": 27 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "只在仓库启用时统计库存;对每个未统计条目进行累计。", + "span": { + "end": 143, + "start": 68 + } + }, + { + "kind": "soft_break", + "span": { + "end": 144, + "start": 143 + } + }, + { + "kind": "text", + "literal": "位置从零下标开始,返回最小计量单位的总量。", + "span": { + "end": 207, + "start": 144 + } + } + ], + "kind": "paragraph", + "span": { + "end": 207, + "start": 68 + } + }, + { + "children": [ + { + "kind": "code", + "literal": "params(仓库启用: Bool, 数量列表: List)", + "span": { + "end": 257, + "start": 209 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 257, + "start": 209 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "总量 = 0", + "span": { + "end": 271, + "start": 261 + } + } + ], + "kind": "strong", + "span": { + "end": 273, + "start": 259 + } + } + ], + "kind": "paragraph", + "span": { + "end": 273, + "start": 259 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "位置 = 0", + "span": { + "end": 287, + "start": 277 + } + } + ], + "kind": "strong", + "span": { + "end": 289, + "start": 275 + } + } + ], + "kind": "paragraph", + "span": { + "end": 289, + "start": 275 + } + }, + { + "children": [ + { + "children": [ + { + "children": [ + { + "kind": "code", + "literal": "if 仓库启用", + "span": { + "end": 311, + "start": 294 + }, + "ticks": 1 + }, + { + "kind": "text", + "literal": ":仅在启用状态下统计库存。", + "span": { + "end": 350, + "start": 311 + } + } + ], + "kind": "paragraph", + "span": { + "end": 350, + "start": 294 + } + }, + { + "children": [ + { + "children": [ + { + "children": [ + { + "kind": "code", + "literal": "while 位置 < 长度(数量列表)", + "span": { + "end": 394, + "start": 357 + }, + "ticks": 1 + }, + { + "kind": "text", + "literal": ":按位置依次统计,到达列表末尾时终止。", + "span": { + "end": 451, + "start": 394 + } + } + ], + "kind": "paragraph", + "span": { + "end": 451, + "start": 357 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "总量 = 总量 + 数量列表[位置]", + "span": { + "end": 498, + "start": 460 + } + } + ], + "kind": "strong", + "span": { + "end": 500, + "start": 458 + } + } + ], + "kind": "paragraph", + "span": { + "end": 500, + "start": 458 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "位置 = 位置 + 1", + "span": { + "end": 528, + "start": 509 + } + } + ], + "kind": "strong", + "span": { + "end": 530, + "start": 507 + } + } + ], + "kind": "paragraph", + "span": { + "end": 530, + "start": 507 + } + }, + { + "children": [ + { + "kind": "code", + "literal": "end", + "span": { + "end": 542, + "start": 537 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 542, + "start": 537 + } + } + ], + "kind": "item", + "span": { + "end": 542, + "start": 355 + } + } + ], + "kind": "list", + "ordered": false, + "span": { + "end": 542, + "start": 355 + }, + "tight": false + } + ], + "kind": "item", + "span": { + "end": 542, + "start": 291 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "code", + "literal": "else", + "span": { + "end": 553, + "start": 547 + }, + "ticks": 1 + }, + { + "kind": "text", + "literal": ":仓库未启用时,总量保持为零。", + "span": { + "end": 598, + "start": 553 + } + } + ], + "kind": "paragraph", + "span": { + "end": 598, + "start": 547 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "不执行任何库存统计。", + "span": { + "end": 633, + "start": 603 + } + } + ], + "kind": "paragraph", + "span": { + "end": 633, + "start": 603 + } + } + ], + "kind": "item", + "span": { + "end": 633, + "start": 544 + } + } + ], + "kind": "list", + "ordered": true, + "span": { + "end": 633, + "start": 291 + }, + "start": 1, + "tight": false + }, + { + "children": [ + { + "kind": "code", + "literal": "end", + "span": { + "end": 640, + "start": 635 + }, + "ticks": 1 + } + ], + "kind": "paragraph", + "span": { + "end": 640, + "start": 635 + } + }, + { + "children": [ + { + "kind": "text", + "literal": "返回累计总量;本函数不会修改库存来源。", + "span": { + "end": 699, + "start": 642 + } + } + ], + "kind": "paragraph", + "span": { + "end": 699, + "start": 642 + } + }, + { + "children": [ + { + "children": [ + { + "kind": "text", + "literal": "return 总量", + "span": { + "end": 715, + "start": 702 + } + } + ], + "kind": "emph", + "span": { + "end": 716, + "start": 701 + } + } + ], + "kind": "paragraph", + "span": { + "end": 716, + "start": 701 + } + } + ], + "kind": "document", + "span": { + "end": 716, + "start": 0 + } + }, + "command": "inspect", + "module": "root:default::inventory.mq.md" +}