diff --git a/doc/roadmap/three-problems-plan.md b/doc/roadmap/three-problems-plan.md index 3bd818a..5e0b92d 100644 --- a/doc/roadmap/three-problems-plan.md +++ b/doc/roadmap/three-problems-plan.md @@ -142,3 +142,23 @@ T1.1 core-surface ─是─> T3.1 语言面 + T1.3 守卫 | Phase 2 | T2.1–T2.5 验收全绿(T2.6 可延后) | | Phase 3 | T3.1–T3.4 验收全绿 | | 三大问题「已解决」 | [three-problems.md](three-problems.md) §5.1 判据矩阵全绿 + 实验数字可复现(Phase 4) | + +## 落地记录 + +### Phase 2 · 渐进式契约层(2026-09-22 完成 T2.1–T2.5;T2.6 按计划延后至 Phase 3) + +- **T2.1** `src/contract.rs`(类型词汇/三形状契约表解析/合并/四边界校验诊断)+ + `src/parse/mod.rs::extract_function_contract`(位置 + 形状双重判定,**在升参推断之前**执行—— + 契约表的单元不会被误升参;契约表从 body 移除,元数据永不执行)。 + 反例守住:**绑定**的 `字段|类型` 数据表(web_db_migration 风格)绝不视为契约。 +- **T2.2** 四边界全接:调用实参(普通/库路径/方法三条调用路径)、返回、表绑定、字段访问 + (键存在性**先于**取值,契约诊断优先于 `missing map key`)。列语义按「几何即类型」:标量或全匹配列向量。 +- **T2.3/T2.5** `marqdo check [FILE] [--json]`:契约行 vs 升参推断形参双向互查 + (错行 ⇒ Error;新升参未覆盖 ⇒ Warning)、未知类型名(附最近建议)、错位契约;Error ⇒ 非零退出。 +- **T2.4** 全部契约诊断带 `doc_anchor`(`file.mq.md#L7-L13`)+ `doc_quote`(契约表原文)+ + `contract_ref`(`declared` = 契约声明摘要);`run --json` / `check --json` 同源输出。 +- **附带修复(错误出口唯一)**:`src/load.rs` 原来把 parse 错误 `anyhow!("{label}: {e}")` 拍平成字符串, + 结构化诊断在 import 装载链路丢失;改为 `label_error` 保留 Diagnostic(补文件标签),任何装载层都不许拍平错误。 +- 验收:`tests/contracts.rs` 12 例(提取 4 + 四边界 4 + check 3 + 正向对照 1)全绿; + 全量回归零失败(含 262 gold)。 +- **T2.6(契约导出 `get_schema`)**:按计划延后至 Phase 3 与 MLSP `schema` 一并实现。 diff --git a/src/ast.rs b/src/ast.rs index d298ddc..5b2b329 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -61,6 +61,10 @@ pub struct Function { pub base: Option, /// Prose `` `名` `` never read/assigned on the executable surface (not params). pub dead_binds: Vec, + /// 渐进式契约(T2.1):形参/返回/对象字段契约(附着在文档表上,升参推断前提取)。 + pub contract: Option, + /// 集合契约(T2.1):变量名 → 字段契约(紧邻 `` `名` = `` 绑定之前的文档表)。 + pub var_contracts: HashMap, } impl Function { diff --git a/src/check.rs b/src/check.rs new file mode 100644 index 0000000..7cf6199 --- /dev/null +++ b/src/check.rs @@ -0,0 +1,213 @@ +//! `marqdo check` —— 静态契约互查(T2.3 + T2.5)。 +//! +//! 只读静态检查,不执行程序。三类必产诊断: +//! +//! 1. **防漂移(T2.5)**:契约行 vs 升参推断形参**双向互查**——契约表一经出现 +//! 就是该单元形参的完整声明:契约多出的名字(错行)与未被覆盖的推断形参 +//! (新升参)都是 `contract.param_drift`。 +//! 2. **未知类型名**:`Ty::Object` 必须是已知对象类型(防 `nubmer` 拼错, +//! 附最近建议)⇒ `contract.unknown_type`。 +//! 3. **错位契约**:契约形状(含 `类型` 列)的未绑定表出现在不允许位置 +//! (提取阶段原样留在 body 里的就是)⇒ `contract.misplaced`。 +//! +//! 任一 Error ⇒ 进程以非零码退出。诊断全部带 `doc_anchor` 锚点(T2.4)。 + +use std::path::Path; + +use anyhow::Result; + +use crate::ast::{Expr, Function, Module, Stmt}; +use crate::contract::{self, Contract, Ty}; +use crate::diagnostics::{Diagnostic, Severity, Span}; +use crate::load; + +/// 读取文件 + 装载(含 import)后做全量契约互查。 +pub fn check_path(path: &Path) -> Result> { + let module = load::load_module(path)?; + Ok(check_module(&module, Some(path))) +} + +/// 递归检查模块全部函数(含子函数)的契约。 +pub fn check_module(module: &Module, path: Option<&Path>) -> Vec { + let known = known_type_names(module); + let mut out = Vec::new(); + walk(module, &module.functions, path, &known, &mut out); + out +} + +/// 已知对象类型名:本文件 `#` 对象 + import/use 绑定 + 导入库的 `#` 对象。 +fn known_type_names(module: &Module) -> Vec { + let mut names = Vec::new(); + for f in &module.functions { + if f.is_object() { + names.push(f.name.clone()); + } + } + for i in &module.imports { + names.push(i.bind.clone()); + } + for u in &module.uses { + names.push(u.bind.clone()); + } + for lib in module.import_modules.values() { + for f in &lib.functions { + if f.is_object() { + names.push(f.name.clone()); + } + } + } + names +} + +fn walk( + module: &Module, + funs: &[Function], + path: Option<&Path>, + known: &[String], + out: &mut Vec, +) { + for fun in funs { + check_one(module, fun, path, known, out); + walk(module, &fun.children, path, known, out); + } +} + +fn check_one( + module: &Module, + fun: &Function, + path: Option<&Path>, + known: &[String], + out: &mut Vec, +) { + if let Some(c) = &fun.contract { + for p in &c.params { + type_name_check(&p.ty, c, &fun.name, path, fun.span, known, out); + } + if let Some(r) = &c.returns { + type_name_check(&r.ty, c, &fun.name, path, fun.span, known, out); + } + for f in &c.fields { + type_name_check(&f.ty, c, &fun.name, path, fun.span, known, out); + } + // ---- T2.5 防漂移:契约行 vs 升参推断形参(双向) ---- + let inferred: Vec = fun.params.iter().map(|p| p.name.clone()).collect(); + for p in &c.params { + if !inferred.contains(&p.name) { + out.push(c.diagnostic( + "contract.param_drift", + &fun.name, + format!( + "契约参数 `{}` 不是 `{}` 的形参(当前形参:[{}])", + p.name, + fun.name, + inferred.join(", ") + ), + "删除契约表该行,或让该名在函数体被读取(升参)/ 用 `+` 行显式声明".to_string(), + path, + fun.span, + )); + } + } + for name in &inferred { + if !c.params.iter().any(|p| p.name == *name) { + let d = c + .diagnostic( + "contract.param_drift", + &fun.name, + format!( + "形参 `{name}` 未被契约覆盖(可能是新推断的升参;契约表一经出现即为完整声明)" + ), + "在契约表补一行 `| {name} | 类型 | 说明 |`,或删掉契约表回到纯动态".to_string(), + path, + fun.span, + ) + .with_severity(Severity::Warning); + out.push(d); + } + } + } + for (name, c) in &fun.var_contracts { + for f in &c.fields { + type_name_check(&f.ty, c, name, path, fun.span, known, out); + } + } + // ---- 错位契约:契约形状的未绑定表被提取器原样留在 body ---- + for stmt in &fun.body { + let Stmt::Expr { value: Expr::Map(pairs), span } = stmt else { + continue; + }; + if let Some(Ok(c)) = contract::parse_contract_table(pairs, span.line, span.line, Vec::new()) + { + out.push(c.diagnostic( + "contract.misplaced", + &fun.name, + "契约表位置不允许(形参/返回表只能在函数体首个可执行行之前;字段表只能紧邻绑定或对象体首成员之前),已按普通表处理".to_string(), + "移动契约表到允许位置,或改表头避开契约形状(含 `类型` 列)".to_string(), + path, + *span, + )); + } + } + let _ = module; +} + +/// 对象类型名必须已知;拼错(`nubmer`)⇒ `contract.unknown_type` + 最近建议。 +fn type_name_check( + ty: &Ty, + c: &Contract, + unit: &str, + path: Option<&Path>, + span: Span, + known: &[String], + out: &mut Vec, +) { + let Ty::Object(name) = ty else { return }; + if known.iter().any(|k| k == name) { + return; + } + let suggestion = match suggest(name, known) { + Some(near) => format!("是不是想写 `{near}`?已知类型:{}", known.join(" / ")), + None => format!("已知类型:{}", known.join(" / ")), + }; + out.push(c.diagnostic( + "contract.unknown_type", + unit, + format!("未知类型名 `{name}`(不是原语,也没有对应的 `#` 对象)"), + suggestion, + path, + span, + )); +} + +const PRIMITIVES: &[&str] = &["text", "number", "bool", "list", "map", "any"]; + +fn edit_distance(a: &str, b: &str) -> usize { + let a: Vec = a.chars().collect(); + let b: Vec = b.chars().collect(); + let mut prev: Vec = (0..=b.len()).collect(); + let mut cur = vec![0usize; b.len() + 1]; + for i in 1..=a.len() { + cur[0] = i; + for j in 1..=b.len() { + let cost = usize::from(a[i - 1] != b[j - 1]); + cur[j] = (prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost); + } + std::mem::swap(&mut prev, &mut cur); + } + prev[b.len()] +} + +fn suggest(name: &str, known: &[String]) -> Option { + let lower = name.to_ascii_lowercase(); + let mut best: Option<(usize, String)> = None; + let candidates = PRIMITIVES.iter().map(|s| s.to_string()).chain( + known.iter().cloned(), + ); + for cand in candidates { + let d = edit_distance(&lower, &cand.to_ascii_lowercase()); + if d <= 2 && best.as_ref().map(|(bd, _)| d < *bd).unwrap_or(true) { + best = Some((d, cand)); + } + } + best.map(|(_, c)| c) +} diff --git a/src/contract.rs b/src/contract.rs new file mode 100644 index 0000000..3242d94 --- /dev/null +++ b/src/contract.rs @@ -0,0 +1,632 @@ +//! Progressive contracts (渐进式契约 / 标注类型) —— schema 长在表格/说明段落里。 +//! +//! 动态默认、按需校验、零契约文件零回归;TS/TS 的全程序静态类型被明确**拒绝**。 +//! 契约唯一来源是**未绑定文档表**(绑定表是数据,永不视为契约): +//! +//! | 形状(含 `类型` 列) | 允许位置 | 附着对象 | +//! |----------------------|----------|----------| +//! | `参数`/`返回` 表 | 函数体首个可执行行之前 | 函数(形参/返回契约) | +//! | `字段` 表 | 紧邻 `` `名` = `` 绑定之前 | 变量(集合契约) | +//! | `字段` 表 | 对象(`#`)体首成员之前 | 对象类型(字段契约) | +//! +//! 提取在**升参推断之前**执行(见 `parse`),契约表的单元不会污染推断。 +//! 校验只发生在四个运行时边界(调用实参 / 字段访问 / 表绑定 / 返回)与 +//! `marqdo check` 静态互查;契约表本身永不执行、永不进入值空间。 +//! 锚点诊断见 [`Contract::anchor`] / [`Contract::quote_text`](T2.4)。 + +use std::collections::HashMap; +use std::path::Path; + +use anyhow::Result; + +use crate::ast::Expr; +use crate::diagnostics::{ContractRef, Diagnostic, Severity, Span}; +use crate::value::Value; + +/// 契约类型词汇(`doc/design/core-surface.md` 的文档层扩展,不进语言核心)。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Ty { + /// 任意值(类型列留空)。 + Any, + Text, + /// `int` / `num`(`Value::Int` / `Value::Num` / 符号公式)。 + Number, + Bool, + List, + Map, + /// 对象类型名(`#` 对象;`check` 阶段校验存在性,防 `nubmer` 拼错)。 + Object(String), +} + +impl Ty { + /// 解析类型列文本(大小写不敏感;未知名 → `Object(name)`,由 check 验证)。 + pub fn parse(raw: &str) -> Ty { + let name = raw.trim().trim_matches('`').to_ascii_lowercase(); + match name.as_str() { + "" | "any" | "任意" => Ty::Any, + "text" | "str" | "string" | "文本" | "字串" | "字符串" => Ty::Text, + "number" | "int" | "float" | "num" | "numeric" | "数字" | "数值" => Ty::Number, + "bool" | "boolean" | "布尔" => Ty::Bool, + "list" | "列表" | "表" => Ty::List, + "map" | "dict" | "object" | "字典" | "映射" => Ty::Map, + _ => Ty::Object(raw.trim().trim_matches('`').to_string()), + } + } + + /// 契约类型名(诊断消息显示用;与 `type` 内置的运行时名对照)。 + pub fn name(&self) -> String { + match self { + Ty::Any => "any".into(), + Ty::Text => "text".into(), + Ty::Number => "number".into(), + Ty::Bool => "bool".into(), + Ty::List => "list".into(), + Ty::Map => "map".into(), + Ty::Object(n) => n.clone(), + } + } + + /// 值是否满足契约类型(对象类型看 `_type` 实例标签)。 + pub fn matches_value(&self, v: &Value) -> bool { + match self { + Ty::Any => true, + Ty::Text => matches!(v, Value::Text(_)), + // 符号公式($$…$$)是数值表达式,按 number 收。 + Ty::Number => matches!(v, Value::Int(_) | Value::Num(_) | Value::Formula(_)), + Ty::Bool => matches!(v, Value::Bool(_)), + Ty::List => matches!(v, Value::List(_)), + Ty::Map => matches!(v, Value::Map(_)), + Ty::Object(n) => instance_type_name(v).as_deref() == Some(n.as_str()), + } + } + + /// 列语义(几何即类型):标量按本类型,或**元素全匹配**的列向量。 + pub fn matches_column(&self, v: &Value) -> bool { + if self.matches_value(v) { + return true; + } + match v { + Value::List(items) => items.iter().all(|it| self.matches_value(it)), + Value::Map(pairs) => pairs + .iter() + .all(|(_, it)| match it { + // map-of-lists 的列向量 + Value::List(xs) => xs.iter().all(|x| self.matches_value(x)), + scalar => self.matches_value(scalar), + }) + && !pairs.is_empty(), + _ => false, + } + } +} + +/// 运行时 `type` 名(诊断消息里的「实际」侧)。 +pub fn type_of(v: &Value) -> &'static str { + match v { + Value::None => "none", + Value::Bool(_) => "bool", + Value::Int(_) => "int", + Value::Num(_) => "num", + Value::Text(_) => "text", + Value::List(_) => "list", + Value::Map(_) => "map", + Value::Formula(_) => "formula", + Value::Code(_) => "code", + } +} + +fn instance_type_name(v: &Value) -> Option { + let Value::Map(pairs) = v else { return None }; + pairs + .iter() + .find(|(k, _)| k == "_type") + .and_then(|(_, v)| match v { + Value::Text(t) => Some(t.clone()), + _ => None, + }) +} + +#[derive(Debug, Clone)] +pub struct ParamContract { + pub name: String, + pub ty: Ty, + pub desc: String, +} + +#[derive(Debug, Clone)] +pub struct ReturnContract { + pub ty: Ty, + pub desc: String, +} + +#[derive(Debug, Clone)] +pub struct FieldContract { + pub name: String, + pub ty: Ty, + pub nullable: bool, + pub desc: String, +} + +/// 一份契约(一个契约表块;同单元多表由 [`merge_contract`] 合并)。 +#[derive(Debug, Clone)] +pub struct Contract { + pub params: Vec, + pub returns: Option, + pub fields: Vec, + pub start_line: u32, + pub end_line: u32, + /// 契约表原文行(诊断 `doc_quote`)。 + pub quote: Vec, +} + +impl Contract { + /// 文档锚点(T2.4):`file.mq.md#L4-L7`。 + pub fn anchor(&self, path: Option<&Path>) -> String { + match path { + Some(p) => format!("{}#L{}-L{}", p.display(), self.start_line, self.end_line), + None => format!("#L{}-L{}", self.start_line, self.end_line), + } + } + + pub fn quote_text(&self) -> String { + self.quote.join("\n") + } + + /// 契约声明摘要(诊断 `contract_ref.declared`)。 + pub fn describe(&self) -> String { + let mut parts = Vec::new(); + if !self.params.is_empty() { + let list = self + .params + .iter() + .map(|p| format!("{}: {}", p.name, p.ty.name())) + .collect::>() + .join(", "); + parts.push(format!("参数[{list}]")); + } + if let Some(r) = &self.returns { + parts.push(format!("返回 {}", r.ty.name())); + } + if !self.fields.is_empty() { + let list = self + .fields + .iter() + .map(|f| format!("{}: {}", f.name, f.ty.name())) + .collect::>() + .join(", "); + parts.push(format!("字段[{list}]")); + } + parts.join("; ") + } + + /// 装配带契约上下文的诊断(code + suggestion + doc_anchor + doc_quote + contract_ref)。 + pub fn diagnostic( + &self, + code: &str, + unit: &str, + message: String, + suggestion: String, + path: Option<&Path>, + span: Span, + ) -> Diagnostic { + Diagnostic::new(path, span, message) + .with_code(code) + .with_severity(Severity::Error) + .with_suggestion(suggestion) + .with_doc_anchor(self.anchor(path)) + .with_doc_quote(self.quote_text()) + .with_contract_ref(ContractRef { + unit: unit.to_string(), + kind: "contract".to_string(), + name: unit.to_string(), + declared: self.describe(), + }) + } +} + +/// 把第二个契约表合并进第一个(多表块;重复行 → Err 防两份契约打架)。 +pub fn merge_contract(dst: &mut Contract, src: Contract) -> std::result::Result<(), String> { + for p in src.params { + if dst.params.iter().any(|q| q.name == p.name) { + return Err(format!("契约参数 `{}` 重复(防两份契约打架)", p.name)); + } + dst.params.push(p); + } + if let Some(r) = src.returns { + if dst.returns.is_some() { + return Err("返回契约重复(防两份契约打架)".to_string()); + } + dst.returns = Some(r); + } + for f in src.fields { + if dst.fields.iter().any(|g| g.name == f.name) { + return Err(format!("契约字段 `{}` 重复(防两份契约打架)", f.name)); + } + dst.fields.push(f); + } + dst.start_line = dst.start_line.min(src.start_line); + dst.end_line = dst.end_line.max(src.end_line); + for q in src.quote { + if !dst.quote.contains(&q) { + dst.quote.push(q); + } + } + Ok(()) +} + +// ---------- 契约表识别与解析 ---------- + +const PARAM_HEADERS: &[&str] = &["参数", "形参", "param", "params", "arg", "args"]; +const RETURN_HEADERS: &[&str] = &["返回", "返回值", "return", "returns", "result"]; +const FIELD_HEADERS: &[&str] = &["字段", "列", "键", "field", "fields", "key", "keys", "column", "columns"]; +const TYPE_HEADERS: &[&str] = &["类型", "type"]; +const DESC_HEADERS: &[&str] = &["说明", "描述", "备注", "注释", "desc", "description"]; +const NULLABLE_HEADERS: &[&str] = &["可空", "nullable", "optional"]; + +fn norm_header(h: &str) -> String { + h.trim().trim_matches('`').to_ascii_lowercase() +} + +fn header_is(h: &str, vocab: &[&str]) -> bool { + let n = norm_header(h); + vocab.iter().any(|v| *v == n) +} + +fn find_col(headers: &[String], vocab: &[&str]) -> Option { + headers.iter().position(|h| header_is(h, vocab)) +} + +/// 单元格 → 文本(text / `` `ident` `` / 数字);嵌套表 → None(那是数据表)。 +fn cell_to_text(e: &Expr) -> Option { + match e { + Expr::Literal(crate::ast::Literal::Text(s)) => Some(s.clone()), + Expr::Var(name) => Some(name.clone()), + Expr::Literal(crate::ast::Literal::Int(i)) => Some(i.to_string()), + Expr::Literal(crate::ast::Literal::Num(n)) => Some(n.to_string()), + Expr::Literal(crate::ast::Literal::Bool(b)) => Some(b.to_string()), + _ => None, + } +} + +/// 列值 → 行文本(标量 = 单行;列向量 = 多行;其它 = None)。 +fn col_rows(e: &Expr) -> Option> { + match e { + Expr::List(items) => items.iter().map(cell_to_text).collect(), + scalar => Some(vec![cell_to_text(scalar)?]), + } +} + +fn is_nullable(raw: &str) -> bool { + matches!( + norm_header(raw).as_str(), + "是" | "true" | "yes" | "y" | "可空" | "✓" + ) +} + +/// 未绑定文档表(`Expr::Map`)→ 契约块。 +/// +/// - `None`:非契约形状(普通数据/说明表,原样保留)。 +/// - `Some(Err)`:契约形状但畸形(缺参数名、列不齐、多行返回表…)——必产诊断。 +/// - `Some(Ok)`:合法契约(`参数`/`返回`/`字段` 三形状之一,须含 `类型` 列)。 +pub fn parse_contract_table( + pairs: &[(String, Expr)], + start_line: u32, + end_line: u32, + quote: Vec, +) -> Option> { + let headers: Vec = pairs.iter().map(|(k, _)| k.clone()).collect(); + let kind = if find_col(&headers, PARAM_HEADERS).is_some() { + 1 + } else if find_col(&headers, RETURN_HEADERS).is_some() { + 2 + } else if find_col(&headers, FIELD_HEADERS).is_some() { + 3 + } else { + return None; + }; + // 契约表必须有 `类型` 列(否则是普通说明表——如 `| 参数 | 说明 |`)。 + let Some(type_col) = find_col(&headers, TYPE_HEADERS) else { + return None; + }; + + let meta = || (start_line, end_line, quote.clone()); + Some(match kind { + 1 => parse_params_table(pairs, &headers, type_col, meta()), + 2 => parse_return_table(pairs, &headers, type_col, meta()), + _ => parse_fields_table(pairs, &headers, type_col, meta()), + }) +} + +fn contract( + meta: (u32, u32, Vec), +) -> Contract { + Contract { + params: Vec::new(), + returns: None, + fields: Vec::new(), + start_line: meta.0, + end_line: meta.1, + quote: meta.2, + } +} + +fn malformed(meta: (u32, u32, Vec), span_line: u32, msg: String) -> Result { + let (start, end, quote) = meta; + let c = Contract { + params: Vec::new(), + returns: None, + fields: Vec::new(), + start_line: start, + end_line: end, + quote, + }; + Err(c + .diagnostic( + "contract.malformed", + "(契约表)", + msg, + "按 `参数|类型|说明` / `返回|类型|说明` / `字段|类型|可空|说明` 形状修正契约表".into(), + None, + Span { line: span_line, col: 1 }, + ) + .into()) +} + +fn parse_params_table( + pairs: &[(String, Expr)], + headers: &[String], + type_col: usize, + meta: (u32, u32, Vec), +) -> Result { + let start_line = meta.0; + let name_col = find_col(headers, PARAM_HEADERS).unwrap(); + let desc_col = find_col(headers, DESC_HEADERS); + let names = col_rows(&pairs[name_col].1).unwrap_or_default(); + let types = col_rows(&pairs[type_col].1).unwrap_or_default(); + let descs = desc_col + .and_then(|c| col_rows(&pairs[c].1)) + .unwrap_or_default(); + if names.len() != types.len() || (!descs.is_empty() && descs.len() != names.len()) { + return malformed(meta, start_line, "契约表列不齐(参数/类型/说明 行数不一致)".into()); + } + let mut c = contract(meta.clone()); + for (i, name) in names.iter().enumerate() { + let name = name.trim(); + if name.is_empty() { + return malformed(meta, start_line, format!("契约表第 {} 行缺参数名", i + 1)); + } + c.params.push(ParamContract { + name: name.to_string(), + ty: Ty::parse(&types[i]), + desc: descs.get(i).cloned().unwrap_or_default(), + }); + } + Ok(c) +} + +fn parse_return_table( + pairs: &[(String, Expr)], + headers: &[String], + type_col: usize, + meta: (u32, u32, Vec), +) -> Result { + let start_line = meta.0; + let desc_col = find_col(headers, DESC_HEADERS); + let types = col_rows(&pairs[type_col].1).unwrap_or_default(); + let descs = desc_col + .and_then(|c| col_rows(&pairs[c].1)) + .unwrap_or_default(); + if types.len() != 1 { + return malformed(meta, start_line, "返回契约只能一行(`返回|类型|说明`)".into()); + } + let mut c = contract(meta.clone()); + c.returns = Some(ReturnContract { + ty: Ty::parse(&types[0]), + desc: descs.first().cloned().unwrap_or_default(), + }); + Ok(c) +} + +fn parse_fields_table( + pairs: &[(String, Expr)], + headers: &[String], + type_col: usize, + meta: (u32, u32, Vec), +) -> Result { + let start_line = meta.0; + let name_col = find_col(headers, FIELD_HEADERS).unwrap(); + let desc_col = find_col(headers, DESC_HEADERS); + let null_col = find_col(headers, NULLABLE_HEADERS); + let names = col_rows(&pairs[name_col].1).unwrap_or_default(); + let types = col_rows(&pairs[type_col].1).unwrap_or_default(); + if names.len() != types.len() { + return malformed(meta, start_line, "契约表列不齐(字段/类型 行数不一致)".into()); + } + let mut c = contract(meta.clone()); + for (i, name) in names.iter().enumerate() { + let name = name.trim(); + if name.is_empty() { + return malformed(meta, start_line, format!("契约表第 {} 行缺字段名", i + 1)); + } + c.fields.push(FieldContract { + name: name.to_string(), + ty: Ty::parse(&types[i]), + nullable: null_col + .and_then(|c| col_rows(&pairs[c].1)) + .and_then(|rows| rows.get(i).cloned()) + .map(|s| is_nullable(&s)) + .unwrap_or(false), + desc: desc_col + .and_then(|c| col_rows(&pairs[c].1)) + .and_then(|rows| rows.get(i).cloned()) + .unwrap_or_default(), + }); + } + Ok(c) +} + +// ---------- 运行时边界校验(T2.2,四个边界) ---------- + +/// 边界 1:调用实参 vs 形参契约。 +pub fn call_arg_diag( + c: &Contract, + unit: &str, + bound: &HashMap, + path: Option<&Path>, + span: Span, +) -> Option { + for p in &c.params { + let Some(v) = bound.get(&p.name) else { continue }; + if v == &Value::None { + continue; // 显式 None = 未填,交给缺参/默认值语义 + } + if !p.ty.matches_value(v) { + return Some(c.diagnostic( + "contract.arg_mismatch", + unit, + format!( + "参数 `{}` 期望 {},实际 {}(契约校验)", + p.name, + p.ty.name(), + type_of(v) + ), + format!( + "把实参改为 {},或修正契约表 `参数/类型` 列(锚点 {})", + p.ty.name(), + c.anchor(path) + ), + path, + span, + )); + } + } + None +} + +/// 边界 2:返回值 vs 返回契约。 +pub fn return_diag( + c: &Contract, + unit: &str, + v: &Value, + path: Option<&Path>, + span: Span, +) -> Option { + let r = c.returns.as_ref()?; + if !r.ty.matches_value(v) { + return Some(c.diagnostic( + "contract.return_mismatch", + unit, + format!( + "返回值期望 {},实际 {}(契约校验)", + r.ty.name(), + type_of(v) + ), + format!( + "修正返回值,或调整契约表 `返回|类型`(锚点 {})", + c.anchor(path) + ), + path, + span, + )); + } + None +} + +/// 边界 3:表绑定 vs 字段契约(集合契约;几何即类型——标量或列向量皆可)。 +pub fn fields_diag( + c: &Contract, + unit: &str, + v: &Value, + path: Option<&Path>, + span: Span, +) -> Option { + if c.fields.is_empty() { + return None; + } + let Value::Map(pairs) = v else { + return Some(c.diagnostic( + "contract.field_mismatch", + unit, + format!("绑定值期望表(map),实际 {}(契约校验)", type_of(v)), + "绑定一个表值,或删除该字段契约表".into(), + path, + span, + )); + }; + for f in &c.fields { + match pairs.iter().find(|(k, _)| k == &f.name) { + Some((_, val)) => { + if !f.ty.matches_column(val) { + return Some(c.diagnostic( + "contract.field_mismatch", + unit, + format!( + "字段 `{}` 期望 {},实际 {}(契约校验)", + f.name, + f.ty.name(), + type_of(val) + ), + format!("修正数据,或调整契约表 `字段/类型`(锚点 {})", c.anchor(path)), + path, + span, + )); + } + } + None if f.nullable => {} + None => { + return Some(c.diagnostic( + "contract.field_mismatch", + unit, + format!("缺少字段 `{}`(契约要求,不可空)", f.name), + format!("补上字段 `{}`,或在契约表 `可空` 列标 `是`(锚点 {})", f.name, c.anchor(path)), + path, + span, + )); + } + } + } + None +} + +/// 边界 4:字段访问 `[键](集合)` vs 字段契约(键存在性 + 取值类型)。 +pub fn index_diag( + c: &Contract, + unit: &str, + key: &str, + v: &Value, + path: Option<&Path>, + span: Span, +) -> Option { + let Some(f) = c.fields.iter().find(|f| f.name == key) else { + return Some(c.diagnostic( + "contract.unknown_key", + unit, + format!("字段 `{key}` 不在契约中(契约校验)"), + format!( + "使用契约内的字段({}),或在契约表补一行", + c.fields + .iter() + .map(|f| f.name.as_str()) + .collect::>() + .join(" / ") + ), + path, + span, + )); + }; + if v != &Value::None && !f.ty.matches_column(v) { + return Some(c.diagnostic( + "contract.field_mismatch", + unit, + format!( + "字段 `{key}` 期望 {},实际 {}(契约校验)", + f.ty.name(), + type_of(v) + ), + format!("修正数据,或调整契约表 `字段/类型`(锚点 {})", c.anchor(path)), + path, + span, + )); + } + None +} diff --git a/src/diagnostics.rs b/src/diagnostics.rs index 33feddf..feed559 100644 --- a/src/diagnostics.rs +++ b/src/diagnostics.rs @@ -126,6 +126,11 @@ impl Diagnostic { self } + /// 从 anyhow 错误链中找回结构化诊断(load/parse 包了 context 也不丢;MLSP 面)。 + pub fn find(err: &anyhow::Error) -> Option<&Diagnostic> { + err.chain().find_map(|e| e.downcast_ref::()) + } + pub fn format_message(&self) -> String { match &self.path { Some(p) => format!("{}:{}: {}", display_path(p), self.span, self.message), diff --git a/src/interp.rs b/src/interp.rs index efc5e79..000eea2 100644 --- a/src/interp.rs +++ b/src/interp.rs @@ -324,6 +324,14 @@ impl Interpreter { Stmt::Assign { name, value, span, .. } => { self.current_span = *span; let v = self.eval_expr(module, fun, env, value)?; + // 契约边界 3(T2.2):表绑定 vs 字段契约。 + if let Some(c) = fun.var_contracts.get(name) { + if let Some(d) = + crate::contract::fields_diag(c, name, &v, self.path.as_deref(), *span) + { + return Err(d.into()); + } + } if self.trace { let display = v.as_display(); emit_trace( @@ -343,6 +351,14 @@ impl Interpreter { Stmt::Return { value, span } => { self.current_span = *span; let v = self.eval_expr(module, fun, env, value)?; + // 契约边界 2(T2.2):返回值 vs 返回契约。 + if let Some(c) = &fun.contract { + if let Some(d) = + crate::contract::return_diag(c, &fun.name, &v, self.path.as_deref(), *span) + { + return Err(d.into()); + } + } if self.trace { let display = v.as_display(); emit_trace( @@ -590,7 +606,38 @@ impl Interpreter { Expr::Index { base, label } => { let v = self.eval_expr(module, fun, env, base)?; let key = self.resolve_index_key(module, fun, env, label)?; - builtin_footnote_get(&v, &key).map_err(|m| self.err(m)) + // 契约边界 4(T2.2):字段访问 vs 字段契约——键存在性**先于**取值 + // (契约诊断优先于运行时 `missing map key`)。 + if let Expr::Var(name) = base.as_ref() { + if let Some(c) = fun.var_contracts.get(name) { + if let Some(d) = crate::contract::index_diag( + c, + name, + &key, + &Value::None, + self.path.as_deref(), + self.current_span, + ) { + return Err(d.into()); + } + } + } + let out = builtin_footnote_get(&v, &key).map_err(|m| self.err(m))?; + if let Expr::Var(name) = base.as_ref() { + if let Some(c) = fun.var_contracts.get(name) { + if let Some(d) = crate::contract::index_diag( + c, + name, + &key, + &out, + self.path.as_deref(), + self.current_span, + ) { + return Err(d.into()); + } + } + } + Ok(out) } Expr::Formula(e) => Ok(Value::Formula(e.clone())), Expr::Code(c) => Ok(Value::Code(c.clone())), @@ -820,6 +867,18 @@ impl Interpreter { let bound = bind_function_args(self, module, fun, env, &target.params, &ev_args, false) .map_err(|m| self.err(m))?; + // 契约边界 1(T2.2):调用实参 vs 形参契约。 + if let Some(c) = &target.contract { + if let Some(d) = crate::contract::call_arg_diag( + c, + &target.name, + &bound, + self.path.as_deref(), + self.current_span, + ) { + return Err(d.into()); + } + } let mut call_env = Env::new(); for (k, v) in bound { call_env.set(k, v); @@ -887,6 +946,18 @@ impl Interpreter { ) .map_err(|m| self.err(m))? }; + // 契约边界 1(T2.2):库路径调用的实参 vs 形参契约。 + if let Some(c) = &node.contract { + if let Some(d) = crate::contract::call_arg_diag( + c, + &display, + &bound, + self.path.as_deref(), + self.current_span, + ) { + return Err(d.into()); + } + } let mut call_env = Env::new(); for (k, v) in bound { call_env.set(k, v); @@ -933,6 +1004,18 @@ impl Interpreter { })?; let bound = bind_function_args(self, module, fun, env, &target.params, ev_args, false) .map_err(|m| self.err(m))?; + // 契约边界 1(T2.2):方法调用的实参 vs 形参契约。 + if let Some(c) = &target.contract { + if let Some(d) = crate::contract::call_arg_diag( + c, + &target.name, + &bound, + self.path.as_deref(), + self.current_span, + ) { + return Err(d.into()); + } + } let mut call_env = Env::new(); for (k, v) in bound { call_env.set(k, v); diff --git a/src/lib.rs b/src/lib.rs index 068c6af..cd4c92e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,8 @@ pub mod bytecode; pub mod capture; #[cfg(feature = "cli")] pub mod catalog; +pub mod check; +pub mod contract; pub mod debug; pub mod diagnostics; pub mod embedded_lib; diff --git a/src/load.rs b/src/load.rs index 21e75a0..727e1b2 100644 --- a/src/load.rs +++ b/src/load.rs @@ -252,6 +252,20 @@ pub fn load_module_from_source(source: &str) -> Result { load_module_from_source_inner(source, "", &mut visited) } +/// 给错误打上文件标签,**保留**结构化诊断(错误出口唯一;AI/MLSP 面不许拍平成字符串)。 +/// 无结构的错误退回 `{label}: {e}` 文本。 +fn label_error(label: &str, e: anyhow::Error) -> anyhow::Error { + match crate::diagnostics::Diagnostic::find(&e).cloned() { + Some(mut d) => { + if d.path.is_none() { + d.path = Some(PathBuf::from(label)); + } + d.into() + } + None => anyhow::anyhow!("{label}: {e}"), + } +} + fn load_module_from_source_inner( source: &str, label: &str, @@ -263,7 +277,7 @@ fn load_module_from_source_inner( } let result = (|| { - let mut module = parse_source(source).map_err(|e| anyhow::anyhow!("{label}: {e}"))?; + let mut module = parse_source(source).map_err(|e| label_error(label, e))?; let imports = module.imports.clone(); let mut import_modules = HashMap::new(); for imp in imports { @@ -274,8 +288,7 @@ fn load_module_from_source_inner( import_modules.insert(imp.bind, dep); } module.import_modules = import_modules; - crate::inherit::validate_inheritance(&module) - .map_err(|e| anyhow::anyhow!("{label}: {e}"))?; + crate::inherit::validate_inheritance(&module).map_err(|e| label_error(label, e))?; Ok(module) })(); diff --git a/src/main.rs b/src/main.rs index cb6f823..93153f9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -70,6 +70,16 @@ enum Commands { #[arg(long)] json: bool, }, + /// Static contract cross-check (渐进式契约): drift, unknown types, misplaced tables + Check { + /// Program path (.mq.md) + #[arg(value_name = "FILE")] + file: PathBuf, + + /// Emit one JSON diagnostic per line on stdout (machine-readable; AI/MLSP 面) + #[arg(long)] + json: bool, + }, /// Browse `.mq.md` structure + execution (live server or static output) View { #[command(subcommand)] @@ -179,14 +189,19 @@ enum ViewAction { fn main() -> ExitCode { let cli = Cli::parse(); - let json_errors = matches!(&cli.command, Commands::Run { json: true, .. }); + let json_errors = matches!( + &cli.command, + Commands::Run { json: true, .. } | Commands::Check { json: true, .. } + ); match try_main(cli) { Ok(code) => ExitCode::from(code as u8), Err(err) => { if json_errors { let diag = match err.downcast::() { Ok(d) => d, - Err(e) => Diagnostic::new(None, Span::new(0, 0), format!("{e:#}")), + Err(e) => Diagnostic::find(&e).cloned().unwrap_or_else(|| { + Diagnostic::new(None, Span::new(0, 0), format!("{e:#}")) + }), }; eprintln!("{}", diag.to_json()); } else { @@ -244,6 +259,28 @@ fn try_main(cli: Cli) -> Result { marqdo::run_file(&path, &opts)?; Ok(0) } + Commands::Check { file, json } => { + let diags = marqdo::check::check_path(&file)?; + let mut errors = 0i32; + for d in &diags { + if matches!(d.severity, marqdo::diagnostics::Severity::Error) { + errors += 1; + } + if json { + println!("{}", d.to_json()); + } else { + println!("{}", d.format_message()); + } + } + if !json { + if diags.is_empty() { + println!("contract check OK: 无契约问题"); + } else { + println!("contract check: {} 条诊断({} error)", diags.len(), errors); + } + } + Ok(errors.min(1)) + } Commands::View { action, path, diff --git a/src/parse/mod.rs b/src/parse/mod.rs index 994ec9a..b11cffc 100644 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -212,6 +212,8 @@ impl<'a> Cursor<'a> { children: Vec::new(), base, dead_binds: Vec::new(), + contract: None, + var_contracts: std::collections::HashMap::new(), }; // Prose decls pending promotion (name → optional default text). let mut prose_decls: Vec<(String, Option)> = Vec::new(); @@ -342,6 +344,8 @@ impl<'a> Cursor<'a> { } } + // 契约提取(T2.1)必须在升参推断**之前**:契约表的单元不污染推断。 + extract_function_contract(&mut fun, self.lines)?; merge_inferred_params(&mut fun, &prose_decls)?; Ok(fun) } @@ -1302,6 +1306,166 @@ fn stmt_from_italic_return(inner: &str, span: Span) -> Result { /// Design §8.2: elevate only when an executable read cannot be satisfied by a prior /// local assign that does not itself read the name (e.g. `score = > json.get …` is local; /// `n = n + 1` still needs external `n`). +// ---------- 契约提取(T2.1 · 渐进式契约 / 标注类型) ---------- +// +// 未绑定文档表 → 契约;**位置 + 形状**双重判定;在升参推断之前执行。 +// 契约表从 body 移除(元数据永不执行、不污染升参推断); +// 非契约表(普通文档/数据表,含一切**绑定**表)原样保留 ⇒ 无契约文件零回归。 + +/// 从表头行起收集连续 `|` 行作为契约原文(诊断 `doc_quote`)。 +fn table_quote(lines: &[ClassifiedLine], start_line: u32) -> (u32, Vec) { + let Some(mut idx) = (0..lines.len()).find(|&i| lines[i].line_no == start_line) else { + return (start_line, Vec::new()); + }; + let mut quote = Vec::new(); + let mut end = start_line; + while idx < lines.len() && lines[idx].text.trim().starts_with('|') { + quote.push(lines[idx].text.trim_end().to_string()); + end = lines[idx].line_no; + idx += 1; + } + (end, quote) +} + +/// 是否「字段契约形状」的未绑定文档表(紧邻判定的透明跳过用)。 +fn is_fields_contract_stmt(stmt: &Stmt, lines: &[ClassifiedLine]) -> bool { + let Stmt::Expr { value: Expr::Map(pairs), span } = stmt else { + return false; + }; + let (end_line, quote) = table_quote(lines, span.line); + matches!( + crate::contract::parse_contract_table(pairs, span.line, end_line, quote), + Some(Ok(ref c)) if !c.fields.is_empty() + ) +} + +/// 紧邻绑定名:跳过连续的字段契约表后,下一条是不是 `` `名` = `` 绑定。 +fn next_binding_name(body: &[Stmt], start: usize, lines: &[ClassifiedLine]) -> Option { + let mut j = start; + while j < body.len() && is_fields_contract_stmt(&body[j], lines) { + j += 1; + } + match body.get(j) { + Some(Stmt::Assign { name, .. }) => Some(name.clone()), + _ => None, + } +} + +fn empty_like(piece: &crate::contract::Contract) -> crate::contract::Contract { + crate::contract::Contract { + params: Vec::new(), + returns: None, + fields: Vec::new(), + start_line: piece.start_line, + end_line: piece.end_line, + quote: Vec::new(), + } +} + +/// 合并契约块;重复行/重复表 → `contract.duplicate` 诊断(防两份契约打架)。 +fn merge_piece( + dst: &mut Option, + piece: crate::contract::Contract, + unit: &str, + span: Span, +) -> Result<()> { + match dst { + None => *dst = Some(piece), + Some(slot) => { + if let Err(m) = crate::contract::merge_contract(slot, piece.clone()) { + return Err(piece + .diagnostic( + "contract.duplicate", + unit, + m, + "删除重复契约表,只保留一份".to_string(), + None, + span, + ) + .into()); + } + } + } + Ok(()) +} + +fn extract_function_contract(fun: &mut Function, lines: &[ClassifiedLine]) -> Result<()> { + let body = std::mem::take(&mut fun.body); + let mut fun_contract: Option = None; + let mut var_contracts: std::collections::HashMap = + std::collections::HashMap::new(); + let mut keep: Vec = Vec::with_capacity(body.len()); + // 「函数体首个可执行行之前」:未绑定表(Map/List 形状的 `Stmt::Expr`)不算可执行行。 + let mut prefix_zone = true; + let mut i = 0usize; + + while i < body.len() { + let stmt = &body[i]; + let (pairs, span) = match stmt { + Stmt::Expr { + value: Expr::Map(pairs), + span, + } => (pairs, *span), + other => { + if !matches!(other, Stmt::Expr { value: Expr::List(_), .. }) { + prefix_zone = false; + } + keep.push(other.clone()); + i += 1; + continue; + } + }; + let (end_line, quote) = table_quote(lines, span.line); + let Some(parsed) = crate::contract::parse_contract_table(pairs, span.line, end_line, quote) + else { + // 非契约形状:普通文档/数据表 → 原样保留(P1 零回归的关键)。 + keep.push(stmt.clone()); + i += 1; + continue; + }; + let piece = parsed?; // 契约形状但畸形 → 必产诊断(contract.malformed) + let is_fn_contract = !piece.params.is_empty() || piece.returns.is_some(); + + if is_fn_contract { + // 形参/返回表只在「首个可执行行之前」生效,否则视为普通表。 + if !prefix_zone { + keep.push(stmt.clone()); + i += 1; + continue; + } + merge_piece(&mut fun_contract, piece, &fun.name, span)?; + i += 1; + continue; + } + + // 字段表:紧邻 `` `名` = `` 绑定之前 → 集合契约;对象体首成员前 → 对象字段契约。 + if let Some(name) = next_binding_name(&body, i + 1, lines) { + let mut slot = Some( + var_contracts + .remove(&name) + .unwrap_or_else(|| empty_like(&piece)), + ); + merge_piece(&mut slot, piece, &name, span)?; + var_contracts.insert(name, slot.unwrap()); + i += 1; + continue; + } + if prefix_zone && fun.is_object() { + merge_piece(&mut fun_contract, piece, &fun.name, span)?; + i += 1; + continue; + } + // 不在允许位置 → 不是契约,原样保留。 + keep.push(stmt.clone()); + i += 1; + } + + fun.body = keep; + fun.contract = fun_contract; + fun.var_contracts = var_contracts; + Ok(()) +} + fn merge_inferred_params( fun: &mut Function, prose_decls: &[(String, Option)], diff --git a/tests/contracts.rs b/tests/contracts.rs new file mode 100644 index 0000000..d10c628 --- /dev/null +++ b/tests/contracts.rs @@ -0,0 +1,319 @@ +//! 渐进式契约(Phase 2 · T2.1–T2.5):契约提取、四边界运行时校验、`check` 静态互查。 +//! +//! 验收对照 `doc/roadmap/three-problems-plan.md` 的完成定义: +//! P1 零回归(绑定表/普通文档表不吃)、P2 锚点诊断、契约漂移必产诊断。 +//! 升参推断 = 散文声明(`` `名` ``)+ 体读取;契约提取在其**之前**执行。 + +use std::path::PathBuf; + +use marqdo::ast::{Expr, Function, Module, Stmt}; +use marqdo::check::check_module; +use marqdo::contract::Ty; +use marqdo::diagnostics::Diagnostic; +use marqdo::load::load_module_from_source; +use marqdo::{run_file, RunOptions}; + +fn fixture(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/contracts") + .join(name) +} + +fn find_fn<'a>(module: &'a Module, name: &str) -> &'a Function { + fn walk<'a>(funs: &'a [Function], name: &str) -> Option<&'a Function> { + for f in funs { + if f.name == name { + return Some(f); + } + if let Some(c) = walk(&f.children, name) { + return Some(c); + } + } + None + } + walk(&module.functions, name).unwrap_or_else(|| panic!("function `{name}` not found")) +} + +/// anyhow 错误链 → 结构化 Diagnostic(load 的 context 包裹也不丢)。 +fn structured(err: anyhow::Error) -> Diagnostic { + match err.downcast::() { + Ok(d) => d, + Err(e) => Diagnostic::find(&e) + .cloned() + .expect("错误必须是结构化 Diagnostic(AI/MLSP 面)"), + } +} + +/// 运行夹具并断言失败的错误是结构化 Diagnostic。 +fn run_err_code(name: &str) -> Diagnostic { + let err = run_file(&fixture(name), &RunOptions::default()) + .expect_err(&format!("{name}: 期望契约报错,实际运行通过")); + structured(err) +} + +// ---------- T2.1 提取 ---------- + +#[test] +fn extracts_param_and_return_contract() { + let src = "\ +# main + +## 加一 + +对于输入变量`n`,执行加一。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| n | number | 输入值 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| | number | 加一结果 | + +*n+1* +"; + let module = load_module_from_source(src).unwrap(); + let fun = find_fn(&module, "加一"); + let c = fun.contract.as_ref().expect("应提取到函数契约"); + assert_eq!(c.params.len(), 1); + assert_eq!(c.params[0].name, "n"); + assert_eq!(c.params[0].ty, Ty::Number); + assert_eq!(c.params[0].desc, "输入值"); + assert_eq!(c.returns.as_ref().unwrap().ty, Ty::Number); + // 契约表从 body 移除(元数据永不执行) + assert!( + !fun.body + .iter() + .any(|s| matches!(s, Stmt::Expr { value: Expr::Map(_), .. })), + "契约表应从 body 移除,剩余 body: {:?}", fun.body + ); + // 升参(散文声明 `n` + 体读取)恰好覆盖契约 + assert_eq!( + fun.params.iter().map(|p| p.name.as_str()).collect::>(), + ["n"] + ); + // T2.4:锚点 + 原文行 + assert_eq!(c.start_line, 7); + assert!(c.quote.iter().any(|q| q.contains("| 参数 | 类型 | 说明 |"))); +} + +#[test] +fn contract_cells_do_not_pollute_inference() { + // 契约说明列里的 `` `x` `` 只是文档提及——提取先于升参推断,`x` 不得被升参。 + let src = "\ +# main + +## 加一 + +对于输入变量`n`,临时量`x`。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| n | number | 与 `x` 相加 | + +*n+1* +"; + let module = load_module_from_source(src).unwrap(); + let fun = find_fn(&module, "加一"); + assert_eq!(fun.contract.as_ref().unwrap().params[0].name, "n"); + assert_eq!( + fun.params.iter().map(|p| p.name.clone()).collect::>(), + ["n"], + "契约单元格的名不得被升参(提取先于推断)" + ); +} + +#[test] +fn bound_data_table_never_contract() { + // P1 零回归反例:**绑定**的 `字段|类型|可空` 数据表(web_db_migration 风格)不吃。 + let module = load_module_from_source( + &std::fs::read_to_string(fixture("bound_data_table.mq.md")).unwrap(), + ) + .unwrap(); + let fun = find_fn(&module, "main"); + assert!(fun.contract.is_none()); + assert!(fun.var_contracts.is_empty()); + run_file(&fixture("bound_data_table.mq.md"), &RunOptions::default()) + .expect("绑定数据表必须照常运行"); +} + +#[test] +fn duplicate_contract_tables_diagnosed() { + // 两份契约打架 ⇒ 必产诊断(防漂移的一部分)。 + let src = "\ +# main + +## 加一 + +对于输入变量`n`,执行加一。 + +| 参数 | 类型 | +|------|------| +| n | number | + +| 参数 | 类型 | +|------|------| +| n | number | + +*n+1* +"; + let err = load_module_from_source(src).expect_err("重复契约必须报错"); + let d = structured(err); + assert_eq!(d.to_json()["code"], "contract.duplicate"); +} + +// ---------- T2.2 四边界运行时校验 ---------- + +#[test] +fn call_arg_mismatch_reports_contract_diagnostic() { + let d = run_err_code("arg_mismatch.mq.md"); + let v = d.to_json(); + assert_eq!(v["code"], "contract.arg_mismatch"); + assert!( + v["message"].as_str().unwrap().contains("参数 `n` 期望 number,实际 text"), + "{v}" + ); + assert_eq!(v["severity"], "error"); + // T2.4:锚点能回溯到出错表,且带原文行 + assert!(v["doc_anchor"].as_str().unwrap().contains("#L")); + assert!( + v["doc_quote"].as_str().unwrap().contains("| 参数 | 类型 | 说明 |"), + "doc_quote 应含契约表原文: {v}" + ); + // contract_ref 指向声明 + assert!( + v["contract_ref"]["declared"].as_str().unwrap().contains("number"), + "{v}" + ); +} + +#[test] +fn return_mismatch_reports_contract_diagnostic() { + let d = run_err_code("return_mismatch.mq.md"); + let v = d.to_json(); + assert_eq!(v["code"], "contract.return_mismatch"); + assert!( + v["message"].as_str().unwrap().contains("返回值期望 number,实际 text"), + "{v}" + ); + assert!(v["doc_anchor"].as_str().unwrap().contains("#L")); +} + +#[test] +fn field_mismatch_at_binding_reports_contract_diagnostic() { + // 字段表紧邻绑定之前 ⇒ 集合契约(T2.1);绑定时校验(边界 3)。 + let module = load_module_from_source( + &std::fs::read_to_string(fixture("field_mismatch.mq.md")).unwrap(), + ) + .unwrap(); + let fun = find_fn(&module, "main"); + let c = fun.var_contracts.get("用户").expect("应提取到集合契约"); + assert_eq!(c.fields.len(), 2); + assert_eq!(c.fields[0].name, "id"); + assert_eq!(c.fields[0].ty, Ty::Number); + assert!(!c.fields[0].nullable); + assert!(c.fields[1].nullable); + + let d = run_err_code("field_mismatch.mq.md"); + let v = d.to_json(); + assert_eq!(v["code"], "contract.field_mismatch"); + assert!( + v["doc_quote"].as_str().unwrap().contains("| 字段 | 类型 | 可空 |"), + "{v}" + ); +} + +#[test] +fn unknown_key_at_index_reports_contract_diagnostic() { + let d = run_err_code("unknown_key.mq.md"); + let v = d.to_json(); + assert_eq!(v["code"], "contract.unknown_key"); + assert!(v["message"].as_str().unwrap().contains("email"), "{v}"); +} + +#[test] +fn ok_contract_runs_unchanged() { + run_file(&fixture("ok_contract.mq.md"), &RunOptions::default()) + .expect("合法契约必须照常运行(P1/P2:不改变正常执行)"); +} + +// ---------- T2.3/T2.5 `check` 静态互查 ---------- + +#[test] +fn check_catches_param_drift() { + let src = "\ +# main + +## 加一 + +对于输入变量`n`,执行加一。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| nn | number | 输入值 | + +*n+1* +"; + let module = load_module_from_source(src).unwrap(); + let diags = check_module(&module, None); + let jsons: Vec = diags.iter().map(|d| d.to_json()).collect(); + assert!( + jsons.iter().any(|v| v["code"] == "contract.param_drift" && v["severity"] == "error"), + "契约行名字错位 ⇒ Error: {jsons:?}" + ); + assert!( + jsons.iter().any(|v| v["code"] == "contract.param_drift" && v["severity"] == "warning"), + "新升参未被契约覆盖 ⇒ Warning: {jsons:?}" + ); +} + +#[test] +fn check_catches_unknown_type_with_suggestion() { + let src = "\ +# main + +## 加一 + +对于输入变量`n`,执行加一。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| n | nubmer | 输入值 | + +*n+1* +"; + let module = load_module_from_source(src).unwrap(); + let diags = check_module(&module, None); + let d = diags + .iter() + .find(|d| d.to_json()["code"] == "contract.unknown_type") + .expect("未知类型名必产诊断(防 nubmer 拼错)"); + let v = d.to_json(); + assert!( + v["suggestion"].as_str().unwrap().contains("number"), + "应给出最近建议: {v}" + ); + assert!(v["doc_anchor"].as_str().unwrap().contains("#L")); +} + +#[test] +fn check_catches_misplaced_contract_table() { + let src = "\ +# main + +**x=1** + +| 参数 | 类型 | 说明 | +|------|------|------| +| n | number | 输入值 | + +*x* +"; + let module = load_module_from_source(src).unwrap(); + let diags = check_module(&module, None); + assert!( + diags.iter().any(|d| d.to_json()["code"] == "contract.misplaced"), + "错位契约必产诊断: {:?}", + diags.iter().map(|d| d.to_json()).collect::>() + ); +} diff --git a/tests/contracts/arg_mismatch.mq.md b/tests/contracts/arg_mismatch.mq.md new file mode 100644 index 0000000..97cc2c1 --- /dev/null +++ b/tests/contracts/arg_mismatch.mq.md @@ -0,0 +1,17 @@ +# main + +> 加一 "七" + +## 加一 + +对于输入变量`n`,期望是数字。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| n | number | 输入值 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| | number | 加一结果 | + +*n+1* diff --git a/tests/contracts/bound_data_table.mq.md b/tests/contracts/bound_data_table.mq.md new file mode 100644 index 0000000..92984eb --- /dev/null +++ b/tests/contracts/bound_data_table.mq.md @@ -0,0 +1,9 @@ +# main + +`列说明` = +| 字段 | 类型 | 可空 | +|------|------|------| +| id | number | | +| name | text | 是 | + +*`列说明`[^字段]* diff --git a/tests/contracts/field_mismatch.mq.md b/tests/contracts/field_mismatch.mq.md new file mode 100644 index 0000000..54b5b1d --- /dev/null +++ b/tests/contracts/field_mismatch.mq.md @@ -0,0 +1,13 @@ +# main + +| 字段 | 类型 | 可空 | +|------|------|------| +| id | number | | +| name | text | 是 | + +`用户` = +| id | name | +|------|------| +| abc | 小明 | + +*`用户`[^name]* diff --git a/tests/contracts/ok_contract.mq.md b/tests/contracts/ok_contract.mq.md new file mode 100644 index 0000000..eca4759 --- /dev/null +++ b/tests/contracts/ok_contract.mq.md @@ -0,0 +1,18 @@ +# main + +**结果 = > 加一 3** +*结果* + +## 加一 + +对于输入变量`n`,期望是数字。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| n | number | 输入值 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| | number | 加一结果 | + +*n+1* diff --git a/tests/contracts/return_mismatch.mq.md b/tests/contracts/return_mismatch.mq.md new file mode 100644 index 0000000..b125bd2 --- /dev/null +++ b/tests/contracts/return_mismatch.mq.md @@ -0,0 +1,18 @@ +# main + +**结果 = > 转换 "七"** +*结果* + +## 转换 + +对于输入变量`s`,期望是文本。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| s | text | 输入 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| | number | 转换结果 | + +*s* diff --git a/tests/contracts/unknown_key.mq.md b/tests/contracts/unknown_key.mq.md new file mode 100644 index 0000000..6effc47 --- /dev/null +++ b/tests/contracts/unknown_key.mq.md @@ -0,0 +1,13 @@ +# main + +| 字段 | 类型 | 可空 | +|------|------|------| +| id | number | | +| name | text | 是 | + +`用户` = +| id | name | +|------|------| +| 1 | 小明 | + +*`用户`[^email]*