From 8a15f2be9b4ed37f9d45a981ea3462872e6f4518 Mon Sep 17 00:00:00 2001 From: cflmy Date: Mon, 30 Nov 2026 16:35:39 +0800 Subject: [PATCH] feat: add heading-jump and unused-import structure rules Continue marqdo-lint#13 with two more Analysis-3-only document-architecture rules (catalog 27, both info, default gate unchanged): - MQD-STRUCT-002: a heading skips more than one level below a real parent unit; top-level H2 under the document root is deliberately exempt. - MQD-REL-002: an explicit import's resolved module is never named by a call target or a Markdown reference target. Rules + unit tests in src/rules/structure.rs, RULES.md catalog, rule count in tests/cli.rs. Evidence: docs/evidence/2026-11-30-doc-rules-p2.md (66 tests, package-tool, real CLI install/lint/remove, 0 diagnostics on the inventory example). No parser copy, no document language, no new dependency. --- docs/RULES.md | 2 + docs/evidence/2026-11-30-doc-rules-p2.md | 41 +++++++ src/rules/mod.rs | 22 +++- src/rules/structure.rs | 144 ++++++++++++++++++++++- tests/cli.rs | 2 +- 5 files changed, 207 insertions(+), 4 deletions(-) create mode 100644 docs/evidence/2026-11-30-doc-rules-p2.md diff --git a/docs/RULES.md b/docs/RULES.md index bb2a54c..338033c 100644 --- a/docs/RULES.md +++ b/docs/RULES.md @@ -25,6 +25,8 @@ | MQD-ENTRY-001 | info | 项目级入口不是 `index.mq.md`(仅 manifest 或多模块项目) | 为项目保留根 `index.mq.md` 导航入口。 | | MQD-STRUCT-001 | info | 同名标题出现在多个作用域(裸锚点会编号) | 使用唯一标题名或完整 unit path。 | | MQD-REL-001 | info | 链接指向未被 import 的模块(静态引用≠执行) | 需要执行目标时显式 import。 | +| MQD-STRUCT-002 | info | 标题层级跳级(父单元非 root 时) | 按父标题下一级书写子标题。 | +| MQD-REL-002 | info | import 未被 calls/references 使用 | 移除未使用 import 或显式使用并说明。 | | MQD-KNOW-001 | warning | 在两个执行段之间切出一段纯文字,或出现跨段控制 | 普通说明留在 Exec,同段关闭控制;公式和富文本可留在 Knowledge | | MQD-LINK-001 | error | `references[].state` 为 `missing`、`ambiguous`、`invalid` 或 `outside_scope` | 修正引用地址或目标;歧义时打印全部候选,不任选第一个 | | MQD-LINK-002 | info | `references[].state` 为 `not_loaded` | 这是“未核验”,不是断链;需要时显式使用 `--refs` | diff --git a/docs/evidence/2026-11-30-doc-rules-p2.md b/docs/evidence/2026-11-30-doc-rules-p2.md new file mode 100644 index 0000000..1e3fd13 --- /dev/null +++ b/docs/evidence/2026-11-30-doc-rules-p2.md @@ -0,0 +1,41 @@ +# Lint 文档结构规则 P2(issue #13) + +Date: 2026-11-30. Branch: `codex/issue-13-doc-rules-p2`. +Baseline: main `cd01607fea2d89752f58afc8a4cbaa77a02759ff`(PR #15)。 + +## 交付 + +在既有 25 条规则基础上新增两条仅读取公开 Analysis 3 的文档结构规则 +(catalog 27 条,均 `info`,不改变默认门槛): + +- `MQD-STRUCT-002`:父单元不是 root 时标题层级跳级(例如 H2 下直接 H4)。 + 顶层 H2 直接位于 root 下是合法风格,不误报。 +- `MQD-REL-002`:显式 import 的 resolved 模块没有被任何 call target 或 Markdown + reference target 使用;只提示,不推断运行时副作用。 + +实现与证据:`src/rules/structure.rs`(规则 + 单测)、`docs/RULES.md`、 +`tests/cli.rs` 规则数更新。 + +## 验证(真实,Linux x86_64 / glibc 2.43) + +输入:CLI 3.0.0-rc.6(merge `afea4f947473ae4cd5688e53a6545cce7f327b2f`), +Bundle `marqdo-stdlib 0.3.0`(tree `sha256:4e47b0ff…`)。 + +```text +cargo fmt --all -- --check PASS +cargo clippy --all-targets --locked -- -D warnings PASS +cargo test --locked 66 passed, 0 failed +./scripts/check-no-legacy.sh PASS +scripts/package-tool.sh PASS + binary sha256 dc31e2dda54c4965976a9b373a0caa7a12c2718594d8c817ff3e4d7bda6c049c + tool.json sha256 e68f22425c697948db95fad2053280e03a59be4d95568a5955254cca710f6edc +真实 Tool install → lint examples/nested/inventory.mq.md --format json → exit 0, 0 diagnostics +真实 Tool remove PASS +``` + +## 边界 / 未验证 + +- 规则只读公开 Analysis 3;不复制 Markdown/语言解析,不引入文档语言。 +- 两条规则都是 `info`,不改变 `--fail-on warning` 默认行为;真实 example + 无误报(0 diagnostics)。 +- 仍属候选:macOS/Windows、正式 `v0.3.0` 发布、rc.6 官方归档消费(#11)。 diff --git a/src/rules/mod.rs b/src/rules/mod.rs index 31f60e0..67e8bd3 100644 --- a/src/rules/mod.rs +++ b/src/rules/mod.rs @@ -271,6 +271,24 @@ pub const CATALOG: &[RuleSpec] = &[ "Analysis references[].state/target_module 与 imports[].resolved 的关系差集。", Manual ), + rule!( + "MQD-STRUCT-002", + Info, + "标题层级跳级", + "跳级标题会削弱目录层级与 section 归属的可读性。", + "按父标题的下一级书写子标题,或把内容移到正确的层级。", + "Analysis units[].level 与 parent_id 的父子关系。", + Manual + ), + rule!( + "MQD-REL-002", + Info, + "import 未被 calls/references 使用", + "显式 import 会加载模块,但没有任何调用或链接依赖它,读者难以判断其用途。", + "移除未使用的 import,或在正文/调用中显式使用它并说明理由。", + "Analysis imports[].resolved 与 calls[].target/references[].target_module 的差集。", + Manual + ), rule!( "MQD-SAFETY-001", Error, @@ -294,7 +312,7 @@ mod tests { #[test] fn catalog_has_stable_unique_ids() { let ids: BTreeSet<_> = CATALOG.iter().map(|rule| rule.id).collect(); - assert_eq!(CATALOG.len(), 25); + assert_eq!(CATALOG.len(), 27); assert_eq!(ids.len(), CATALOG.len()); assert!(ids.contains("MQD-BRANCH-001")); assert!(ids.contains("MQD-SAFETY-001")); @@ -303,5 +321,7 @@ mod tests { assert!(ids.contains("MQD-ENTRY-001")); assert!(ids.contains("MQD-STRUCT-001")); assert!(ids.contains("MQD-REL-001")); + assert!(ids.contains("MQD-STRUCT-002")); + assert!(ids.contains("MQD-REL-002")); } } diff --git a/src/rules/structure.rs b/src/rules/structure.rs index d9bc422..cc657e9 100644 --- a/src/rules/structure.rs +++ b/src/rules/structure.rs @@ -12,7 +12,7 @@ use std::collections::BTreeMap; use crate::{ diagnostics::Diagnostic, input::{ProjectInput, SourceDocument}, - model::{AnalysisModule, IdentityKind, ReferenceState, Span}, + model::{AnalysisModule, IdentityKind, ReferenceState, Span, UnitKind}, }; /// Document-local structure/navigation diagnostics. @@ -21,7 +21,9 @@ pub fn check_document_structure(document: &SourceDocument) -> Vec { return Vec::new(); }; let mut diagnostics = duplicate_heading_name_rules(module); + diagnostics.extend(level_jump_rules(module)); diagnostics.extend(link_not_import_rules(module)); + diagnostics.extend(unused_import_rules(module)); diagnostics } @@ -88,6 +90,73 @@ fn duplicate_heading_name_rules(module: &AnalysisModule) -> Vec { diagnostics } +/// A heading that skips one or more levels below a real parent unit. +/// +/// Top-level headings under the document root are exempt: using `##` as the +/// first heading is a valid style, not a jump from a parent unit. +fn level_jump_rules(module: &AnalysisModule) -> Vec { + let mut by_id = BTreeMap::new(); + for unit in &module.units { + by_id.insert(unit.id.as_str(), unit); + } + let mut diagnostics = Vec::new(); + for unit in &module.units { + let Some(parent_id) = unit.parent_id.as_deref() else { + continue; + }; + let Some(parent) = by_id.get(parent_id) else { + continue; + }; + if parent.kind == UnitKind::Root { + continue; + } + if unit.level > parent.level + 1 { + let span = unit.heading_span.unwrap_or(unit.span); + diagnostics.push( + Diagnostic::new("MQD-STRUCT-002", span).with_message(format!( + "标题 `{}` 从父级 H{} 跳到 H{}", + unit.path.join("/"), + parent.level, + unit.level + )), + ); + } + } + diagnostics +} + +/// Imports whose resolved module is never named by a call target or a link. +fn unused_import_rules(module: &AnalysisModule) -> Vec { + if module.imports.is_empty() { + return Vec::new(); + } + let mut diagnostics = Vec::new(); + for import in &module.imports { + let Some(resolved) = import.resolved.as_deref() else { + continue; + }; + let prefix = format!("{resolved}::"); + let used_by_call = module.calls.iter().any(|call| { + call.target + .as_deref() + .is_some_and(|target| target.starts_with(&prefix)) + }); + let used_by_link = module + .references + .iter() + .any(|reference| reference.target_module.as_deref() == Some(resolved)); + if !used_by_call && !used_by_link { + diagnostics.push( + Diagnostic::new("MQD-REL-002", import.span).with_message(format!( + "import `{}`({})未在 calls 或 references 中使用", + import.alias, import.target + )), + ); + } + } + diagnostics +} + /// A Markdown link to a loaded module that the document never imports. /// /// A link is a static reference; it never loads, imports or executes the @@ -131,7 +200,7 @@ mod tests { use crate::model::{ExecutionProjection, MarkdownTree}; use serde_json::json; - fn analysis_with_units(namespaces: &[(&str, &[&str])]) -> serde_json::Value { + pub(super) fn analysis_with_units(namespaces: &[(&str, &[&str])]) -> serde_json::Value { // One namespace per entry with the given child heading names. Every // unit gets a valid span so the projection passes the strict // Analysis-3 validator; the rules read identity/name/path only. @@ -300,3 +369,74 @@ mod tests { assert!(check_project(&project).is_empty()); } } + +#[cfg(test)] +mod additional_tests { + use super::*; + use crate::model::ExecutionProjection; + + fn document_with(raw: serde_json::Value) -> SourceDocument { + let projection = ExecutionProjection::from_json(raw).unwrap(); + let module = projection.entry_module().unwrap().clone(); + let source = module + .source_snapshot(std::path::PathBuf::from("index.mq.md")) + .unwrap(); + SourceDocument { + markdown: crate::model::MarkdownTree::empty(&source), + source, + module: Some(module), + } + } + + #[test] + fn heading_level_jumps_below_a_real_parent_are_reported() { + let mut raw = super::tests::analysis_with_units(&[("甲", &["说明"])]); + let module_id = raw["modules"][0]["id"].as_str().unwrap().to_string(); + let parent_id = format!("{module_id}#甲/说明"); + let namespace_id = format!("{module_id}#甲"); + let source_len = raw["modules"][0]["source"].as_str().unwrap().len(); + raw["modules"][0]["units"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "id": format!("{parent_id}/子"), + "path": ["甲", "说明", "子"], + "parent_id": parent_id, + "kind": "section", + "name": "子", + "level": 4, + "mode": "knowledge", + "mode_origin": "inherited", + "mode_source_unit_id": namespace_id, + "heading_span": {"start": 0, "end": 0}, + "span": {"start": 0, "end": source_len}, + "function": null + })); + let diagnostics = check_document_structure(&document_with(raw)); + let jump: Vec<_> = diagnostics + .iter() + .filter(|diagnostic| diagnostic.id == "MQD-STRUCT-002") + .collect(); + assert_eq!(jump.len(), 1, "{diagnostics:?}"); + } + + #[test] + fn unused_imports_are_reported() { + let mut raw = super::tests::analysis_with_units(&[("甲", &["说明"])]); + let module_id = raw["modules"][0]["id"].as_str().unwrap().to_string(); + let imported = format!("{module_id}::dep.mq.md"); + raw["modules"][0]["imports"] = serde_json::json!([{ + "alias": "dep", + "target": "./dep.mq.md", + "span": {"start": 0, "end": 0}, + "resolved": imported, + }]); + let diagnostics = check_document_structure(&document_with(raw)); + assert!( + diagnostics + .iter() + .any(|diagnostic| diagnostic.id == "MQD-REL-002"), + "{diagnostics:?}" + ); + } +} diff --git a/tests/cli.rs b/tests/cli.rs index fc67f6a..98bc215 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -19,7 +19,7 @@ fn rule_commands_do_not_require_the_core() { .unwrap(); assert!(output.status.success()); let rules: Vec = serde_json::from_slice(&output.stdout).unwrap(); - assert_eq!(rules.len(), 25); + assert_eq!(rules.len(), 27); let output = lint() .env("MARQDO_BIN", "no-such-core") -- 2.54.1