migrate: own Table value operations as std:collections/table #2

Merged
cflmy merged 1 commits from migration/stdlib-collections into main 2026-11-26 23:58:12 +08:00
7 changed files with 853 additions and 6 deletions

No files matched your search

+26 -5
View File
@@ -1,14 +1,35 @@
# marqdo-std-collections
本仓负责List、Map 和 Table 值操作。当前状态为 `planned`。
本仓负责 List、Map 和 Table 的通用值操作。当前处于**标准库源码归位迁移**阶段:Table 值操作源码与断言已迁入本仓,等待父仓候选组合验收(父仓工单 [marqdo#9](https://git.cflmy.cn/cflmy/marqdo/issues/9),本仓工单 [#1](https://git.cflmy.cn/cflmy/marqdo-std-collections/issues/1))。
## 首项任务
## 唯一公开入口(Bundle 根相对路径)
实现 List、Map 和 Table 的通用集合操作,从数据格式处理中拆出表格算法。
| 发布路径 | 公开导入 | 职责 |
| --- | --- | --- |
| `collections/table.mq.md` | `std:collections/table` | Table 值操作:选择列、过滤、插入有序、排序、追加行、设置单元格、连接、分组 |
**公开路径调整(本迁移内的库组织调整)**:原 `std:data/table` 的 Table 值操作入口迁移为 `std:collections/table`;序列化(`连接片段`/`连接行`/`转义单元格`/`转GFM`)归 `std:data/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 的真实 Table 输出(值操作部分);修改期望值等于声明公开行为变化,必须单独评审。
## 边界
不实现语言内核、Host 权限或其他标准库;Table 序列化不属于本仓;不新增集合算法之外的语义。
[生态迁移台账](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/MIGRATION.md) · [开发流程](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/DEVELOPMENT.md)
+267
View File
@@ -0,0 +1,267 @@
# @exec table
## 选择列
`params(数据, 列)`
**列名 = table.columns(数据)**
**结果行 = []**
**行号 = 0**
`while 行号 < 长度(数据)`
**行 = table.row(数据, 行号)**
**结果行 = list.append(结果行, [行[列]])**
**行号 = 行号 + 1**
`end`
`return 表([列名[列]], 结果行)`
## 过滤数值大于
`params(数据, 列, 阈值)`
**列名 = table.columns(数据)**
**结果行 = []**
**行号 = 0**
`while 行号 < 长度(数据)`
**行 = table.row(数据, 行号)**
`if 行[列] > 阈值`
**结果行 = list.append(结果行, 行)**
`else`
`if true`
**忽略 = 0**
`end`
`end`
**行号 = 行号 + 1**
`end`
`return 表(列名, 结果行)`
## 插入有序
`params(已排序, 行, 列)`
**新列表 = []**
**已插入 = false**
**下标 = 0**
`while 下标 < 长度(已排序)`
**当前行 = 已排序[下标]**
`if not 已插入 and 当前行[列] > 行[列]`
**新列表 = list.append(新列表, 行)**
**新列表 = list.append(新列表, 当前行)**
**已插入 = true**
`else`
`if true`
**新列表 = list.append(新列表, 当前行)**
`end`
`end`
**下标 = 下标 + 1**
`end`
`if not 已插入`
**新列表 = list.append(新列表, 行)**
`else`
`if true`
**忽略 = 0**
`end`
`end`
`return 新列表`
## 排序
`params(数据, 列)`
**列名 = table.columns(数据)**
**行数 = 长度(数据)**
**已排序 = []**
**下标 = 0**
`while 下标 < 行数`
**已排序 = 插入有序(已排序, table.row(数据, 下标), 列)**
**下标 = 下标 + 1**
`end`
`return 表(列名, 已排序)`
## 追加行
`params(数据, 行)`
**列名 = table.columns(数据)**
**所有行 = []**
**行号 = 0**
`while 行号 < 长度(数据)`
**所有行 = list.append(所有行, table.row(数据, 行号))**
**行号 = 行号 + 1**
`end`
`return 表(列名, list.append(所有行, 行))`
## 设置单元格
`params(数据, 目标行, 目标列, 值)`
**列名 = table.columns(数据)**
**新行表 = []**
**行号 = 0**
`while 行号 < 长度(数据)`
**行 = table.row(数据, 行号)**
`if 行号 == 目标行`
**新行 = []**
**列号 = 0**
`while 列号 < 长度(行)`
`if 列号 == 目标列`
**新行 = list.append(新行, 值)**
`else`
`if true`
**新行 = list.append(新行, 行[列号])**
`end`
`end`
**列号 = 列号 + 1**
`end`
**新行表 = list.append(新行表, 新行)**
`else`
`if true`
**新行表 = list.append(新行表, 行)**
`end`
`end`
**行号 = 行号 + 1**
`end`
`return 表(列名, 新行表)`
## 连接
`params(左, 右, 左列, 右列)`
**表头 = list.concat(table.columns(左), table.columns(右))**
**结果行 = []**
**左行号 = 0**
`while 左行号 < 长度(左)`
**左行 = table.row(左, 左行号)**
**键 = 左行[左列]**
**右行号 = 0**
`while 右行号 < 长度(右)`
**右行 = table.row(右, 右行号)**
`if 右行[右列] == 键`
**结果行 = list.append(结果行, list.concat(左行, 右行))**
`else`
`if true`
**忽略 = 0**
`end`
`end`
**右行号 = 右行号 + 1**
`end`
**左行号 = 左行号 + 1**
`end`
`return 表(表头, 结果行)`
## 分组
`params(数据, 键列, 值列)`
**结果 = {}**
**行号 = 0**
`while 行号 < 长度(数据)`
**行 = table.row(数据, 行号)**
**键 = 行[键列]**
**当前 = map.get(结果, 键)**
**列表 = []**
`if map.has(结果, 键)`
**列表 = 当前**
`else`
`if true`
**忽略 = 0**
`end`
`end`
**列表 = list.append(列表, 行[值列])**
**结果 = map.set(结果, 键, 列表)**
**行号 = 行号 + 1**
`end`
`return 结果`
+207
View File
@@ -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())
+7
View File
@@ -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" "$@"
+5 -1
View File
@@ -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 的真实执行结果;修改期望值等于声明公开行为变化,必须单独评审。
+311
View File
@@ -0,0 +1,311 @@
{
"schema": "marqdo.stdlib-test-case",
"schema_version": 1,
"name": "table",
"file": "table.mq.md",
"require_module": "collections/table.mq.md",
"args": [],
"stdin": "",
"env": {},
"expected_stdout": "",
"expected_terminal": {
"type": "list",
"items": [
{
"header": [
"分数"
],
"rows": [
[
{
"decimal": "87",
"type": "int"
}
],
[
{
"decimal": "92",
"type": "int"
}
],
[
{
"decimal": "71",
"type": "int"
}
]
],
"type": "table"
},
{
"header": [
"名称",
"分数"
],
"rows": [
[
{
"type": "text",
"value": "甲"
},
{
"decimal": "87",
"type": "int"
}
],
[
{
"type": "text",
"value": "乙"
},
{
"decimal": "92",
"type": "int"
}
]
],
"type": "table"
},
{
"header": [
"名称",
"分数"
],
"rows": [
[
{
"type": "text",
"value": "丙"
},
{
"decimal": "71",
"type": "int"
}
],
[
{
"type": "text",
"value": "甲"
},
{
"decimal": "87",
"type": "int"
}
],
[
{
"type": "text",
"value": "乙"
},
{
"decimal": "92",
"type": "int"
}
]
],
"type": "table"
},
{
"header": [
"名称",
"分数"
],
"rows": [
[
{
"type": "text",
"value": "甲"
},
{
"decimal": "87",
"type": "int"
}
],
[
{
"type": "text",
"value": "乙"
},
{
"decimal": "92",
"type": "int"
}
],
[
{
"type": "text",
"value": "丙"
},
{
"decimal": "71",
"type": "int"
}
],
[
{
"type": "text",
"value": "丁"
},
{
"decimal": "65",
"type": "int"
}
]
],
"type": "table"
},
{
"header": [
"名称",
"分数"
],
"rows": [
[
{
"type": "text",
"value": "甲"
},
{
"decimal": "99",
"type": "int"
}
],
[
{
"type": "text",
"value": "乙"
},
{
"decimal": "92",
"type": "int"
}
],
[
{
"type": "text",
"value": "丙"
},
{
"decimal": "71",
"type": "int"
}
]
],
"type": "table"
},
{
"header": [
"名称",
"分数",
"名称",
"等级"
],
"rows": [
[
{
"type": "text",
"value": "甲"
},
{
"decimal": "87",
"type": "int"
},
{
"type": "text",
"value": "甲"
},
{
"type": "text",
"value": "B"
}
],
[
{
"type": "text",
"value": "乙"
},
{
"decimal": "92",
"type": "int"
},
{
"type": "text",
"value": "乙"
},
{
"type": "text",
"value": "A"
}
]
],
"type": "table"
},
{
"entries": {
"a": {
"items": [
{
"decimal": "1",
"type": "int"
},
{
"decimal": "3",
"type": "int"
}
],
"type": "list"
},
"b": {
"items": [
{
"decimal": "2",
"type": "int"
}
],
"type": "list"
}
},
"type": "map"
},
{
"header": [
"名称",
"分数"
],
"rows": [
[
{
"type": "text",
"value": "甲"
},
{
"decimal": "87",
"type": "int"
}
],
[
{
"type": "text",
"value": "乙"
},
{
"decimal": "92",
"type": "int"
}
],
[
{
"type": "text",
"value": "丙"
},
{
"decimal": "71",
"type": "int"
}
]
],
"type": "table"
}
]
}
}
+30
View File
@@ -0,0 +1,30 @@
---
import:
table_lib: "std:collections/table"
---
# @exec table
## main
**数据 = 表(["名称", "分数"], [["甲", 87], ["乙", 92], ["丙", 71]])**
**选择 = table_lib.选择列(数据, 1)**
**过滤 = table_lib.过滤数值大于(数据, 1, 80)**
**排序 = table_lib.排序(数据, 1)**
**追加 = table_lib.追加行(数据, ["丁", 65])**
**设置 = table_lib.设置单元格(数据, 0, 1, 99)**
**左 = 表(["名称", "分数"], [["甲", 87], ["乙", 92]])**
**右 = 表(["名称", "等级"], [["乙", "A"], ["甲", "B"]])**
**连接 = table_lib.连接(左, 右, 0, 0)**
**分组 = table_lib.分组(表(["类别", "值"], [["a", 1], ["b", 2], ["a", 3]]), 0, 1)**
`return [选择, 过滤, 排序, 追加, 设置, 连接, 分组, 数据]`