feat(core): Phase 1 —— 核心收口 + 诊断地基(core-surface 守卫 · 三层准入 · Diagnostic JSON)
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
a49592a3ba
commit
97fda7aa10
9 files changed
+396
-5
No files matched your search
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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", "*仅* / **说明**"),
|
||||
];
|
||||
Reference in new issue
Block a user