From 848af7a357ceda2cfc20721b93406cf4be705889 Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 26 Nov 2026 23:32:22 +0800 Subject: [PATCH] migrate: own JSON/CSV and Table serialization; drop the value algorithms Move JSON, CSV and the Table serialization half of the frozen module to their unique source authority. Value operations now live only in std-collections; there is no second implementation or legacy forwarder. Baseline JSON/CSV and Table GFM expectations are carried into component cases. Refs cflmy/marqdo#9, cflmy/marqdo-std-data#1 --- README.md | 33 +- modules/data/csv.mq.md | 354 +++++++++++++++ modules/data/json.mq.md | 920 +++++++++++++++++++++++++++++++++++++++ modules/data/table.mq.md | 151 +++++++ scripts/run_cases.py | 207 +++++++++ scripts/test.sh | 7 + tests/README.md | 6 +- tests/cases/csv.json | 102 +++++ tests/cases/json.json | 78 ++++ tests/cases/table.json | 20 + tests/csv.mq.md | 22 + tests/json.mq.md | 42 ++ tests/table.mq.md | 12 + 13 files changed, 1948 insertions(+), 6 deletions(-) create mode 100644 modules/data/csv.mq.md create mode 100644 modules/data/json.mq.md create mode 100644 modules/data/table.mq.md create mode 100755 scripts/run_cases.py create mode 100755 scripts/test.sh create mode 100644 tests/cases/csv.json create mode 100644 tests/cases/json.json create mode 100644 tests/cases/table.json create mode 100644 tests/csv.mq.md create mode 100644 tests/json.mq.md create mode 100644 tests/table.mq.md diff --git a/README.md b/README.md index 7a3ce90..f6922bc 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,37 @@ # marqdo-std-data -本仓负责JSON、CSV、TOML 与 GFM 数据转换。当前状态为 `planned`。 +本仓负责 JSON、CSV 与 GFM 数据交换。当前处于**标准库源码归位迁移**阶段:JSON/CSV 与 Table 序列化源码、断言已迁入本仓,等待父仓候选组合验收(父仓工单 [marqdo#9](https://git.cflmy.cn/cflmy/marqdo/issues/9),本仓工单 [#1](https://git.cflmy.cn/cflmy/marqdo-std-data/issues/1))。 -## 首项任务 +## 唯一公开入口(Bundle 根相对路径) -迁入 JSON、CSV 和表格格式转换,补齐 TOML 与 GFM。 +| 发布路径 | 公开导入 | 职责 | +| --- | --- | --- | +| `data/json.mq.md` | `std:data/json` | 递归 JSON 解析/格式化(128 层上限、多值) | +| `data/csv.mq.md` | `std:data/csv` | 引号单行/多行 CSV 解析与格式化 | +| `data/table.mq.md` | `std:data/table` | Table 序列化:`连接片段`、`连接行`、`转义单元格`、`转GFM` | + +**职责切分(本迁移内冻结)**:Table 值操作归 `std:collections/table`,本仓只保留序列化;不复制集合算法,不保留旧入口兼容转发。跨模块组合断言由根 Bundle 组合测试承担。 + +`modules/` 保存 Bundle 根相对路径;Bundle 与 `stdlib.json` 由父仓唯一生产者生成,本仓不维护第二份官方 manifest。 ## 目录 -- [modules/](modules/README.md) 存放对外发布的模块源码。 -- [tests/](tests/README.md) 存放独立验收用的输入和断言。 +- `modules/`:对外发布的模块源码。 +- `tests/`:迁入的自测源与 `tests/cases/` 期望。 +- `scripts/`:独立验收入口。 + +## 独立验收 + +```sh +MARQDO_BIN=/path/to/verified/marqdo \ +MARQDO_STDLIB_DIR=/path/to/installed/bundle \ +scripts/test.sh +``` + +期望值取自迁移前基线 Bundle 的真实执行(JSON/CSV 分项断言、Table GFM 输出);修改期望值等于声明公开行为变化,必须单独评审。 + +## 边界 + +不实现语言内核、Host 权限、集合算法或数据库接口;GFM 序列化只复用自身转义/连接函数。 [生态迁移台账](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/MIGRATION.md) · [开发流程](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/DEVELOPMENT.md) diff --git a/modules/data/csv.mq.md b/modules/data/csv.mq.md new file mode 100644 index 0000000..2bf57be --- /dev/null +++ b/modules/data/csv.mq.md @@ -0,0 +1,354 @@ + +# @exec csv +## 成功 + +`params(值)` + +`return {ok: true, value: 值}` + +## 失败 + +`params(代码, 消息)` + +`return {ok: false, code: 代码, message: 消息}` + +## 解析行 + +`params(文本)` + +解析单行 CSV:逗号分隔、双引号包裹、"" 表示一个字面双引号。 +不处理换行、多行字段或首尾空白。未闭合引号和未加引号字段中的双引号 +返回可恢复错误。 + +**点 = text.codepoints(文本)** + +**下标 = 0** + +**字段 = ""** + +**字段表 = []** + +**引号内 = false** + +**错误 = ""** + +`while 下标 < 长度(点) and 错误 == ""` + +**字符 = text.from_codepoint(点[下标])** + +`if 引号内 and 字符 == "\""` + +`if 下标 + 1 < 长度(点) and text.from_codepoint(点[下标 + 1]) == "\""` + +**`字段 = 字段 + "\""`** + +**下标 = 下标 + 2** + +`else` +`if true` + +**引号内 = false** + +**下标 = 下标 + 1** + +`end` +`end` +`else` +`if 引号内` + +**字段 = 字段 + 字符** + +**下标 = 下标 + 1** + +`else` +`if 字符 == "\""` + +`if 字段 == ""` + +**引号内 = true** + +**下标 = 下标 + 1** + +`else` +`if true` + +**错误 = "csv.invalid_quote"** + +`end` +`end` +`else` +`if 字符 == ","` + +**字段表 = list.append(字段表, 字段)** + +**字段 = ""** + +**下标 = 下标 + 1** + +`else` +`if true` + +**字段 = 字段 + 字符** + +**下标 = 下标 + 1** + +`end` +`end` +`end` +`end` +`end` +`end` +`if 错误 != ""` + +`return 失败(错误, "未加引号字段中出现双引号")` + +`else` +`if 引号内` + +`return 失败("csv.unterminated_quote", "引号未闭合")` + +`end` +`end` +`return 成功(list.concat(字段表, [字段]))` + +## 格式化字段 + +`params(文本)` + +含逗号、双引号、换行或回车的字段加引号,内部双引号写成 ""。 + +**点 = text.codepoints(文本)** + +**下标 = 0** + +**需要引号 = false** + +`while 下标 < 长度(点) and not 需要引号` + +**码点 = 点[下标]** + +`if 码点 == 34 or 码点 == 44 or 码点 == 10 or 码点 == 13` + +**需要引号 = true** + +`else` +`if true` + +**忽略 = 0** + +`end` +`end` +**下标 = 下标 + 1** + +`end` +`if not 需要引号` + +`return 文本` + +`end` +**`结果 = "\""`** + +**下标 = 0** + +`while 下标 < 长度(点)` + +`if 点[下标] == 34` + +**`结果 = 结果 + "\"\""`** + +`else` +`if true` + +**结果 = 结果 + text.from_codepoint(点[下标])** + +`end` +`end` +**下标 = 下标 + 1** + +`end` +``return 结果 + "\""`` + +## 格式化行 + +`params(列表)` + +**结果 = ""** + +**下标 = 0** + +`while 下标 < 长度(列表)` + +`if 下标 > 0` + +**结果 = 结果 + ","** + +`else` +`if true` + +**忽略 = 0** + +`end` +`end` +**结果 = 结果 + 格式化字段(文本(列表[下标]))** + +**下标 = 下标 + 1** + +`end` +`return 结果` + +## 解析 + +`params(文本)` + +解析多行 CSV(逗号分隔、双引号、"" 转义、CRLF/LF 行尾,引号内可含 +换行)。返回 {ok:true, value:List>};未闭合引号和不合法 +引号返回可恢复错误。 + +**点 = text.codepoints(文本)** + +**下标 = 0** + +**字段 = ""** + +**当前行 = []** + +**行 = []** + +**引号内 = false** + +**错误 = ""** + +`while 下标 < 长度(点) and 错误 == ""` + +**字符 = text.from_codepoint(点[下标])** + +`if 引号内 and 字符 == "\""` + +`if 下标 + 1 < 长度(点) and text.from_codepoint(点[下标 + 1]) == "\""` + +**`字段 = 字段 + "\""`** + +**下标 = 下标 + 2** + +`else` +`if true` + +**引号内 = false** + +**下标 = 下标 + 1** + +`end` +`end` +`else` +`if 引号内` + +**字段 = 字段 + 字符** + +**下标 = 下标 + 1** + +`else` +`if 字符 == "\""` + +`if 字段 == ""` + +**引号内 = true** + +**下标 = 下标 + 1** + +`else` +`if true` + +**错误 = "csv.invalid_quote"** + +`end` +`end` +`else` +`if 字符 == ","` + +**当前行 = list.append(当前行, 字段)** + +**字段 = ""** + +**下标 = 下标 + 1** + +`else` +`if 字符 == "\n"` + +**当前行 = list.append(当前行, 字段)** + +**行 = list.append(行, 当前行)** + +**当前行 = []** + +**字段 = ""** + +**下标 = 下标 + 1** + +`else` +`if 字符 == "\r"` + +**下标 = 下标 + 1** + +`else` +`if true` + +**字段 = 字段 + 字符** + +**下标 = 下标 + 1** + +`end` +`end` +`end` +`end` +`end` +`end` +`end` +`end` +`if 错误 != ""` + +`return 失败(错误, "未加引号字段中出现双引号")` + +`else` +`if 引号内` + +`return 失败("csv.unterminated_quote", "引号未闭合")` + +`else` +`if 字段 != "" or 长度(当前行) > 0` + +**当前行 = list.append(当前行, 字段)** + +**行 = list.append(行, 当前行)** + +`end` +`end` +`end` +`return 成功(行)` + +## 格式化 + +`params(行列表)` + +**结果 = ""** + +**行号 = 0** + +`while 行号 < 长度(行列表)` + +`if 行号 > 0` + +**结果 = 结果 + "\n"** + +`else` +`if true` + +**忽略 = 0** + +`end` +`end` +**结果 = 结果 + 格式化行(行列表[行号])** + +**行号 = 行号 + 1** + +`end` +`return 结果` diff --git a/modules/data/json.mq.md b/modules/data/json.mq.md new file mode 100644 index 0000000..76d8eac --- /dev/null +++ b/modules/data/json.mq.md @@ -0,0 +1,920 @@ + +# @exec json +## 嵌套深度 + +`params(文本)` + +按未转义字符串之外的 {/[ 计算最大嵌套深度。 + +**点 = text.codepoints(文本)** + +**下标 = 0** + +**深度 = 0** + +**最大 = 0** + +**字符串内 = false** + +**转义 = false** + +`while 下标 < 长度(点)` + +**码点 = 点[下标]** + +`if 字符串内` + +`if 转义` + +**转义 = false** + +`else` +`if 码点 == 92` + +**转义 = true** + +`else` +`if 码点 == 34` + +**字符串内 = false** + +`else` +`if true` + +**忽略 = 0** + +`end` +`end` +`end` +`end` +`else` +`if 码点 == 34` + +**字符串内 = true** + +`else` +`if 码点 == 123 or 码点 == 91` + +**深度 = 深度 + 1** + +`if 深度 > 最大` + +**最大 = 深度** + +`else` +`if true` + +**忽略 = 0** + +`end` +`end` +`else` +`if 码点 == 125 or 码点 == 93` + +`if 深度 > 0` + +**深度 = 深度 - 1** + +`else` +`if true` + +**忽略 = 0** + +`end` +`end` +`else` +`if true` + +**忽略 = 0** + +`end` +`end` +`end` +`end` +`end` +**下标 = 下标 + 1** + +`end` +`return 最大` + +## 解析 + +`params(文本)` + +解析一个完整的 JSON 文本。值之后只允许空白;多余输入返回 +json.trailing,嵌套超过 128 层返回 json.depth。成功结果只保留 +{ok, value},不暴露内部游标。 + +**点 = text.codepoints(文本)** + +`if 嵌套深度(文本) > 128` + +`return 失败("json.depth", "嵌套深度超过 128")` + +`end` +**结果 = 解析值(点, 0)** + +`if not 结果.ok` + +`return 结果` + +`end` +**位置 = 跳过空白(点, 结果.next)** + +`if 位置 != 长度(点)` + +`return 失败("json.trailing", "值后存在多余输入")` + +`end` +`return {ok: true, value: 结果.value}` + +## 成功值 + +`params(值, 下一位置)` + +`return {ok: true, value: 值, next: 下一位置}` + +## 失败 + +`params(代码, 消息)` + +`return {ok: false, code: 代码, message: 消息}` + +## 是空白 + +`params(码点)` + +`return 码点 == 32 or 码点 == 9 or 码点 == 10 or 码点 == 13` + +## 是数字 + +`params(码点)` + +`return 码点 >= 48 and 码点 <= 57` + +## 跳过空白 + +`params(点, 位置)` + +**当前 = 位置** + +`while 当前 < 长度(点) and 是空白(点[当前])` + +**当前 = 当前 + 1** + +`end` +`return 当前` + +## 匹配 + +`params(点, 位置, 文本)` + +**目标 = text.codepoints(文本)** + +**下标 = 0** + +**结果 = true** + +`while 下标 < 长度(目标) and 结果` + +`if 位置 + 下标 >= 长度(点)` + +**结果 = false** + +`else` +`if 点[位置 + 下标] != 目标[下标]` + +**结果 = false** + +`else` +`if true` + +**继续 = 0** + +`end` +`end` +`end` +**下标 = 下标 + 1** + +`end` +`return 结果` + +## 片段 + +`params(点, 起点, 终点)` + +**结果 = ""** + +**下标 = 起点** + +`while 下标 < 终点` + +**结果 = 结果 + text.from_codepoint(点[下标])** + +**下标 = 下标 + 1** + +`end` +`return 结果` + +## 解析数字 + +`params(点, 位置)` + +JSON 数字:可选负号、整数位、可选小数位、可选指数;含 ./e 返回 Float。 + +**开始 = 位置** + +**当前 = 位置** + +`if text.from_codepoint(点[当前]) == "-"` + +**当前 = 当前 + 1** + +`else` +`if true` + +**非负 = 0** + +`end` +`end` +**整数位 = 0** + +`while 当前 < 长度(点) and 是数字(点[当前])` + +**整数位 = 整数位 + 1** + +**当前 = 当前 + 1** + +`end` +**有小数 = false** + +**小数位 = 0** + +`if 当前 < 长度(点) and text.from_codepoint(点[当前]) == "."` + +**有小数 = true** + +**当前 = 当前 + 1** + +`while 当前 < 长度(点) and 是数字(点[当前])` + +**小数位 = 小数位 + 1** + +**当前 = 当前 + 1** + +`end` +`else` +`if true` + +**忽略 = 0** + +`end` +`end` +**指数位 = 0** + +**指数标记 = false** + +`if 当前 < 长度(点) and (text.from_codepoint(点[当前]) == "e" or text.from_codepoint(点[当前]) == "E")` + +**有小数 = true** + +**指数标记 = true** + +**当前 = 当前 + 1** + +`if 当前 < 长度(点) and (text.from_codepoint(点[当前]) == "+" or text.from_codepoint(点[当前]) == "-")` + +**当前 = 当前 + 1** + +`else` +`if true` + +**忽略指数符号 = 0** + +`end` +`end` +`while 当前 < 长度(点) and 是数字(点[当前])` + +**指数位 = 指数位 + 1** + +**当前 = 当前 + 1** + +`end` +`else` +`if 整数位 == 0` + +`return 失败("json.invalid_number", "数字缺少整数位")` + +`else` +`if 有小数 and not 指数标记 and 小数位 == 0` + +`return 失败("json.invalid_number", "小数缺少位数")` + +`else` +`if 指数标记 and 指数位 == 0` + +`return 失败("json.invalid_number", "指数缺少位数")` + +`end` +`end` +`end` +`end` +**原文 = 片段(点, 开始, 当前)** + +`if 有小数` + +`return 成功值(小数(原文), 当前)` + +`end` +`return 成功值(整数(原文), 当前)` + +## 十六进制值 + +`params(码点)` + +`if 码点 >= 48 and 码点 <= 57` + +`return 码点 - 48` + +`else` +`if 码点 >= 65 and 码点 <= 70` + +`return 码点 - 55` + +`else` +`if 码点 >= 97 and 码点 <= 102` + +`return 码点 - 87` + +`end` +`end` +`end` +`return 0 - 1` + +## 解析字符串 + +`params(点, 位置)` + +**当前 = 位置 + 1** + +**结果 = ""** + +**完成 = false** + +**错误 = ""** + +`while 当前 < 长度(点) and not 完成 and 错误 == ""` + +**码点 = 点[当前]** + +`if 码点 == 34` + +**完成 = true** + +**当前 = 当前 + 1** + +`else` +`if 码点 == 92` + +`if 当前 + 1 >= 长度(点)` + +**错误 = "json.invalid_escape"** + +`else` +`if true` + +**转义码点 = 点[当前 + 1]** + +`if 转义码点 == 34` + +**结果 = 结果 + text.from_codepoint(34)** + +**当前 = 当前 + 2** + +`else` +`if 转义码点 == 92` + +**结果 = 结果 + text.from_codepoint(92)** + +**当前 = 当前 + 2** + +`else` +`if 转义码点 == 47` + +**结果 = 结果 + text.from_codepoint(47)** + +**当前 = 当前 + 2** + +`else` +`if 转义码点 == 98` + +**结果 = 结果 + text.from_codepoint(8)** + +**当前 = 当前 + 2** + +`else` +`if 转义码点 == 102` + +**结果 = 结果 + text.from_codepoint(12)** + +**当前 = 当前 + 2** + +`else` +`if 转义码点 == 110` + +**结果 = 结果 + text.from_codepoint(10)** + +**当前 = 当前 + 2** + +`else` +`if 转义码点 == 114` + +**结果 = 结果 + text.from_codepoint(13)** + +**当前 = 当前 + 2** + +`else` +`if 转义码点 == 116` + +**结果 = 结果 + text.from_codepoint(9)** + +**当前 = 当前 + 2** + +`else` +`if 转义码点 == 117` + +`if 当前 + 5 >= 长度(点)` + +**错误 = "json.invalid_escape"** + +`else` +`if true` + +**数字 = 十六进制值(点[当前 + 2]) * 4096 + 十六进制值(点[当前 + 3]) * 256 + 十六进制值(点[当前 + 4]) * 16 + 十六进制值(点[当前 + 5])** + +`if 数字 < 0 or (数字 >= 55296 and 数字 <= 57343)` + +**错误 = "json.invalid_escape"** + +`else` +`if true` + +**结果 = 结果 + text.from_codepoint(数字)** + +**当前 = 当前 + 6** + +`end` +`end` +`end` +`end` +`else` +`if true` + +**错误 = "json.invalid_escape"** + +`end` +`end` +`end` +`end` +`end` +`end` +`end` +`end` +`end` +`end` +`end` +`end` +`else` +`if true` + +**结果 = 结果 + text.from_codepoint(码点)** + +**当前 = 当前 + 1** + +`end` +`end` +`end` +`end` +`if 错误 != ""` + +`return 失败("json.invalid_string", "字符串转义无效")` + +`else` +`if not 完成` + +`return 失败("json.unexpected_eof", "字符串未闭合")` + +`end` +`end` +`return 成功值(结果, 当前)` + +## 解析对象 + +`params(点, 位置)` + +`return 解析对象项(点, 位置 + 1, {})` + +## 解析对象项 + +`params(点, 位置, 已解析)` + +**位置 = 跳过空白(点, 位置)** + +`if 位置 >= 长度(点)` + +`return 失败("json.unexpected_eof", "对象未闭合")` + +`end` +**当前 = text.from_codepoint(点[位置])** + +`if 当前 == "}"` + +`return 成功值(已解析, 位置 + 1)` + +`end` +**键结果 = 解析字符串(点, 位置)** + +`if not 键结果.ok` + +`return 键结果` + +`end` +**键 = 键结果.value** + +**位置 = 跳过空白(点, 键结果.next)** + +`if 位置 >= 长度(点)` + +`return 失败("json.unexpected_eof", "对象缺少冒号")` + +`else` +`if text.from_codepoint(点[位置]) != ":"` + +`return 失败("json.invalid_object", "对象缺少冒号")` + +`end` +`end` +**位置 = 跳过空白(点, 位置 + 1)** + +**值结果 = 解析值(点, 位置)** + +`if not 值结果.ok` + +`return 值结果` + +`end` +**新的已解析 = map.set(已解析, 键, 值结果.value)** + +**位置 = 跳过空白(点, 值结果.next)** + +`if 位置 >= 长度(点)` + +`return 失败("json.unexpected_eof", "对象未闭合")` + +`end` +**分隔 = text.from_codepoint(点[位置])** + +`if 分隔 == ","` + +`return 解析对象项(点, 位置 + 1, 新的已解析)` + +`else` +`if 分隔 == "}"` + +`return 成功值(新的已解析, 位置 + 1)` + +`else` +`if true` + +`return 失败("json.invalid_object", "对象缺少逗号或 }")` + +`end` +`end` +`end` +## 解析值 + +`params(点, 位置)` + +**位置 = 跳过空白(点, 位置)** + +`if 位置 >= 长度(点)` + +`return 失败("json.unexpected_eof", "需要值")` + +`end` +**首 = text.from_codepoint(点[位置])** + +**首码点 = 点[位置]** + +`if 首码点 == 34` + +`return 解析字符串(点, 位置)` + +`else` +`if 首码点 == 123` + +`return 解析对象(点, 位置)` + +`else` +`if 首 == "["` + +`return 解析数组(点, 位置)` + +`else` +`if 首 == "-" or 是数字(点[位置])` + +`return 解析数字(点, 位置)` + +`else` +`if 首 == "t"` + +`if 匹配(点, 位置, "true")` + +`return 成功值(true, 位置 + 4)` + +`else` +`if true` + +`return 失败("json.invalid_literal", "无效字面量")` + +`end` +`end` +`else` +`if 首 == "f"` + +`if 匹配(点, 位置, "false")` + +`return 成功值(false, 位置 + 5)` + +`else` +`if true` + +`return 失败("json.invalid_literal", "无效字面量")` + +`end` +`end` +`else` +`if 首 == "n"` + +`if 匹配(点, 位置, "null")` + +`return 成功值(None, 位置 + 4)` + +`else` +`if true` + +`return 失败("json.invalid_literal", "无效字面量")` + +`end` +`end` +`else` +`if true` + +`return 失败("json.unexpected_token", "不支持的值")` + +`end` +`end` +`end` +`end` +`end` +`end` +`end` +`end` +## 解析数组 + +`params(点, 位置)` + +`return 解析数组项(点, 位置 + 1, [])` + +## 解析数组项 + +`params(点, 位置, 已解析)` + +**位置 = 跳过空白(点, 位置)** + +`if 位置 >= 长度(点)` + +`return 失败("json.unexpected_eof", "数组未闭合")` + +`end` +**当前 = text.from_codepoint(点[位置])** + +`if 当前 == "]"` + +`return 成功值(已解析, 位置 + 1)` + +`end` +**项 = 解析值(点, 位置)** + +`if not 项.ok` + +`return 项` + +`end` +**新的已解析 = list.append(已解析, 项.value)** + +**位置 = 跳过空白(点, 项.next)** + +`if 位置 >= 长度(点)` + +`return 失败("json.unexpected_eof", "数组未闭合")` + +`end` +**分隔 = text.from_codepoint(点[位置])** + +`if 分隔 == ","` + +`return 解析数组项(点, 位置 + 1, 新的已解析)` + +`else` +`if 分隔 == "]"` + +`return 成功值(新的已解析, 位置 + 1)` + +`else` +`if true` + +`return 失败("json.invalid_array", "数组缺少逗号或 ]")` + +`end` +`end` +`end` +## 格式化文本 + +`params(文本)` + +**点 = text.codepoints(文本)** + +**`结果 = "\""`** + +**下标 = 0** + +`while 下标 < 长度(点)` + +**码点 = 点[下标]** + +`if 码点 == 34` + +**`结果 = 结果 + "\\\""`** + +`else` +`if 码点 == 92` + +**`结果 = 结果 + "\\\\"`** + +`else` +`if 码点 == 10` + +**`结果 = 结果 + "\\n"`** + +`else` +`if 码点 == 9` + +**`结果 = 结果 + "\\t"`** + +`else` +`if 码点 == 13` + +**`结果 = 结果 + "\\r"`** + +`else` +`if true` + +**结果 = 结果 + text.from_codepoint(码点)** + +`end` +`end` +`end` +`end` +`end` +`end` +**下标 = 下标 + 1** + +`end` +``return 结果 + "\""`` + +## 格式化列表 + +`params(列表)` + +**结果 = "["** + +**下标 = 0** + +`while 下标 < 长度(列表)` + +`if 下标 > 0` + +**结果 = 结果 + ", "** + +`else` +`if true` + +**忽略 = 0** + +`end` +`end` +**结果 = 结果 + 格式化(列表[下标])** + +**下标 = 下标 + 1** + +`end` +`return 结果 + "]"` + +## 格式化对象 + +`params(映射)` + +**键列表 = map.keys(映射)** + +**结果 = "{"** + +**下标 = 0** + +`while 下标 < 长度(键列表)` + +`if 下标 > 0` + +**结果 = 结果 + ", "** + +`else` +`if true` + +**忽略 = 0** + +`end` +`end` +**当前键 = 键列表[下标]** + +**结果 = 结果 + 格式化文本(当前键) + ": " + 格式化(map.get(映射, 当前键))** + +**下标 = 下标 + 1** + +`end` +`return 结果 + "}"` + +## 格式化 + +`params(值)` + +**类别 = 类型(值)** + +`if 类别 == "Text"` + +`return 格式化文本(值)` + +`else` +`if 类别 == "None"` + +`return "null"` + +`else` +`if 类别 == "Bool" or 类别 == "Int" or 类别 == "Float"` + +`return 文本(值)` + +`else` +`if 类别 == "List"` + +`return 格式化列表(值)` + +`else` +`if 类别 == "Map"` + +`return 格式化对象(值)` + +`end` +`end` +`end` +`end` +`end` +`return "null"` + +## 解析多个 + +`params(文本)` + +解析连续多个 JSON 值(空白分隔),返回 {ok:true, value:List}。 +任一项失败时返回该项的错误,不返回部分结果。 + +**点 = text.codepoints(文本)** + +**位置 = 跳过空白(点, 0)** + +**结果 = []** + +`while 位置 < 长度(点)` + +**项 = 解析值(点, 位置)** + +`if not 项.ok` + +`return 项` + +`end` +**结果 = list.append(结果, 项.value)** + +**位置 = 跳过空白(点, 项.next)** + +`end` +`return {ok: true, value: 结果}` diff --git a/modules/data/table.mq.md b/modules/data/table.mq.md new file mode 100644 index 0000000..430ce1a --- /dev/null +++ b/modules/data/table.mq.md @@ -0,0 +1,151 @@ + +# @exec table +## 连接片段 + +`params(片段)` + +**结果 = ""** + +**下标 = 0** + +`while 下标 < 长度(片段)` + +`if 下标 > 0` + +**结果 = 结果 + " | "** + +`else` +`if true` + +**忽略 = 0** + +`end` +`end` +**结果 = 结果 + 片段[下标]** + +**下标 = 下标 + 1** + +`end` +`return 结果` + +## 连接行 + +`params(行列表)` + +**结果 = ""** + +**下标 = 0** + +`while 下标 < 长度(行列表)` + +`if 下标 > 0` + +**结果 = 结果 + "\n"** + +`else` +`if true` + +**忽略 = 0** + +`end` +`end` +**结果 = 结果 + 行列表[下标]** + +**下标 = 下标 + 1** + +`end` +`return 结果` + +## 转义单元格 + +`params(值)` + +**文本值 = 文本(值)** + +**点 = text.codepoints(文本值)** + +**结果 = ""** + +**下标 = 0** + +`while 下标 < 长度(点)` + +`if 点[下标] == 124` + +**结果 = 结果 + text.from_codepoint(92) + "|"** + +`else` +`if 点[下标] == 10 or 点[下标] == 13` + +**结果 = 结果 + " "** + +`else` +`if true` + +**结果 = 结果 + text.from_codepoint(点[下标])** + +`end` +`end` +`end` +**下标 = 下标 + 1** + +`end` +`return 结果` + +## 转GFM + +`params(数据)` + +**列名 = table.columns(数据)** + +**表头 = []** + +**下标 = 0** + +`while 下标 < 长度(列名)` + +**表头 = list.append(表头, 转义单元格(列名[下标]))** + +**下标 = 下标 + 1** + +`end` +**行列表 = []** + +**行列表 = list.append(行列表, "| " + 连接片段(表头) + " |")** + +**分隔 = []** + +**下标 = 0** + +`while 下标 < 长度(列名)` + +**分隔 = list.append(分隔, "---")** + +**下标 = 下标 + 1** + +`end` +**行列表 = list.append(行列表, "| " + 连接片段(分隔) + " |")** + +**行号 = 0** + +`while 行号 < 长度(数据)` + +**行 = table.row(数据, 行号)** + +**单元格 = []** + +**列号 = 0** + +`while 列号 < 长度(行)` + +**单元格 = list.append(单元格, 转义单元格(行[列号]))** + +**列号 = 列号 + 1** + +`end` +**行列表 = list.append(行列表, "| " + 连接片段(单元格) + " |")** + +**行号 = 行号 + 1** + +`end` +`return 连接行(行列表)` diff --git a/scripts/run_cases.py b/scripts/run_cases.py new file mode 100755 index 0000000..0e38c3d --- /dev/null +++ b/scripts/run_cases.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +"""Run this component's public `.mq.md` self-tests against a real CLI Bundle. + +Inputs are explicit and never discovered from sibling checkouts: + +* ``MARQDO_BIN`` verified ``marqdo`` executable; +* ``MARQDO_STDLIB_DIR`` Bundle that already installs this component's modules at + their frozen bundle paths (the Bundle identity is the caller's responsibility; + the CLI itself verifies the manifest digest before loading a module). + +Each ``tests/cases/*.json`` file pins one self-test: the source file, stdin, CLI +flags, environment, the expected bundle module path and the expected observation +terminal value / stdout. The expected values are the baseline captured from the +pre-migration CLI Bundle; a change is a public behaviour change and must be +reviewed as one. + +Usage: scripts/test.sh [CASE_NAME...] +""" + +from __future__ import annotations + +import argparse +import base64 +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +REPO = Path(__file__).resolve().parents[1] +CASES = REPO / "tests" / "cases" +SCHEMA = "marqdo.stdlib-test-case" +SCHEMA_VERSION = 1 + + +class CaseError(Exception): + pass + + +def _substitute(value, bin_version: str): + if isinstance(value, dict): + if set(value) == {"$bin_version"}: + return bin_version + return {key: _substitute(item, bin_version) for key, item in value.items()} + if isinstance(value, list): + return [_substitute(item, bin_version) for item in value] + return value + + +def _channel_text(events: list[dict], channel: str) -> str: + chunks = [] + for event in events: + if event.get("kind") != channel: + continue + payload = event["payload"] + data = base64.b64decode(payload["data_base64"]) + if len(data) != payload["byte_count"]: + raise CaseError(f"{channel} byte_count does not match decoded bytes") + chunks.append(data) + return b"".join(chunks).decode("utf-8") + + +def _run_case(case: dict, case_path: Path, binary: str, bundle: Path) -> None: + name = case["name"] + module = case.get("require_module") + if module and not (bundle / module).is_file(): + raise CaseError(f"{name}: Bundle {bundle} does not install {module}") + source = REPO / "tests" / case["file"] + if not source.is_file(): + raise CaseError(f"{name}: missing test source {source}") + for relative in case.get("clean", []): + target = (REPO / relative).resolve() + if REPO not in target.parents: + raise CaseError(f"{name}: clean path escapes the repository") + if target.is_dir(): + shutil.rmtree(target) + elif target.exists(): + target.unlink() + env = os.environ.copy() + env["MARQDO_STDLIB_DIR"] = str(bundle) + for key, value in case.get("env", {}).items(): + env[key] = str(value).replace("$MARQDO_BIN", binary) + version = subprocess.run( + [binary, "--version"], capture_output=True, text=True, check=True + ).stdout + args = [str(arg).replace("$MARQDO_BIN", binary) for arg in case.get("args", [])] + command = [binary, "run", str(source), *args, "--output", "json"] + result = subprocess.run( + command, + cwd=REPO, + env=env, + input=case.get("stdin", "").encode(), + capture_output=True, + ) + if result.returncode != 0: + raise CaseError( + f"{name}: CLI exited {result.returncode}\nstderr:\n" + f"{result.stderr.decode(errors='replace')}" + ) + try: + report = json.loads(result.stdout) + except json.JSONDecodeError as error: + raise CaseError(f"{name}: CLI did not emit a JSON report: {error}") from error + if report.get("run", {}).get("status") != "ok": + raise CaseError(f"{name}: run status is not ok: {report.get('run')}") + events = report.get("events") or [] + if not events or events[-1].get("kind") not in ( + "run.completed", + "run.failed", + "run.rejected", + ): + raise CaseError(f"{name}: report has no terminal event") + terminal = events[-1]["payload"] + if terminal.get("status") != "ok": + raise CaseError(f"{name}: terminal status is not ok: {terminal.get('status')}") + actual_value = terminal.get("value") + expected_value = _substitute(case["expected_terminal"], version) + if actual_value != expected_value: + raise CaseError( + f"{name}: terminal value changed\nexpected: " + f"{json.dumps(expected_value, ensure_ascii=False, sort_keys=True)}\n" + f"actual: {json.dumps(actual_value, ensure_ascii=False, sort_keys=True)}" + ) + expected_stdout = case.get("expected_stdout", "") + actual_stdout = _channel_text(events, "stdout.chunk") + if actual_stdout != expected_stdout: + raise CaseError( + f"{name}: stdout changed: expected {expected_stdout!r}, got {actual_stdout!r}" + ) + for check in case.get("event_checks", []): + matching = [ + event + for event in events + if event.get("kind") == check["kind"] + and all( + _dig(event.get("payload"), pointer) == expected + for pointer, expected in check.get("payload", {}).items() + ) + ] + if not matching: + raise CaseError( + f"{name}: no {check['kind']} event matched {check.get('payload')}" + ) + + +def _dig(value, pointer: str): + current = value + for part in pointer.split("."): + if isinstance(current, list): + current = current[int(part)] + elif isinstance(current, dict): + current = current[part] + else: + return object() + return current + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("cases", nargs="*", help="case names to run") + args = parser.parse_args() + binary = os.environ.get("MARQDO_BIN") + bundle = os.environ.get("MARQDO_STDLIB_DIR") + if not binary or not shutil.which(binary): + print("MARQDO_BIN must point at a verified marqdo executable", file=sys.stderr) + return 2 + if not bundle or not Path(bundle).is_dir(): + print("MARQDO_STDLIB_DIR must point at an installed Bundle", file=sys.stderr) + return 2 + bundle = Path(bundle).resolve() + paths = sorted(CASES.glob("*.json")) + if not paths: + print("no test cases in tests/cases", file=sys.stderr) + return 2 + selected = set(args.cases) + failures = 0 + ran = 0 + for path in paths: + try: + case = json.loads(path.read_text(encoding="utf-8")) + except json.JSONDecodeError as error: + print(f"FAIL {path.name}: invalid JSON: {error}", file=sys.stderr) + failures += 1 + continue + if case.get("schema") != SCHEMA or case.get("schema_version") != SCHEMA_VERSION: + print(f"FAIL {path.name}: unsupported case schema", file=sys.stderr) + failures += 1 + continue + if selected and case["name"] not in selected: + continue + ran += 1 + try: + _run_case(case, path, binary, bundle) + print(f"PASS {case['name']}") + except CaseError as error: + print(f"FAIL {error}", file=sys.stderr) + failures += 1 + if failures: + print(f"{failures} of {ran} cases failed", file=sys.stderr) + return 1 + print(f"{ran} cases passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/test.sh b/scripts/test.sh new file mode 100755 index 0000000..ae97e8f --- /dev/null +++ b/scripts/test.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# Explicit inputs only: a verified CLI binary and a Bundle that installs this +# component's modules at their frozen paths. Never discovers sibling checkouts. +set -eu +: "${MARQDO_BIN:?set MARQDO_BIN to the verified marqdo executable}" +: "${MARQDO_STDLIB_DIR:?set MARQDO_STDLIB_DIR to the installed Bundle}" +exec python3 "$(dirname "$0")/run_cases.py" "$@" diff --git a/tests/README.md b/tests/README.md index 7d9f050..17856da 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,3 +1,7 @@ # 验收测试 -首个功能附带正例和失败用例,记录所用 CLI 提交或发行版本以及实际运行命令。 +`tests/*.mq.md` 是迁移期保留的真实测试源;`tests/cases/*.json` 固定输入(stdin、CLI 参数、环境、所需 Bundle 模块)与期望结果(observation 终值、stdout、必要的资源事件)。 + +运行入口是 `scripts/test.sh`,要求显式传入 `MARQDO_BIN` 与 `MARQDO_STDLIB_DIR`。缺少制品、Bundle 缺少模块或 digest 校验失败时必须失败,不得回退到其它目录。 + +期望值取自迁移前基线 Bundle 的真实执行结果;修改期望值等于声明公开行为变化,必须单独评审。 diff --git a/tests/cases/csv.json b/tests/cases/csv.json new file mode 100644 index 0000000..8190c48 --- /dev/null +++ b/tests/cases/csv.json @@ -0,0 +1,102 @@ +{ + "schema": "marqdo.stdlib-test-case", + "schema_version": 1, + "name": "csv", + "file": "csv.mq.md", + "require_module": "data/csv.mq.md", + "args": [], + "stdin": "", + "env": {}, + "expected_stdout": "", + "expected_terminal": { + "items": [ + { + "items": [ + { + "type": "text", + "value": "甲" + }, + { + "type": "text", + "value": "乙,丙" + }, + { + "type": "text", + "value": "说\"好" + } + ], + "type": "list" + }, + { + "type": "text", + "value": "甲,\"乙,丙\",\"说\"\"好\"" + }, + { + "items": [ + { + "type": "text", + "value": "" + } + ], + "type": "list" + }, + { + "type": "text", + "value": "csv.unterminated_quote" + }, + { + "items": [ + { + "type": "text", + "value": "a" + }, + { + "type": "text", + "value": "b" + } + ], + "type": "list" + }, + { + "type": "bool", + "value": true + }, + { + "items": [ + { + "items": [ + { + "type": "text", + "value": "甲" + }, + { + "type": "text", + "value": "乙,丙" + } + ], + "type": "list" + }, + { + "items": [ + { + "type": "text", + "value": "说\"好" + }, + { + "type": "text", + "value": "2" + } + ], + "type": "list" + } + ], + "type": "list" + }, + { + "type": "text", + "value": "甲,\"乙,丙\"\n\"说\"\"好\",2" + } + ], + "type": "list" + } +} diff --git a/tests/cases/json.json b/tests/cases/json.json new file mode 100644 index 0000000..89f1964 --- /dev/null +++ b/tests/cases/json.json @@ -0,0 +1,78 @@ +{ + "schema": "marqdo.stdlib-test-case", + "schema_version": 1, + "name": "json", + "file": "json.mq.md", + "require_module": "data/json.mq.md", + "args": [], + "stdin": "", + "env": {}, + "expected_stdout": "", + "expected_terminal": { + "items": [ + { + "type": "bool", + "value": true + }, + { + "decimal": "1", + "type": "int" + }, + { + "type": "text", + "value": "说\"好" + }, + { + "type": "text", + "value": "[1, 2.5, -300.0, 0.4, {\"a\": 1.0}, \"x\"]" + }, + { + "type": "bool", + "value": false + }, + { + "type": "text", + "value": "json.invalid_array" + }, + { + "type": "text", + "value": "json.trailing" + }, + { + "type": "bool", + "value": false + }, + { + "type": "text", + "value": "json.depth" + }, + { + "type": "bool", + "value": true + }, + { + "items": [ + { + "decimal": "1", + "type": "int" + }, + { + "decimal": "2", + "type": "int" + }, + { + "items": [ + { + "decimal": "3", + "type": "int" + } + ], + "type": "list" + } + ], + "type": "list" + } + ], + "type": "list" + } +} diff --git a/tests/cases/table.json b/tests/cases/table.json new file mode 100644 index 0000000..e4020f7 --- /dev/null +++ b/tests/cases/table.json @@ -0,0 +1,20 @@ +{ + "schema": "marqdo.stdlib-test-case", + "schema_version": 1, + "name": "table", + "file": "table.mq.md", + "require_module": "data/table.mq.md", + "args": [], + "stdin": "", + "env": {}, + "expected_stdout": "", + "expected_terminal": { + "type": "list", + "items": [ + { + "type": "text", + "value": "| 名称 | 分数 |\n| --- | --- |\n| 甲 | 87 |\n| 乙 | 92 |\n| 丙 | 71 |" + } + ] + } +} diff --git a/tests/csv.mq.md b/tests/csv.mq.md new file mode 100644 index 0000000..38d5d1d --- /dev/null +++ b/tests/csv.mq.md @@ -0,0 +1,22 @@ +--- +import: + csv: "std:data/csv" +--- + +# @exec csv + +## main + +**`行 = csv.解析行("甲,\"乙,丙\",\"说\"\"好\"")`** + +**`空 = csv.解析行("")`** + +**`坏 = csv.解析行("\"a")`** + +**`框 = csv.解析行("a,\"b\"")`** + +**`多行 = csv.解析("甲,\"乙,丙\"\n\"说\"\"好\",2")`** + +**格式化 = csv.格式化(多行.value)** + +`return [行.value, csv.格式化行(行.value), 空.value, 坏.code, 框.value, 多行.ok, 多行.value, 格式化]` diff --git a/tests/json.mq.md b/tests/json.mq.md new file mode 100644 index 0000000..7c98e41 --- /dev/null +++ b/tests/json.mq.md @@ -0,0 +1,42 @@ +--- +import: + json: "std:data/json" +--- + +# @exec json + +## main + +**`对象 = json.解析("{\"a\": 1, \"b\": [true, null, \"说\\\"好\"]}")`** + +**`浮点 = json.解析("[1, 2.5, -3e2, 4E-1, {\"a\": 1.0}, \"x\"]")`** + +**`失败 = json.解析("[1 2]")`** + +**`尾随 = json.解析("1 2")`** + +**深度文本 = ""** + +**深度下标 = 0** + +`while 深度下标 < 130` + +**深度文本 = 深度文本 + "["** + +**深度下标 = 深度下标 + 1** + +`end` +**深度下标 = 0** + +`while 深度下标 < 130` + +**深度文本 = 深度文本 + "]"** + +**深度下标 = 深度下标 + 1** + +`end` +**深度 = json.解析(深度文本)** + +**`多个 = json.解析多个("1 2 [3]")`** + +`return [对象.ok, 对象.value.a, 对象.value.b[2], json.格式化(浮点.value), 失败.ok, 失败.code, 尾随.code, 深度.ok, 深度.code, 多个.ok, 多个.value]` diff --git a/tests/table.mq.md b/tests/table.mq.md new file mode 100644 index 0000000..9940553 --- /dev/null +++ b/tests/table.mq.md @@ -0,0 +1,12 @@ +--- +import: + table_lib: "std:data/table" +--- + +# @exec table + +## main + +**数据 = 表(["名称", "分数"], [["甲", 87], ["乙", 92], ["丙", 71]])** + +`return [table_lib.转GFM(数据)]`