migrate: own text/UTF-8 sources and carry their baseline assertions #2

Merged
cflmy merged 2 commits from migration/stdlib-text into main 2026-11-26 23:58:08 +08:00
10 changed files with 603 additions and 6 deletions

No files matched your search

+29 -5
View File
@@ -1,14 +1,38 @@
# marqdo-std-text
本仓负责Unicode 文本、字节值与 UTF-8。当前状态为 `planned`。
本仓负责 Unicode 文本、字节值与 UTF-8。当前处于**标准库源码归位迁移**阶段:源码与断言已迁入本仓,等待父仓候选组合验收(父仓工单 [marqdo#9](https://git.cflmy.cn/cflmy/marqdo/issues/9),本仓工单 [#1](https://git.cflmy.cn/cflmy/marqdo-std-text/issues/1))。
## 首项任务
## 唯一公开入口(Bundle 根相对路径)
统一 Unicode 文本、字节值切片和 UTF-8 编解码。
| 发布路径 | 公开导入 | 职责 |
| --- | --- | --- |
| `text/utf8.mq.md` | `std:text/utf8` | UTF-8 编解码的**唯一**实现 |
| `text.mq.md` | `std:text` | `utf8编码` 的公开名称,薄封装调用 `std:text/utf8`,不复制算法 |
`modules/` 保存将来 Bundle 根下的相对路径;Bundle 与 `stdlib.json` 由父仓唯一生产者生成,本仓不维护第二份官方 manifest。
## 目录
- [modules/](modules/README.md) 存放对外发布的模块源码。
- [tests/](tests/README.md) 存放独立验收用的输入和断言。
- `modules/`:对外发布的模块源码(Bundle 根相对路径)。
- `tests/`:迁移期保留的 `.mq.md` 自测源与 `tests/cases/` 期望(observation 终值、stdout、参数、环境)。
- `scripts/`:独立验收入口。
## 独立验收
只接受显式传入的已验证制品,不读取兄弟仓物理路径或浮动分支:
```sh
MARQDO_BIN=/path/to/verified/marqdo \
MARQDO_STDLIB_DIR=/path/to/installed/bundle \
scripts/test.sh
```
- `MARQDO_BIN`:真实 CLI 二进制;`MARQDO_STDLIB_DIR`:已安装且通过 manifest digest 校验、包含本仓模块的 Bundle。
- `tests/cases/*.json` 的期望值来自迁移前 CLI Bundle 基线的真实执行结果;修改期望值等于声明公开行为变化,必须单独评审。
- 测试覆盖 UTF-8 字节序列、中文/多字节/emoji、空串和边界 Memory;非法 UTF-8 行为以基线断言为准。
## 边界
不实现语言内核、Host 权限、资源原语或其他标准库;UTF-8 算法只存在于 `text/utf8.mq.md`。标准库聚合(`marqdo-stdlib`)尚未建立,本仓保持父仓 catalog 的 `planned` 状态,直到同候选组合验收通过。
[生态迁移台账](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/MIGRATION.md) · [开发流程](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/DEVELOPMENT.md)
+13
View File
@@ -0,0 +1,13 @@
---
import:
utf8: "./text/utf8.mq.md"
---
# @exec text
## utf8编码
`params(文本, 内存, 基址)`
把 Unicode 标量序列按 UTF-8 写入 Memory,返回字节长度。
`return utf8.编码(文本, 内存, 基址)`
+258
View File
@@ -0,0 +1,258 @@
# @exec utf8
## 成功
`params(值)`
`return {ok: true, value: 值}`
## 失败
`params(代码, 消息)`
`return {ok: false, code: 代码, message: 消息}`
## 续字节
`params(字节)`
`return 字节 >= 128 and 字节 < 192`
## 编码
`params(文本, 内存, 基址)`
把 Unicode 标量序列按 UTF-8 写入 Memory,返回字节长度。
这是 .mq.md 自己实现的编码逻辑,不是 Rust 内建 UTF-8 转换。
**点 = text.codepoints(文本)**
**下标 = 0**
**偏移 = 0**
`while 下标 < 长度(点)`
**码点 = 点[下标]**
`if 码点 < 128`
**`内存[基址 + 偏移] = 码点`**
**偏移 = 偏移 + 1**
`else`
`if 码点 < 2048`
**`内存[基址 + 偏移] = 192 + 码点 // 64`**
**`内存[基址 + 偏移 + 1] = 128 + 码点 % 64`**
**偏移 = 偏移 + 2**
`else`
`if 码点 < 65536`
**`内存[基址 + 偏移] = 224 + 码点 // 4096`**
**`内存[基址 + 偏移 + 1] = 128 + 码点 // 64 % 64`**
**`内存[基址 + 偏移 + 2] = 128 + 码点 % 64`**
**偏移 = 偏移 + 3**
`else`
`if true`
**`内存[基址 + 偏移] = 240 + 码点 // 262144`**
**`内存[基址 + 偏移 + 1] = 128 + 码点 // 4096 % 64`**
**`内存[基址 + 偏移 + 2] = 128 + 码点 // 64 % 64`**
**`内存[基址 + 偏移 + 3] = 128 + 码点 % 64`**
**偏移 = 偏移 + 4**
`end`
`end`
`end`
`end`
**下标 = 下标 + 1**
`end`
`return 偏移`
## 解码2
`params(内存, 基址, 长度, 偏移, 文本)`
`if 偏移 + 1 >= 长度`
`return [文本, 偏移, "utf8.truncated"]`
`end`
**b1 = 内存[基址 + 偏移 + 1]**
`if not 续字节(b1)`
`return [文本, 偏移, "utf8.invalid_continuation"]`
`end`
**码点 = (内存[基址 + 偏移] - 192) * 64 + (b1 - 128)**
`if 码点 < 128`
`return [文本, 偏移, "utf8.invalid_scalar"]`
`end`
`return [文本 + text.from_codepoint(码点), 偏移 + 2, ""]`
## 解码3
`params(内存, 基址, 长度, 偏移, 文本)`
`if 偏移 + 2 >= 长度`
`return [文本, 偏移, "utf8.truncated"]`
`end`
**b1 = 内存[基址 + 偏移 + 1]**
**b2 = 内存[基址 + 偏移 + 2]**
`if not (续字节(b1) and 续字节(b2))`
`return [文本, 偏移, "utf8.invalid_continuation"]`
`end`
**码点 = (内存[基址 + 偏移] - 224) * 4096 + (b1 - 128) * 64 + (b2 - 128)**
`if 码点 < 2048 or (码点 >= 55296 and 码点 <= 57343)`
`return [文本, 偏移, "utf8.invalid_scalar"]`
`end`
`return [文本 + text.from_codepoint(码点), 偏移 + 3, ""]`
## 解码4
`params(内存, 基址, 长度, 偏移, 文本)`
`if 偏移 + 3 >= 长度`
`return [文本, 偏移, "utf8.truncated"]`
`end`
**b1 = 内存[基址 + 偏移 + 1]**
**b2 = 内存[基址 + 偏移 + 2]**
**b3 = 内存[基址 + 偏移 + 3]**
`if not (续字节(b1) and 续字节(b2) and 续字节(b3))`
`return [文本, 偏移, "utf8.invalid_continuation"]`
`end`
**码点 = (内存[基址 + 偏移] - 240) * 262144 + (b1 - 128) * 4096 + (b2 - 128) * 64 + (b3 - 128)**
`if 码点 < 65536 or 码点 > 1114111`
`return [文本, 偏移, "utf8.invalid_scalar"]`
`end`
`return [文本 + text.from_codepoint(码点), 偏移 + 4, ""]`
## 解码
`params(内存, 基址, 长度)`
**偏移 = 0**
**文本 = ""**
**错误 = ""**
`while 偏移 < 长度 and 错误 == ""`
**首 = 内存[基址 + 偏移]**
`if 首 < 128`
**文本 = 文本 + text.from_codepoint(首)**
**偏移 = 偏移 + 1**
`else`
`if 首 < 194`
**错误 = "utf8.invalid_lead"**
`else`
`if 首 < 224`
**结果 = 解码2(内存, 基址, 长度, 偏移, 文本)**
**文本 = 结果[0]**
**偏移 = 结果[1]**
**错误 = 结果[2]**
`else`
`if 首 < 240`
**结果 = 解码3(内存, 基址, 长度, 偏移, 文本)**
**文本 = 结果[0]**
**偏移 = 结果[1]**
**错误 = 结果[2]**
`else`
`if 首 < 245`
**结果 = 解码4(内存, 基址, 长度, 偏移, 文本)**
**文本 = 结果[0]**
**偏移 = 结果[1]**
**错误 = 结果[2]**
`else`
`if true`
**错误 = "utf8.invalid_lead"**
`end`
`end`
`end`
`end`
`end`
`end`
`end`
`if 错误 == ""`
`return 成功(文本)`
`else`
`if true`
`return 失败(错误, "UTF-8 解码失败")`
`end`
`end`
## utf8编码
`params(文本, 内存, 基址)`
`return 编码(文本, 内存, 基址)`
## utf8解码
`params(内存, 基址, 长度)`
`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` 是从迁移前 CLI 官方标准库自测迁入的真实测试源;`tests/cases/*.json` 固定每个测试的输入(stdin、CLI 参数、环境、所需 Bundle 模块)和期望结果(observation 终值、stdout、必要的资源事件)。
运行入口是 `scripts/test.sh`,它要求显式传入 `MARQDO_BIN` 与 `MARQDO_STDLIB_DIR`。缺少制品、Bundle 缺少模块或 digest 校验失败时必须失败,不得回退到其它目录。
期望值取自迁移前基线 CLI 的真实执行结果;任何期望值改动都必须作为公开行为变化单独评审并记录证据。
+28
View File
@@ -0,0 +1,28 @@
{
"schema": "marqdo.stdlib-test-case",
"schema_version": 1,
"name": "text",
"file": "text.mq.md",
"require_module": "text.mq.md",
"args": [],
"stdin": "",
"env": {},
"expected_stdout": "",
"expected_terminal": {
"items": [
{
"decimal": "2",
"type": "int"
},
{
"decimal": "195",
"type": "int"
},
{
"decimal": "169",
"type": "int"
}
],
"type": "list"
}
}
+28
View File
@@ -0,0 +1,28 @@
{
"schema": "marqdo.stdlib-test-case",
"schema_version": 1,
"name": "utf8",
"file": "utf8.mq.md",
"require_module": "text/utf8.mq.md",
"args": [],
"stdin": "",
"env": {},
"expected_stdout": "",
"expected_terminal": {
"items": [
{
"decimal": "2",
"type": "int"
},
{
"type": "text",
"value": "é"
},
{
"type": "bool",
"value": false
}
],
"type": "list"
}
}
+14
View File
@@ -0,0 +1,14 @@
---
import:
text_lib: "std:text"
---
# @exec text
## main
**内存 = memory.new(1, 1)**
**长度 = text_lib.utf8编码("é", 内存, 0)**
`return [长度, 内存[0], 内存[1]]`
+14
View File
@@ -0,0 +1,14 @@
---
import:
utf8: "std:text/utf8"
---
# @exec utf8
## main
**内存 = memory.new(1, 1)**
**长度 = utf8.编码("é", 内存, 0)**
`return [长度, utf8.解码(内存, 0, 长度).value, utf8.解码(内存, 0, 1).ok]`