feat(check): M4 L1 引用一致性 — 描述里的反引号实体必须可解析(label.ref_dangling)
规则:描述里的 `名字` = 断言,必须能解析 —— 要么 () 的实现用到它,要么文档定义了它(函数/参数/import 绑定/frontmatter 键), 要么是内置函数。否则报 label.ref_dangling(error)。 只认反引号(可证伪原则):普通汉字不参与判定,避免海量假阳性; 代价是作者不写反引号就得不到保护,这是刻意的——机器只校验它看得懂的断言。 实现: - refs(label):扫描成对反引号取内部(未闭合/空串忽略,不 panic) - payload_idents(payload):Var / callee / path 段 / receiver / [k] 变量键 / 插值变量 - module_symbols(module):函数与子函数、参数、import/use 绑定、frontmatter 键 - 内置函数用 crate::host::HostFn::from_name 判定 - OcclusionSite 增加 payload_idents,collect 阶段一次算好 实测: 悬空 → "描述引用了不存在的实体:`税率` ..." 1 error, exit 1 可解析(payload 变量 / len 内置 / `> 加 1 2` 行内调用)→ 零诊断 测试:3 个单测(抽取/多引用与散文混排/未闭合不 panic) + 2 个集成(悬空 exit 1;三类可解析零诊断) 全量 cargo test --release:583 passed / 0 failed(M2.5 后 578 + 5) 文档:doc/design/change-m4-label-refs.md
This commit is contained in:
1 parent
1a94cc8490
commit
6dd0ce47b1
5 files changed
+297
No files matched your search
@@ -0,0 +1,84 @@
|
||||
# 变更记录:M4 L1 引用一致性(`label.ref_dangling`)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Implemented** |
|
||||
| 日期 | 2026-10-22 |
|
||||
| 里程碑 | M4([label-freshness-and-repair.md](label-freshness-and-repair.md) §3.1 / [occlusion-syntax.md](occlusion-syntax.md) §11.1) |
|
||||
| 改动文件 | `src/label.rs` · `tests/occlusion.rs` · `tests/occlusion/ref-*.mq.md` |
|
||||
| 影响面 | `marqdo check`(新增一条 error) |
|
||||
|
||||
---
|
||||
|
||||
## 1. 规则
|
||||
|
||||
> 描述里用反引号写出的名字 = **断言**:它必须能解析
|
||||
> —— 要么 `()` 的实现用到它,要么文档里定义了它,要么它是内置函数。
|
||||
|
||||
```markdown
|
||||
**a = [按 `税率` 计算](100 * 0.1)** # ❌ label.ref_dangling(税率为空悬)
|
||||
**b = [按 `税率` 算](100 * `税率`)** # ✅ 实现里用到
|
||||
**c = [取长度](len("abc"))** # ✅ 内置函数
|
||||
**d = [用 `加` 求和](> 加 1 2))** # ✅ 模块内函数
|
||||
```
|
||||
|
||||
实测:
|
||||
|
||||
```
|
||||
dangling.mq.md:3:1: 描述引用了不存在的实体:`税率` —— 本段实现没有用到它,模块里也没有定义
|
||||
contract check: 1 条诊断(1 error) # exit 1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 为什么只认反引号(可证伪原则)
|
||||
|
||||
| 写法 | 是否检查 | 原因 |
|
||||
|------|---------|------|
|
||||
| `` `税率` `` | ✅ | 显式引用,可证伪 |
|
||||
| 普通汉字"税率" | ❌ | 自然语言无法机械判定,检查必然假阳性 |
|
||||
|
||||
代价:作者不写反引号就得不到保护。这是刻意的——**机器只校验它看得懂的断言**,
|
||||
同时反向抑制"为凑数写废话"。
|
||||
|
||||
---
|
||||
|
||||
## 3. 实现
|
||||
|
||||
| 环节 | 做法 |
|
||||
|------|------|
|
||||
| 抽取 | `refs(label)`:扫描成对反引号,取内部去空白;未闭合/空串忽略 |
|
||||
| 作用域 | `payload_idents(payload)`(Var / callee / path / receiver / `[k]` 的变量键 / 插值变量)∪ `module_symbols(module)`(函数与子函数、参数、import/use 绑定、frontmatter 键)∪ `HostFn::from_name` |
|
||||
| 诊断 | `label.ref_dangling`,**error**,带 `doc_quote`(描述原文)与可执行建议 |
|
||||
|
||||
`OcclusionSite` 增加 `payload_idents` 字段,在 `collect` 阶段一次算好,`check` 只做集合查找。
|
||||
|
||||
---
|
||||
|
||||
## 4. 测试
|
||||
|
||||
| 层 | 内容 | 结果 |
|
||||
|----|------|------|
|
||||
| 单元(3) | 单引用 / 多引用与散文混排 / 无引用与未闭合反引号不 panic | ✅ |
|
||||
| 集成(2) | 悬空引用 exit 1 + 文案;三类可解析引用(payload 变量 / 内置 / 模块函数)零诊断 | ✅ |
|
||||
| 全量 | `cargo test --release` | **583 passed / 0 failed**(M2.5 后 578 + 5) |
|
||||
|
||||
---
|
||||
|
||||
## 5. 边界与后续
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 只查"能否解析" | 不查"语义是否仍成立"——那是 T1(M6)与人工/LLM 复核的活 |
|
||||
| 不查"能解析但实现没用到" | 该情形在模块级符号时无法区分误报,留待 T1 变更驱动 |
|
||||
| 描述里的反引号不是变量绑定 | 只是断言,不进入任何作用域 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 变更清单
|
||||
|
||||
| 文件 | 变更 |
|
||||
|------|------|
|
||||
| `src/label.rs` | `refs()` · `payload_idents()` · `module_symbols()` · `OcclusionSite.payload_idents` · `check` 增 `label.ref_dangling` · 3 个单测 |
|
||||
| `tests/occlusion.rs` + `tests/occlusion/{ref-dangling,ref-ok}.mq.md` | 2 个集成测试 |
|
||||
| `doc/design/change-m4-label-refs.md` | 本文件 |
|
||||
+169
@@ -20,6 +20,8 @@ pub struct OcclusionSite {
|
||||
pub line: u32,
|
||||
/// Enclosing function/object name (`# main` → `main`).
|
||||
pub unit: String,
|
||||
/// Identifiers the payload actually mentions (for L1 ref checks).
|
||||
pub payload_idents: std::collections::HashSet<String>,
|
||||
}
|
||||
|
||||
/// Collect every occlusion in `module` (declaration order).
|
||||
@@ -87,11 +89,16 @@ fn walk_arm(arm: &BranchArm, line: u32, unit: &str, out: &mut Vec<OcclusionSite>
|
||||
fn walk_expr(expr: &Expr, line: u32, unit: &str, out: &mut Vec<OcclusionSite>) {
|
||||
match expr {
|
||||
Expr::Occluded { label, payload } => {
|
||||
let mut idents = std::collections::HashSet::new();
|
||||
if let Some(inner) = payload {
|
||||
payload_idents(inner, &mut idents);
|
||||
}
|
||||
out.push(OcclusionSite {
|
||||
label: label.clone(),
|
||||
has_payload: payload.is_some(),
|
||||
line,
|
||||
unit: unit.to_string(),
|
||||
payload_idents: idents,
|
||||
});
|
||||
if let Some(inner) = payload {
|
||||
walk_expr(inner, line, unit, out);
|
||||
@@ -127,12 +134,120 @@ fn walk_expr(expr: &Expr, line: u32, unit: &str, out: &mut Vec<OcclusionSite>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Backticked entity references inside a label: `` 按 `税率` 计算 `` → `["税率"]`.
|
||||
///
|
||||
/// Only explicit backticks count as claims — plain prose never is. `<TAB>` M4
|
||||
pub fn refs(label: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = label;
|
||||
while let Some(open) = rest.find('`') {
|
||||
let after = &rest[open + 1..];
|
||||
let Some(close) = after.find('`') else {
|
||||
break;
|
||||
};
|
||||
let name = after[..close].trim();
|
||||
if !name.is_empty() {
|
||||
out.push(name.to_string());
|
||||
}
|
||||
rest = &after[close + 1..];
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every identifier the payload actually mentions (variables, callees, path parts).
|
||||
fn payload_idents(expr: &Expr, out: &mut std::collections::HashSet<String>) {
|
||||
match expr {
|
||||
Expr::Var(n) => {
|
||||
out.insert(n.clone());
|
||||
}
|
||||
Expr::Occluded { payload, .. } => {
|
||||
if let Some(inner) = payload {
|
||||
payload_idents(inner, out);
|
||||
}
|
||||
}
|
||||
Expr::Unary { expr, .. } => payload_idents(expr, out),
|
||||
Expr::Binary { left, right, .. } => {
|
||||
payload_idents(left, out);
|
||||
payload_idents(right, out);
|
||||
}
|
||||
Expr::Call(call) => {
|
||||
out.insert(call.callee.clone());
|
||||
if let Some(p) = &call.path {
|
||||
for seg in p {
|
||||
out.insert(seg.clone());
|
||||
}
|
||||
}
|
||||
if let Some(r) = &call.receiver {
|
||||
out.insert(r.clone());
|
||||
}
|
||||
for a in &call.args {
|
||||
match a {
|
||||
Arg::Positional(e) | Arg::Named { value: e, .. } => payload_idents(e, out),
|
||||
}
|
||||
}
|
||||
}
|
||||
Expr::List(items) => {
|
||||
for e in items {
|
||||
payload_idents(e, out);
|
||||
}
|
||||
}
|
||||
Expr::Map(pairs) => {
|
||||
for (_, e) in pairs {
|
||||
payload_idents(e, out);
|
||||
}
|
||||
}
|
||||
Expr::Index { base, label } => {
|
||||
payload_idents(base, out);
|
||||
if let crate::ast::IndexKey::Var(n) = label {
|
||||
out.insert(n.clone());
|
||||
}
|
||||
}
|
||||
Expr::Interp(parts) => {
|
||||
for p in parts {
|
||||
if let crate::ast::InterpPart::Var(n) = p {
|
||||
out.insert(n.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Expr::Literal(_) | Expr::Formula(_) | Expr::Code(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Names that exist in the document scope: functions/objects (recursive),
|
||||
/// import aliases, frontmatter keys. Builtins are checked separately.
|
||||
fn module_symbols(module: &Module) -> std::collections::HashSet<String> {
|
||||
let mut out = std::collections::HashSet::new();
|
||||
fn walk_fun(f: &Function, out: &mut std::collections::HashSet<String>) {
|
||||
out.insert(f.name.clone());
|
||||
for p in &f.params {
|
||||
out.insert(p.name.clone());
|
||||
}
|
||||
for c in &f.children {
|
||||
walk_fun(c, out);
|
||||
}
|
||||
}
|
||||
for f in &module.functions {
|
||||
walk_fun(f, &mut out);
|
||||
}
|
||||
for imp in &module.imports {
|
||||
out.insert(imp.bind.clone());
|
||||
}
|
||||
for u in &module.uses {
|
||||
out.insert(u.bind.clone());
|
||||
}
|
||||
for (k, _) in &module.metadata {
|
||||
out.insert(k.clone());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Diagnostics for label structure. `<TAB>` M2.5
|
||||
///
|
||||
/// - empty label → `label.missing` (**error**): you wrote a shape without prose
|
||||
/// - empty payload → `label.empty_payload` (**warning**): say what the stub returns
|
||||
pub fn check(module: &Module, path: Option<&std::path::Path>) -> Vec<Diagnostic> {
|
||||
let mut out = Vec::new();
|
||||
let symbols = module_symbols(module);
|
||||
for site in collect(module) {
|
||||
let span = Span::new(site.line, 1);
|
||||
if site.label.is_empty() {
|
||||
@@ -164,6 +279,60 @@ pub fn check(module: &Module, path: Option<&std::path::Path>) -> Vec<Diagnostic>
|
||||
.with_suggestion("写清桩的返回值(如 `(None)` 或 `(0)`),或补上真实实现"),
|
||||
);
|
||||
}
|
||||
|
||||
// `<TAB>` M4 (L1): every backticked ref in the label must resolve —
|
||||
// either the payload mentions it, or the document defines it, or it is
|
||||
// a builtin. This is the deterministic half of staleness detection.
|
||||
for r in refs(&site.label) {
|
||||
if site.payload_idents.contains(&r)
|
||||
|| symbols.contains(&r)
|
||||
|| crate::host::HostFn::from_name(&r).is_some()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
out.push(
|
||||
Diagnostic::new(
|
||||
path,
|
||||
span,
|
||||
format!(
|
||||
"描述引用了不存在的实体:`{r}` —— 本段实现没有用到它,模块里也没有定义"
|
||||
),
|
||||
)
|
||||
.with_code("label.ref_dangling")
|
||||
.with_severity(Severity::Error)
|
||||
.with_doc_quote(site.label.clone())
|
||||
.with_suggestion(format!(
|
||||
"检查是否改名/删除;若只是措辞,把 `{r}` 的反引号去掉或改写描述"
|
||||
)),
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::refs;
|
||||
|
||||
#[test]
|
||||
fn refs_extracts_backticked_names() {
|
||||
assert_eq!(refs("按 `税率` 计算"), vec!["税率".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refs_multiple_and_skips_prose() {
|
||||
assert_eq!(
|
||||
refs("用 `a` 和 `b`,但 plain words 不算"),
|
||||
vec!["a".to_string(), "b".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refs_none_and_unmatched_backtick() {
|
||||
assert!(refs("纯口语描述").is_empty());
|
||||
// Unmatched trailing backtick: ignore, do not panic.
|
||||
assert!(refs("半截 `名字").is_empty());
|
||||
// Empty ticks are not refs.
|
||||
assert!(refs("空 `` 引号").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -83,3 +83,19 @@ fn label_ok_has_no_diagnostics() {
|
||||
assert!(!text.contains("空载荷"), "text={text}");
|
||||
assert!(!text.contains("缺少描述"), "text={text}");
|
||||
}
|
||||
|
||||
// ---- M4: L1 reference consistency (`label.ref_dangling`) ----
|
||||
|
||||
#[test]
|
||||
fn label_ref_dangling_is_an_error() {
|
||||
let (code, text) = check("tests/occlusion/ref-dangling.mq.md", "occlusion");
|
||||
assert_eq!(code, 1, "text={text}");
|
||||
assert!(text.contains("描述引用了不存在的实体"), "text={text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn label_refs_that_resolve_are_fine() {
|
||||
let (code, text) = check("tests/occlusion/ref-ok.mq.md", "occlusion");
|
||||
assert_eq!(code, 0, "text={text}");
|
||||
assert!(!text.contains("不存在的实体"), "text={text}");
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
title: dangling label ref
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
**a = [按 `税率` 计算](100 * 0.1)**
|
||||
> print text=`a`
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
title: resolvable label refs
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`税率` = 0.1
|
||||
|
||||
**a = [按 `税率` 算](100 * `税率`)**
|
||||
**b = [取长度](len("abc"))**
|
||||
**c = [用 `加` 求和](> 加 1 2)**
|
||||
> print text=`a`
|
||||
> print text=`b`
|
||||
> print text=`c`
|
||||
|
||||
## 加
|
||||
+ `x`
|
||||
+ `y`
|
||||
|
||||
*`x` + `y`*
|
||||
Reference in new issue
Block a user