migrate: publish the regex domain module as an explicit package #2

Merged
cflmy merged 1 commits from migration/ext-regex into main 2026-11-27 00:09:00 +08:00
8 changed files with 871 additions and 6 deletions

No files matched your search

+35 -5
View File
@@ -1,14 +1,44 @@
# marqdo-ext-regex
本仓负责正则匹配、捕获、扫描和替换。当前状态为 `planned`。
本仓负责正则匹配、捕获、扫描与替换(显式 Package)。当前处于**标准库源码归位迁移**阶段:领域模块已迁入本仓作为显式 Package,等待父仓候选组合验收(父仓工单 [marqdo#9](https://git.cflmy.cn/cflmy/marqdo/issues/9),本仓工单 [#1](https://git.cflmy.cn/cflmy/marqdo-ext-regex/issues/1))。
## 首项任务
## 现行形态:显式 Package,不进入默认 Bundle
提供匹配、捕获、扫描与替换,为 CLI 移除旧正则入口提供可验证的替代。
- 入口:`index.mq.md`(`marqdo.yaml` 声明 package)。
- 消费者声明依赖并用公开 `@alias` 导入:
```yaml
# consumer/marqdo.yaml
dependencies:
regex:
git: https://git.cflmy.cn/cflmy/marqdo-ext-regex
rev: <精确提交>
```
```markdown
---
import:
regex: "@regex"
---
## @exec main
`return regex.<函数>(...)`
```
- 不再以 `std:regex` 提供,不保留隐藏 fallback;默认标准库 Bundle 不包含本模块。
- 测试:`scripts/test.sh` 只接受 `MARQDO_BIN` + `MARQDO_STDLIB_DIR`,用临时消费者工程经 `marqdo lock` 与 `@alias` 公开导入执行。
`index.mq.md`:原 `regex.mq.md` 的纯 Marqdo 子集与宿主薄包装函数,公开为 Package 入口(消费者通过 `@regex` 导入)
## 边界
不进入默认 Bundle,不提供 `std:regex`;不新增第三个正则引擎,CLI 既有 `regex.match`/`regex.captures` 宿主请求保留;如实记录纯子集与宿主路径的语义差异。
## 目录
- [modules/](modules/README.md) 存放对外发布的模块源码。
- [tests/](tests/README.md) 存放独立验收用的输入和断言。
- `index.mq.md`:Package 入口与唯一公开入口。
- `tests/`:迁入的领域测试源与期望。
- `scripts/`:独立验收入口。
[生态迁移台账](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/MIGRATION.md) · [开发流程](https://git.cflmy.cn/cflmy/marqdo/src/branch/main/docs/DEVELOPMENT.md)
+541
View File
@@ -0,0 +1,541 @@
# @exec regex
## 成功
`params(值)`
`return {ok: true, value: 值}`
## 失败
`params(代码, 消息)`
`return {ok: false, code: 代码, message: 消息}`
## 包含
`params(列表, 值)`
**结果 = false**
**下标 = 0**
`while 下标 < 长度(列表) and not 结果`
`if 列表[下标] == 值`
**结果 = true**
`else`
`if true`
**忽略 = 0**
`end`
`end`
**下标 = 下标 + 1**
`end`
`return 结果`
## 去头
`params(列表)`
**结果 = []**
**下标 = 1**
`while 下标 < 长度(列表)`
**结果 = list.append(结果, 列表[下标])**
**下标 = 下标 + 1**
`end`
`return 结果`
## 设置最后
`params(列表, 值)`
**结果 = []**
**下标 = 0**
`while 下标 < 长度(列表)`
`if 下标 + 1 == 长度(列表)`
**结果 = list.append(结果, 值)**
`else`
`if true`
**结果 = list.append(结果, 列表[下标])**
`end`
`end`
**下标 = 下标 + 1**
`end`
`return 结果`
## 片段
`params(点, 起点, 终点)`
**结果 = ""**
**下标 = 起点**
`while 下标 < 终点`
**结果 = 结果 + text.from_codepoint(点[下标])**
**下标 = 下标 + 1**
`end`
`return 结果`
## 是数字
`params(码点)`
`return 码点 >= 48 and 码点 <= 57`
## 字面令牌
`params(码点)`
包含数量词,默认恰好一次。
`return {kind: "literal", value: 码点, neg: false, min: 1, max: 1}`
## 任意令牌
`params()`
`return {kind: "any", value: 0, neg: false, min: 1, max: 1}`
## 类令牌
`params(集合, 否定)`
`return {kind: "class", value: 集合, neg: 否定, min: 1, max: 1}`
## 锚点令牌
`params(方向)`
`return {kind: "anchor", value: 方向, neg: false, min: 1, max: 1}`
## 设置量词
`params(令牌, 码点)`
`if 码点 == 42`
`return {kind: 令牌.kind, value: 令牌.value, neg: 令牌.neg, min: 0, max: -1}`
`else`
`if 码点 == 43`
`return {kind: 令牌.kind, value: 令牌.value, neg: 令牌.neg, min: 1, max: -1}`
`end`
`end`
`return {kind: 令牌.kind, value: 令牌.value, neg: 令牌.neg, min: 0, max: 1}`
## 编译类
`params(点, 位置)`
**当前 = 位置 + 1**
**否定 = false**
`if 当前 < 长度(点) and 点[当前] == 94`
**否定 = true**
**当前 = 当前 + 1**
`else`
`if true`
**忽略否定 = 0**
`end`
`end`
**集合 = []**
**完成 = false**
**错误 = ""**
`while 当前 < 长度(点) and not 完成 and 错误 == ""`
**码点 = 点[当前]**
`if 码点 == 93`
**完成 = true**
**当前 = 当前 + 1**
`else`
`if 码点 == 92`
`if 当前 + 1 >= 长度(点)`
**错误 = "regex.invalid"**
`else`
`if true`
**集合 = list.append(集合, 点[当前 + 1])**
**当前 = 当前 + 2**
`end`
`end`
`else`
`if 当前 + 2 < 长度(点) and 点[当前 + 1] == 45 and 点[当前 + 2] != 93`
**开始 = 码点**
**结束 = 点[当前 + 2]**
`if 开始 > 结束`
**错误 = "regex.invalid"**
`else`
`if true`
**值 = 开始**
`while 值 <= 结束`
**集合 = list.append(集合, 值)**
**值 = 值 + 1**
`end`
**当前 = 当前 + 3**
`end`
`end`
`else`
`if true`
**集合 = list.append(集合, 码点)**
**当前 = 当前 + 1**
`end`
`end`
`end`
`end`
`end`
`if not 完成`
`return 失败("regex.invalid", "字符类未闭合")`
`else`
`if 错误 != ""`
`return 失败(错误, "字符类范围无效")`
`end`
`end`
`return 成功({set: 集合, neg: 否定, next: 当前})`
## 编译
`params(点, 位置)`
**令牌表 = []**
**当前 = 位置**
**错误 = ""**
**代码 = ""**
`while 当前 < 长度(点) and 错误 == ""`
**码点 = 点[当前]**
`if 码点 == 94`
**令牌表 = list.append(令牌表, 锚点令牌("start"))**
**当前 = 当前 + 1**
`else`
`if 码点 == 36`
**令牌表 = list.append(令牌表, 锚点令牌("end"))**
**当前 = 当前 + 1**
`else`
`if 码点 == 91`
**类结果 = 编译类(点, 当前)**
`if not 类结果.ok`
**错误 = 类结果.code**
**代码 = 类结果.message**
`else`
`if true`
**令牌表 = list.append(令牌表, 类令牌(类结果.value.set, 类结果.value.neg))**
**当前 = 类结果.value.next**
`end`
`end`
`else`
`if 码点 == 92`
`if 当前 + 1 >= 长度(点)`
**错误 = "regex.invalid"**
**代码 = "转义缺少字符"**
`else`
`if true`
**令牌表 = list.append(令牌表, 字面令牌(点[当前 + 1]))**
**当前 = 当前 + 2**
`end`
`end`
`else`
`if 码点 == 46`
**令牌表 = list.append(令牌表, 任意令牌())**
**当前 = 当前 + 1**
`else`
`if 码点 == 40 or 码点 == 41 or 码点 == 124`
**错误 = "regex.unsupported"**
**代码 = "不支持分组或选择"**
`else`
`if 码点 == 42 or 码点 == 43 or 码点 == 63`
**错误 = "regex.invalid"**
**代码 = "量词没有前一项"**
`else`
`if true`
**令牌表 = list.append(令牌表, 字面令牌(码点))**
**当前 = 当前 + 1**
`end`
`end`
`end`
`end`
`end`
`end`
`end`
`end`
`while 错误 == "" and 当前 < 长度(点) and (点[当前] == 42 or 点[当前] == 43 or 点[当前] == 63)`
**令牌表 = 设置最后(令牌表, 设置量词(令牌表[长度(令牌表) - 1], 点[当前]))**
**当前 = 当前 + 1**
`while 当前 < 长度(点) and (点[当前] == 42 or 点[当前] == 43 or 点[当前] == 63)`
**错误 = "regex.invalid"**
**代码 = "连续量词无效"**
`end`
`end`
`end`
`if 错误 != ""`
`return 失败(错误, 代码)`
`end`
`return 成功(令牌表)`
## 单字符匹配
`params(令牌, 码点)`
**类别 = 令牌.kind**
`if 类别 == "any"`
`return true`
`else`
`if 类别 == "literal"`
`return 令牌.value == 码点`
`else`
`if 类别 == "class"`
`return 包含(令牌.value, 码点) != 令牌.neg`
`end`
`end`
`end`
`return false`
## 尝试匹配
`params(令牌, 下标, 当前, 点, 位置, 次数, 要求结束)`
**下限 = 当前.min**
**上限 = 当前.max**
`if 次数 >= 下限 and 匹配序列(令牌, 下标 + 1, 点, 位置, 要求结束)`
`return true`
`else`
`if 上限 >= 0 and 次数 >= 上限`
`return false`
`else`
`if 位置 < 长度(点) and 单字符匹配(当前, 点[位置])`
`return 尝试匹配(令牌, 下标, 当前, 点, 位置 + 1, 次数 + 1, 要求结束)`
`end`
`end`
`end`
`return false`
## 匹配序列
`params(令牌, 下标, 点, 位置, 要求结束)`
`if 下标 >= 长度(令牌)`
`if 要求结束`
`return 位置 == 长度(点)`
`end`
`return true`
`end`
**当前 = 令牌[下标]**
`if 当前.kind == "anchor"`
`if 当前.value == "start" and 位置 == 0`
`return 匹配序列(令牌, 下标 + 1, 点, 位置, 要求结束)`
`else`
`if 当前.value == "end" and 位置 == 长度(点)`
`return 匹配序列(令牌, 下标 + 1, 点, 位置, 要求结束)`
`end`
`end`
`return false`
`end`
`return 尝试匹配(令牌, 下标, 当前, 点, 位置, 0, 要求结束)`
## 匹配
`params(模式, 文本)`
编译后要求整个文本匹配。支持 ^、$、.、*、+、?、
[...] 和 \\ 转义;不支持分组和选择。
**编译结果 = 编译(text.codepoints(模式), 0)**
`if not 编译结果.ok`
`return 编译结果`
`end`
`return {ok: true, value: 匹配序列(编译结果.value, 0, text.codepoints(文本), 0, true)}`
## 搜索
`params(模式, 文本)`
**编译结果 = 编译(text.codepoints(模式), 0)**
`if not 编译结果.ok`
`return 编译结果`
`end`
**令牌 = 编译结果.value**
**点 = text.codepoints(文本)**
**下标 = 0**
**结果 = false**
`while 下标 <= 长度(点) and not 结果`
`if 匹配序列(令牌, 0, 点, 下标, false)`
**结果 = true**
`else`
`if true`
**忽略 = 0**
`end`
`end`
**下标 = 下标 + 1**
`end`
`return 成功(结果)`
## 扩展匹配
`params(模式, 文本)`
使用宿主正则引擎(支持分组、选择、\\d 等)判断是否匹配。模式无效时
返回 regex.invalid。仅项目模式;纯 .mq.md 子集仍由 匹配/搜索 提供。
`return resource.request("regex.match", [模式, 文本])`
## 扩展搜索
`params(模式, 文本)`
`return resource.request("regex.match", [模式, 文本])`
## 捕获
`params(模式, 文本)`
返回 {ok:true, value:{matched:Bool, groups:List<Text|None>}}。下标 0 是
完整匹配;未参与匹配的分组是 None。
`return resource.request("regex.captures", [模式, 文本])`
+5
View File
@@ -0,0 +1,5 @@
project:
name: marqdo-ext-regex
version: 0.1.0
marqdo: ">=3.0.0-beta.1,<4.0.0"
dependencies: {}
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env python3
"""Run an explicit-package extension repository's tests with real CLI inputs.
Each case builds a throwaway consumer project whose `dependencies.<alias>` path
points at a copy of this repository's package (`marqdo.yaml` + `index.mq.md`),
runs `marqdo lock` once, then executes the migrated `.mq.md` test through the
public `@alias` import. Inputs are explicit: `MARQDO_BIN` (verified CLI) and
`MARQDO_STDLIB_DIR` (installed Bundle for the remaining `std:` imports, if any).
Nothing reads a sibling repository or a floating branch.
"""
from __future__ import annotations
import base64
import json
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
CASES = REPO / "tests" / "cases"
SCHEMA = "marqdo.package-test-case"
SCHEMA_VERSION = 1
class CaseError(Exception):
pass
def substitute(value, binary: str, package_root: Path):
if isinstance(value, dict):
if set(value) == {"$bin_version"}:
return subprocess.run([binary, "--version"], capture_output=True, text=True).stdout
if set(value) == {"$package_root"}:
return str(package_root)
return {k: substitute(v, binary, package_root) for k, v in value.items()}
if isinstance(value, list):
return [substitute(v, binary, package_root) for v in value]
return value
def channel_text(events, channel):
parts = []
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 mismatch")
parts.append(data)
return b"".join(parts).decode()
def consumer_manifest(alias: str) -> str:
return (
"project:\n"
" name: package-test-consumer\n"
" version: 0.0.0\n"
' marqdo: ">=3.0.0-beta.1,<4.0.0"\n'
"dependencies:\n"
f" {alias}:\n"
f" path: ./deps/{alias}\n"
)
def run_case(case: dict, binary: str, bundle: Path) -> None:
name = case["name"]
alias = case["dep_alias"]
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)
source = REPO / "tests" / case["file"]
if not source.is_file():
raise CaseError(f"{name}: missing test source {source}")
with tempfile.TemporaryDirectory(prefix="mq-package-test-") as tmp:
consumer = Path(tmp) / "consumer"
package = consumer / "deps" / alias
package.mkdir(parents=True)
shutil.copy2(REPO / "marqdo.yaml", package / "marqdo.yaml")
shutil.copy2(REPO / "index.mq.md", package / "index.mq.md")
(consumer / "marqdo.yaml").write_text(consumer_manifest(alias))
(consumer / "tests").mkdir()
shutil.copy2(source, consumer / "tests" / case["file"])
lock = subprocess.run([binary, "lock"], cwd=consumer, env=env, capture_output=True)
if lock.returncode != 0:
raise CaseError(f"{name}: marqdo lock failed: {lock.stderr.decode(errors='replace')}")
args = [str(arg).replace("$MARQDO_BIN", binary) for arg in case.get("args", [])]
result = subprocess.run(
[binary, "run", str(consumer / "tests" / case["file"]), *args, "--output", "json"],
cwd=consumer, env=env, input=case.get("stdin", "").encode(), capture_output=True,
)
if result.returncode != 0:
raise CaseError(f"{name}: CLI exited {result.returncode}:\n{result.stderr.decode(errors='replace')}")
report = json.loads(result.stdout)
if report.get("run", {}).get("status") != "ok":
raise CaseError(f"{name}: run status not ok")
terminal = report["events"][-1]["payload"]
if terminal.get("status") != "ok":
raise CaseError(f"{name}: terminal status not ok")
expected = substitute(case["expected_terminal"], binary, REPO)
if terminal.get("value") != expected:
raise CaseError(
f"{name}: terminal value changed\nexpected: "
f"{json.dumps(expected, ensure_ascii=False, sort_keys=True)}\nactual: "
f"{json.dumps(terminal.get('value'), ensure_ascii=False, sort_keys=True)}"
)
stdout = channel_text(report["events"], "stdout.chunk")
if stdout != case.get("expected_stdout", ""):
raise CaseError(f"{name}: stdout changed: {stdout!r}")
def main() -> int:
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", file=sys.stderr)
return 2
failures = 0
ran = 0
for path in paths:
case = json.loads(path.read_text())
if case.get("schema") != SCHEMA or case.get("schema_version") != SCHEMA_VERSION:
print(f"FAIL {path.name}: unsupported schema", file=sys.stderr)
failures += 1
continue
ran += 1
try:
run_case(case, binary, bundle)
print(f"PASS {case['name']}")
except (CaseError, json.JSONDecodeError) 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 the installed Bundle that
# still provides the std: dependencies (if any). Never reads 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 官方标准库自测迁入的真实测试源,导入已改为公开 Package 别名(`@alias`);`tests/cases/*.json` 固定输入(stdin、CLI 参数、环境、依赖别名)与期望结果(observation 终值、stdout)。
运行入口是 `scripts/test.sh`,要求显式传入 `MARQDO_BIN` 与 `MARQDO_STDLIB_DIR`。运行器为每个 case 建立临时消费者工程(`dependencies.<alias>.path` 指向本仓 Package 副本),先 `marqdo lock` 再通过公开 `@alias` 导入执行,不读取兄弟仓路径或浮动分支。
期望值取自迁移前基线 Bundle 的真实执行结果;修改期望值等于声明公开行为变化,必须单独评审。
+89
View File
@@ -0,0 +1,89 @@
{
"schema": "marqdo.package-test-case",
"schema_version": 1,
"name": "regex",
"file": "regex.mq.md",
"dep_alias": "regex",
"args": [],
"stdin": "",
"env": {},
"expected_stdout": "",
"expected_terminal": {
"items": [
{
"type": "bool",
"value": true
},
{
"type": "bool",
"value": false
},
{
"type": "bool",
"value": true
},
{
"type": "bool",
"value": true
},
{
"type": "bool",
"value": true
},
{
"type": "bool",
"value": true
},
{
"type": "bool",
"value": true
},
{
"type": "bool",
"value": true
},
{
"type": "bool",
"value": true
},
{
"type": "bool",
"value": false
},
{
"type": "text",
"value": "regex.invalid"
},
{
"type": "text",
"value": "regex.unsupported"
},
{
"type": "bool",
"value": true
},
{
"type": "bool",
"value": true
},
{
"items": [
{
"type": "text",
"value": "aab"
},
{
"type": "text",
"value": "aa"
},
{
"type": "text",
"value": "b"
}
],
"type": "list"
}
],
"type": "list"
}
}
+36
View File
@@ -0,0 +1,36 @@
---
import:
regex: "@regex"
---
# @exec regex
## main
**`星号 = regex.匹配("a*b", "aaab")`**
**`加号 = regex.匹配("a+b", "b")`**
**`锚点 = regex.匹配("^a.*z$", "abcz")`**
**`类 = regex.匹配("[a-c]+", "abc")`**
**`否定类 = regex.匹配("[^0-9]", "a")`**
**`任意 = regex.匹配("a.a", "aba")`**
**`可选 = regex.匹配("a?b", "b")`**
**`转义 = regex.匹配("\\.", ".")`**
**`搜索 = regex.搜索("b+c", "xxbbcyy")`**
**`无效 = regex.匹配("[a", "a")`**
**`不支持 = regex.匹配("(a)", "a")`**
**扩展 = regex.扩展匹配("^(a+)(b|c)$", "aab")**
**捕获 = regex.捕获("^(a+)(b|c)$", "aab")**
`return [星号.value, 加号.value, 锚点.value, 类.value, 否定类.value, 任意.value, 可选.value, 转义.value, 搜索.value, 无效.ok, 无效.code, 不支持.code, 扩展.value, 捕获.value.matched, 捕获.value.groups]`