feat(core): Phase 1 —— 核心收口 + 诊断地基(core-surface 守卫 · 三层准入 · Diagnostic JSON)

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-22 19:03:03 +08:00
1 parent a49592a3ba
commit 97fda7aa10
9 files changed
+396 -5

No files matched your search

+1 -1
View File
@@ -85,7 +85,7 @@ Checks: clean tree; `main` ff-only; smoke tests; CHANGELOG Unreleased; no secret
|------|------|-----|-----|
| `Cargo.toml` + `crates/marqdo-wasm/Cargo.toml` | bump | bump | — |
| `ext/VERSION` | bump | — | bump |
| `CHANGELOG.md` | `## vVER` | `## vVER` | `## Ext pack vVER` |
| `CHANGELOG.md` | `## vVER`(含**核心表面 Δ**,见 `doc/design/layers.md`) | same | `## Ext pack vVER` |
| `README.md` / `public/**` install + download table | update | update | update ext notes |
| `.cursor/skills/marqdo/SKILL.md` | if surface changed | same | rare |
| `.github/workflows/release.yml` Highlights stub | yes | yes | — |
+15
View File
@@ -0,0 +1,15 @@
## 层归属(必填,见 doc/design/layers.md)
- [ ] Language(`src/lex` `src/parse` `src/ast` `src/interp` `src/diagnostics` / 契约)
- [ ] Runtime(`lib/` `plugins/` `crates/` catalog / view / debug / builtin)
- [ ] Document(`*.mq.md` `skills/` `ext/` `public/` `examples/`)
## 核心表面(见 doc/design/core-surface.md)
- [ ] 不涉及核心标记
- [ ] 涉及核心标记:ADR 编号 ______;core-surface.md 与 `CORE_CONSTRUCTS` 已同步(CI 守卫)
## 验收
- [ ] 相关验收(机器可验证)全绿
- [ ] 全量回归绿(`cargo test` / `go test ./...` 视触及面)
+47
View File
@@ -0,0 +1,47 @@
# 核心表面清单(core-surface)
| | |
|---|---|
| 状态 | **Accepted · 核心语法封闭集合(CI 守卫锁定)** |
| 日期 | 2026-09-22 |
| 守卫 | `tests/core_surface.rs` ⇄ `src/parse/mod.rs` `CORE_CONSTRUCTS`(改动任一侧不同步 → CI 红) |
| 相关 | [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md)(语义宪法)· [layers.md](layers.md)(准入戒律)· [three-problems.md](../roadmap/three-problems.md) 问题一 · [three-problems-plan.md](../roadmap/three-problems-plan.md) T1.1/T1.3 |
> **戒律总纲**:核心标记是**封闭集合**(约 19 个构造)。新增任何一行必须走 ADR(见 [layers.md](layers.md) 准入戒律)并回答「为什么现有标记不够」;生态需求的默认答案是**进 ext**。本表 id 列与守卫测试强一致:改表不同步 `CORE_CONSTRUCTS`(或反之)、样例文件缺失,一律 CI 红。
## 1. 行构造
| id | 外形 | 语义 | 戒律 | 样例 |
|----|------|------|------|------|
| `narrative` | 无标记文字 | 叙述(注释) | 段落内延续到空行;**默认安全**——永远不存在「叙述被执行」的路径 | `tests/markup-v03/soft-emphasis.mq.md` |
| `blank` | 空行 | 段落边界 | 叙述分段的唯一手段;不得被赋予其它语义 | `tests/markup-v03/inc-prose.mq.md` |
| `heading-unit` | `#` / `##` | 对象 / 函数单元 | 标题即单元边界,按深度嵌套;正文禁止用 `##` 做版式(会变成函数) | `tests/markup-v03/decl-ident-only.mq.md` |
| `call-line` | `>` | 调用行 | 输出等副作用 = **普通函数**,不是架构标记 | `tests/markup-v03/dual-call.mq.md` |
| `branch-list` | 体内 `1.` 递增 | 分支 | 自 `1.` 起序号递增构成一个判断;重出 `1.` 开新判断;`N. *` = else;**不是所有有序列表都是 if** | `tests/markup-v03/greet-default.mq.md` |
| `loop-list` | `-` | 循环 | 条件形 `` - `条件` `` 或遍历形 `- [项](集合)` | `tests/structure/loop.mq.md` |
| `param` | `` + `名` `` | 形参(兼容形) | 首选叙述 `` `名` `` 升参(宪法 §8);`+` 形仅兼容保留 | `tests/markup-v03/greet-default.mq.md` |
| `table` | GFM 表 | 集合 | 几何即类型([tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md));**绑定 = 数据,未绑定 = 文档表** | `tests/structure/collection.mq.md` |
| `fence` | ` ```lang ` | 外联 | 语言块原样外联,不进 Marqdo 语义 | `tests/lib/foreign-python.mq.md` |
| `hr` | 单行 `---` 或 `***` | 叙述分隔 | **不收束函数**(返回才收束) | `tests/markup-v03/module-hr.mq.md` |
| `writeback` | `<!-- marqdo-out … -->` | 持久化输出 | 只读回放,不执行 | `tests/lib/writeback-get.mq.md` |
## 2. 内联标记
| id | 外形 | 语义 | 戒律 | 样例 |
|----|------|------|------|------|
| `ident` | `` `名` `` | 声明 / 引用 | 首次未赋值 = 声明;叙述与程序共用同一视觉习惯 | `tests/markup-v03/decl-ident-only.mq.md` |
| `bold-code` | `**…**` | 代码(赋值 / 调用 / 表达式) | 只有粗体进入执行;判别序:赋值 → 调用 → 表达式 | `tests/markup-v03/multi-bold.mq.md` |
| `italic-return` | `*…*` | 返回 | 改变控制流(**返回是架构**);返回即结束函数体 | `tests/markup-v03/inc-prose.mq.md` |
| `empty-return` | `*None*` / `****` | 空返回 | 返回 `None` 并结束函数体 | `tests/markup-v03/empty-return-none.mq.md` |
| `link-index` | `[键](集合)` | 取元 / foreach | **主取元语法**;与 bracket-call 靠 `]` 后是否紧邻 `(` 消歧 | `tests/lib/table-collections.mq.md` |
| `bracket-call` | `修饰… [函数] 实参…` | 方括号标记调用 | 前置修饰 → `名=True`;与 link-index 消歧同上 | `tests/structure/bracket-call.mq.md` |
| `footnote-index` | `集合[^键]` | 过渡取元 | **仅兼容**;新代码一律写 link-index | `tests/structure/footnote-index.mq.md` |
| `soft-emphasis` | `*仅*` / `**说明**` | 忽略 | 非代码形强调**不执行**——默认安全的关键消歧规则 | `tests/markup-v03/soft-emphasis.mq.md` |
## 3. 词法大类(LineKind,`src/lex/mod.rs`)
行级入口只有四个大类:`Blank` / `Comment`(叙述段落,含软强调与行内 `` `名` ``)/ `Writeback` / `Code`(`# * > + - | ~ $` 或数字开头)。本清单第 1 节的行构造是在 `Code`(及 `Comment`/`Writeback`)内部的**语义细分**;第 2 节内联标记由 `src/parse/prose.rs` 行内扫描产出。两层合起来 = 核心表面全集。
## 4. 范围外(进 Language 层,但不在本守卫)
frontmatter YAML(元信息)与 `import` 行(模块装载)属于 Language 层的其它语言面,随 [layers.md](layers.md) 准入流程登记,暂不进本清单守卫;如需一并守卫,走 ADR 扩表。
+29
View File
@@ -0,0 +1,29 @@
# 三层归属与准入戒律(layers)
| | |
|---|---|
| 状态 | **Accepted · 准入制度(问题一落地)** |
| 日期 | 2026-09-22 |
| 相关 | [core-surface.md](core-surface.md)(核心表面守卫)· [three-problems.md](../roadmap/three-problems.md) 问题一 · [three-problems-plan.md](../roadmap/three-problems-plan.md) T1.2 |
> **目的**:语言核心保持小——**Language / Runtime / Document 三层分明,生态功能不淹没语言身份**。本制度是机制不是宣言:违反即 CI 红 / PR 不评审。
## 1. 三层归属表
| 层 | 内容 | 仓库位置 |
|----|------|----------|
| **Language** | 标记映射、词法/行分类、AST、语义、升参、契约检查器、诊断 | `src/lex/` `src/parse/` `src/ast.rs` `src/interp.rs` `src/diagnostics.rs`(及 `contract`/`check`)· 宪法 [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [core-surface.md](core-surface.md) |
| **Runtime** | stdlib、插件 ABI、WASM、debugger、view、catalog / schema / mcp CLI、字节码后端 | `lib/` `plugins/` `crates/` `src/catalog.rs` `src/view/` `src/debug/` `src/builtin.rs` `src/bytecode/` |
| **Document** | 知识单元、AI skills、示例、官方扩展、用户站 | `*.mq.md` `skills/` `ext/` `public/` `examples/` `doc/` |
## 2. 准入戒律
1. **先填层归属**:任何新特性提案(issue / PR / 设计文档)必须先声明进哪层;未填 = 不评审。
2. **Language 层变更 = ADR**:新增核心标记必须有 `doc/adr/` 编号 + 「为什么现有标记不够」+ [core-surface.md](core-surface.md) 增行 + 样例 + `CORE_CONSTRUCTS` 同步(缺任一 → CI 守卫红)。
3. **核心计数只许持平或下降**:每个 release 的核心标记计数不得增长;确需增长即触发 Language 层复盘(ADR 里写明不可替代理由)。
4. **默认进 ext**:能用扩展、stdlib、插件解决的,一律不进核心。
5. **CHANGELOG 单列「核心表面 Δ」**:每个 release 写明增删(无 Δ 写「无」);发版 checklist(`.cursor/skills/marqdo-release/SKILL.md`)含此步。
## 3. PR 模板
`.github/PULL_REQUEST_TEMPLATE.md` 含「层归属」必填项与「核心表面」勾选——与本制度一一对应。
+127
View File
@@ -41,13 +41,40 @@ pub fn display_path(path: &Path) -> String {
}
}
/// Diagnostic severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
Error,
Warning,
}
/// Contract reference (Phase 2 填值;schema 源头 = 契约表 / 说明段落).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContractRef {
pub unit: String,
pub kind: String,
pub name: String,
pub declared: String,
}
/// Unified diagnostic: `path:line:col: message` (path omitted if unknown).
///
/// 人类文本(`Display`)与机器面([`Diagnostic::to_json`])同源:凡可定位必有
/// `span`;凡契约错必带 `doc_anchor` / `doc_quote` / `contract_ref`
/// (见 `doc/roadmap/three-problems.md` §3.3 诊断协议)。
#[derive(Debug, Error, Clone)]
#[error("{}", self.format_message())]
pub struct Diagnostic {
pub path: Option<PathBuf>,
pub span: Span,
pub message: String,
/// Stable machine code (`parse.*` / `contract.*` / `runtime.*` …).
pub code: String,
pub severity: Severity,
pub suggestion: Option<String>,
pub doc_anchor: Option<String>,
pub doc_quote: Option<String>,
pub contract_ref: Option<ContractRef>,
}
impl Diagnostic {
@@ -56,6 +83,12 @@ impl Diagnostic {
path: path.map(|p| p.to_path_buf()),
span,
message: message.into(),
code: "marqdo.error".to_string(),
severity: Severity::Error,
suggestion: None,
doc_anchor: None,
doc_quote: None,
contract_ref: None,
}
}
@@ -63,12 +96,69 @@ impl Diagnostic {
Self::new(Some(path), span, message)
}
pub fn with_code(mut self, code: impl Into<String>) -> Self {
self.code = code.into();
self
}
pub fn with_severity(mut self, severity: Severity) -> Self {
self.severity = severity;
self
}
pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
self.suggestion = Some(suggestion.into());
self
}
pub fn with_doc_anchor(mut self, anchor: impl Into<String>) -> Self {
self.doc_anchor = Some(anchor.into());
self
}
pub fn with_doc_quote(mut self, quote: impl Into<String>) -> Self {
self.doc_quote = Some(quote.into());
self
}
pub fn with_contract_ref(mut self, contract_ref: ContractRef) -> Self {
self.contract_ref = Some(contract_ref);
self
}
pub fn format_message(&self) -> String {
match &self.path {
Some(p) => format!("{}:{}: {}", display_path(p), self.span, self.message),
None => format!("{}: {}", self.span, self.message),
}
}
/// Machine-readable form(AI/MLSP 面;`run --json` 出口)。
pub fn to_json(&self) -> serde_json::Value {
use serde_json::json;
json!({
"code": self.code,
"severity": match self.severity {
Severity::Error => "error",
Severity::Warning => "warning",
},
"message": self.message,
"span": {
"file": self.path.as_ref().map(|p| display_path(p)),
"line": self.span.line,
"col": self.span.col,
},
"doc_anchor": self.doc_anchor,
"doc_quote": self.doc_quote,
"contract_ref": self.contract_ref.as_ref().map(|c| json!({
"unit": c.unit,
"kind": c.kind,
"name": c.name,
"declared": c.declared,
})),
"suggestion": self.suggestion,
})
}
}
/// Convenience for `anyhow` sites that already have a span.
@@ -106,4 +196,41 @@ mod tests {
assert!(!msg.contains(r"\\?\"));
assert!(msg.contains(r"E:\marqdo\x.mq.md:7:1:"));
}
#[test]
fn json_shape_defaults_nonempty_code_and_span() {
let d = Diagnostic::at(Path::new("x.mq.md"), Span::new(3, 5), "boom");
let v = d.to_json();
assert_eq!(v["code"], "marqdo.error");
assert_eq!(v["severity"], "error");
assert_eq!(v["span"]["line"], 3);
assert_eq!(v["span"]["col"], 5);
assert_eq!(v["span"]["file"], "x.mq.md");
}
#[test]
fn json_carries_doc_anchor_and_contract_ref() {
let d = Diagnostic::at(
Path::new("demo.mq.md"),
Span::new(12, 3),
"参数 `n` 期望 number,实际 text",
)
.with_code("contract.arg_mismatch")
.with_doc_anchor("demo.mq.md#L4-L7")
.with_doc_quote("| `n` | number | 输入值 |")
.with_suggestion("把实参改为数字")
.with_contract_ref(ContractRef {
unit: "加一".to_string(),
kind: "param".to_string(),
name: "n".to_string(),
declared: "number".to_string(),
});
let v = d.to_json();
assert_eq!(v["code"], "contract.arg_mismatch");
assert_eq!(v["doc_anchor"], "demo.mq.md#L4-L7");
assert_eq!(v["contract_ref"]["unit"], "加一");
assert_eq!(v["suggestion"], "把实参改为数字");
// Display 零回归
assert!(d.format_message().contains("demo.mq.md:12:3:"));
}
}
+19 -4
View File
@@ -5,6 +5,7 @@ use anyhow::Result;
use clap::{Parser, Subcommand, ValueEnum};
use marqdo::catalog::{write_catalog, CatalogOptions};
use marqdo::diagnostics::{Diagnostic, Span};
use marqdo::ext_cli::{add_ext, list_ext, remove_ext};
use marqdo::input_feed::load_stdin_file;
use marqdo::view::{serve, serve_debug, write_static, DebugOptions, OutputOptions, ViewOptions};
@@ -64,6 +65,10 @@ enum Commands {
/// Write `# main` return value as JSON (used by file subtasks).
#[arg(long, value_name = "FILE")]
emit_result: Option<PathBuf>,
/// Emit diagnostics as JSON on stderr (machine-readable; AI/MLSP 面).
#[arg(long)]
json: bool,
},
/// Browse `.mq.md` structure + execution (live server or static output)
View {
@@ -173,17 +178,26 @@ enum ViewAction {
}
fn main() -> ExitCode {
match try_main() {
let cli = Cli::parse();
let json_errors = matches!(&cli.command, Commands::Run { json: true, .. });
match try_main(cli) {
Ok(code) => ExitCode::from(code as u8),
Err(err) => {
eprintln!("error: {err:#}");
if json_errors {
let diag = match err.downcast::<Diagnostic>() {
Ok(d) => d,
Err(e) => Diagnostic::new(None, Span::new(0, 0), format!("{e:#}")),
};
eprintln!("{}", diag.to_json());
} else {
eprintln!("error: {err:#}");
}
ExitCode::from(1)
}
}
}
fn try_main() -> Result<i32> {
let cli = Cli::parse();
fn try_main(cli: Cli) -> Result<i32> {
match cli.command {
Commands::Run {
file,
@@ -197,6 +211,7 @@ fn try_main() -> Result<i32> {
dump_all,
stdin_file,
emit_result,
json: _,
} => {
let path = file.unwrap_or_else(|| PathBuf::from("index.mq.md"));
let stdin_lines = match stdin_file {
+29
View File
@@ -1853,3 +1853,32 @@ Candidates may include lexical `score`.
}
}
}
/// 核心表面构造注册表(T1.3)——`(id, Markdown 外形)`。
///
/// **紧邻分类代码维护**;与 `doc/design/core-surface.md` 的 id 列强一致,
/// 由 `tests/core_surface.rs` 守卫:改动任一侧不同步 → CI 红。
/// 新增条目必须走 ADR(`doc/design/layers.md` 准入戒律)。
pub const CORE_CONSTRUCTS: &[(&str, &str)] = &[
// 行构造
("narrative", "无标记文字"),
("blank", "空行"),
("heading-unit", "# / ##"),
("call-line", ">"),
("branch-list", "1. 递增"),
("loop-list", "-"),
("param", "+ `名`"),
("table", "GFM 表"),
("fence", "```lang"),
("hr", "--- / ***"),
("writeback", "<!-- marqdo-out -->"),
// 内联标记
("ident", "`名`"),
("bold-code", "**…**"),
("italic-return", "*…*"),
("empty-return", "*None* / ****"),
("link-index", "[键](集合)"),
("bracket-call", "修饰… [函数] …"),
("footnote-index", "集合[^键]"),
("soft-emphasis", "*仅* / **说明**"),
];
+96
View File
@@ -0,0 +1,96 @@
//! T1.3 核心表面守卫:`doc/design/core-surface.md` ⇄ `marqdo::parse::CORE_CONSTRUCTS`。
//!
//! 三重断言(反遮盖):
//! 1. 文档 id 列与代码注册表**双向集合相等**——改任一侧不同步 → 红;
//! 2. id 不重复;
//! 3. 每行「样例」列指向的文件真实存在——删/改名样例 → 红。
//!
//! 任何新增核心标记都必须同步文档 + 本注册表 + 样例(`doc/design/layers.md` 准入戒律)。
use marqdo::parse::CORE_CONSTRUCTS;
/// 解析构造表:首格为 kebab-case 反引号 id 的行 → `(id, 样例路径)`。
fn construct_rows(doc: &str) -> Vec<(String, String)> {
let mut rows = Vec::new();
for line in doc.lines() {
let line = line.trim();
if !line.starts_with("| `") {
continue;
}
let cells: Vec<&str> = line.split('|').collect();
if cells.len() < 3 {
continue;
}
let id = cells[1].trim().trim_matches('`').to_string();
if id.is_empty() || !id.chars().all(|c| c.is_ascii_lowercase() || c == '-') {
continue; // 非构造行(如 LineKind 大类名首字母大写,天然排除)
}
let sample = line
.split('`')
.find_map(|s| {
let s = s.trim();
if s.starts_with("tests/") || s.starts_with("examples/") {
Some(s.to_string())
} else {
None
}
})
.unwrap_or_default();
rows.push((id, sample));
}
rows
}
#[test]
fn core_surface_doc_matches_registry() {
let doc = include_str!("../doc/design/core-surface.md");
let mut doc_ids: Vec<String> = construct_rows(doc).into_iter().map(|(id, _)| id).collect();
doc_ids.sort();
let mut code_ids: Vec<String> = CORE_CONSTRUCTS
.iter()
.map(|(id, _)| (*id).to_string())
.collect();
code_ids.sort();
assert_eq!(
doc_ids, code_ids,
"core-surface.md 与 CORE_CONSTRUCTS 不一致(T1.3 守卫)"
);
}
#[test]
fn core_surface_ids_unique() {
let doc = include_str!("../doc/design/core-surface.md");
let ids: Vec<String> = construct_rows(doc).into_iter().map(|(id, _)| id).collect();
let mut sorted = ids.clone();
sorted.sort();
sorted.dedup();
assert_eq!(ids.len(), sorted.len(), "core-surface.md 存在重复 id");
let mut code: Vec<&str> = CORE_CONSTRUCTS.iter().map(|(id, _)| *id).collect();
let before = code.len();
code.sort_unstable();
code.dedup();
assert_eq!(before, code.len(), "CORE_CONSTRUCTS 存在重复 id");
}
#[test]
fn core_surface_samples_exist() {
let doc = include_str!("../doc/design/core-surface.md");
for (id, sample) in construct_rows(doc) {
assert!(!sample.is_empty(), "构造 `{id}` 缺「样例」列");
assert!(
std::path::Path::new(&sample).exists(),
"构造 `{id}` 样例不存在:{sample}"
);
}
}
#[test]
fn core_surface_registry_ids_are_kebab() {
for (id, shape) in CORE_CONSTRUCTS {
assert!(
id.chars().all(|c| c.is_ascii_lowercase() || c == '-'),
"CORE_CONSTRUCTS id 非 kebab:{id}"
);
assert!(!shape.is_empty(), "CORE_CONSTRUCTS `{id}` 缺外形描述");
}
}
+33
View File
@@ -0,0 +1,33 @@
//! T1.4 诊断机器面:真实错误路径产出的 Diagnostic 可序列化(`run --json` 出口)。
//!
//! 验收(three-problems-plan.md T1.4):人类文本零回归 + JSON `code`/`span` 非空。
use std::path::Path;
use marqdo::diagnostics::Diagnostic;
use marqdo::RunOptions;
#[test]
fn error_fixture_downcasts_and_serializes() {
let err = marqdo::run_file(
Path::new("tests/errors/div-zero.mq.md"),
&RunOptions::default(),
)
.expect_err("div-zero 应失败");
let diag: Diagnostic = err
.downcast()
.expect("错误应为 diagnostics::Diagnostic(机器面出口的前提)");
let v = diag.to_json();
assert_eq!(v["code"], "marqdo.error"); // code 分类细化随 Phase 2/3
assert_eq!(v["severity"], "error");
assert!(
v["span"]["line"].as_u64().unwrap() > 0,
"JSON span.line 必须非空"
);
assert!(v["message"]
.as_str()
.unwrap()
.contains("division by zero"));
// 人类文本零回归
assert!(diag.format_message().contains("division by zero"));
}