---
title: "诊断"
---

> Documentation Index
> Fetch the complete documentation index at: https://koine.systems/llms.txt
> Use this file to discover all available pages before exploring further.

# 诊断

诊断是值，不是异常。`check` 返回二选一：成功带世界，失败带诊断列表。

## 阶段

每个阶段只产生自己那一段的码，不共享全局错误状态。

| 阶段 | 产出 | 典型错误 |
| --- | --- | --- |
| `parse` | AST + span | 意外 token、未闭合括号 |
| `resolve` | 名字表 | 未知类型、未知关系、重名 |
| `type` | 类型化 AST | 参数类型、arity、key、聚合 |
| `state` | 世界 | 实体重复、元组重复、非法项 |
| `axiom` | 边或拒绝 | 目标世界违反约束 |
| `run` | 路径 | 未知 transition、绑定不匹配、某步被拒 |

## 结构

> 特性：K-024

参考 RFC 9457 的字段划分，但不使用它的 HTTP 语义。

| RFC 9457 | Koine 诊断 | 说明 |
| --- | --- | --- |
| `type` | `code` | 分段文本，不是 URI |
| `title` | `title` | 简短摘要 |
| `detail` | `detail` | 详细解释 |
| `instance` | `span` | 源文件位置，不是 URI |
| `status` | 不用 | 编译器诊断没有 HTTP 状态码 |
| 扩展字段 | `suggestion`、`notes` | 结构化建议 |

```text
Diagnostic {
  code:       "koine.type.sort-mismatch",
  title:      "参数类型不匹配",
  detail:     "第 2 个参数应该是 Order，实际是 Customer",
  span:       { start, end },
  suggestion: Suggestion | null,
  notes:      [string],
}

Suggestion {
  kind:  "replace" | "insert" | "delete" | "rename" | "create",
  title: string,
  edits: [Edit],
}

Edit {
  span:        { start, end },
  replacement: string,
}
```

## 渲染

终端渲染包含四行：

```text
error[koine.type.sort-mismatch]: 参数类型不匹配
  --> model.koi:12:18
   |
12 |   placed_by(o1, c1)
   |                 ^^ 第 2 个参数应该是 Order，实际是 Customer
   = note: relation placed_by 定义在 4:3
   = help: 把 c1 换成 o1
```

规则：

- 第一行：`severity[code]: title`。
- 第二行：文件、行、列。
- 第三行：源码行。
- 第四行：caret + detail。
- `note` 和 `help` 按需追加。

## 排序

诊断按 `span.start` 升序，再按 `code` 字典序。同一位置的多条诊断合并显示。

## 机器可读

`--format json` 输出：

```json
[
  {
    "code": "koine.type.sort-mismatch",
    "title": "参数类型不匹配",
    "detail": "第 2 个参数应该是 Order，实际是 Customer",
    "span": { "start": 187, "end": 189 },
    "suggestion": {
      "kind": "replace",
      "title": "把 c1 换成 o1",
      "edits": [{ "span": { "start": 187, "end": 189 }, "replacement": "o1" }]
    },
    "notes": ["relation placed_by 定义在 4:3"]
  }
]
```

## 建议应用

- `edits` 的 span 相对于原始源文件。
- 应用时从后往前，或一次性构建。
- `kind` 只影响展示，不影响应用。
- `suggestion` 可以为空。
- 多个建议不自动合并，由调用方选择。

## 错误恢复

解析器遇到错误时：

1. 记录诊断。
2. 跳到下一个顶层声明或分号/换行边界。
3. 继续解析。
4. 返回部分 AST 和全部诊断。

目标不是"猜对"，是"一次报告多个独立错误"。

## 错误码

见[错误码](https://koine.systems/reference/errors/)。

Source: https://koine.systems/reference/spec/diagnostics/index.mdx
