feat(stdlib): Mid M1 regex and encoding libraries
Add lib/re and lib/encoding (EN/ZH) backed by host_re_* and host_encoding_*, with golds, public demos, and design docs. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
1a5ee57a6f
commit
838a2b425a
26 files changed
+702
-13
No files matched your search
@@ -149,6 +149,22 @@ import text:lib/text.mq.md
|
||||
> print text=`parts`
|
||||
```
|
||||
|
||||
## 7b. Mid M1 — regex + encoding (no plugin)
|
||||
|
||||
```markdown
|
||||
---
|
||||
import re:lib/re.mq.md
|
||||
import enc:lib/encoding.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*`ok` = > re.is_match text="a@b.c" pattern="@"*
|
||||
*`b64` = > enc.base64_encode text="hi"*
|
||||
> print text=`ok`
|
||||
> print text=`b64`
|
||||
```
|
||||
|
||||
## 8. Comment paragraphs (blank-line rule)
|
||||
|
||||
```markdown
|
||||
|
||||
+2
-1
@@ -3,7 +3,8 @@
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
- **中层标准库(规划)**:通用原语沉 `lib/`(re / encoding / path / hash / csv …),减少「事事 ABI 插件」。设计 [stdlib-mid.md](doc/design/stdlib-mid.md) · 路线 [stdlib-mid.md](doc/roadmap/stdlib-mid.md)。
|
||||
- **中层标准库 M1**:`lib/re` / `lib/正则`(`is_match`/`find`/`find_all`/`replace`/`split`)与 `lib/encoding` / `lib/编码`(base64/hex);host `host_re_*` + `host_encoding_*`;金样与 public `08-re-encoding`。设计 [stdlib-mid.md](doc/design/stdlib-mid.md) · [stdlib-re.md](doc/design/stdlib-re.md) · [stdlib-encoding.md](doc/design/stdlib-encoding.md)。
|
||||
- **中层标准库(规划)**:通用原语沉 `lib/`(path / hash / csv …),减少「事事 ABI 插件」。路线 [stdlib-mid.md](doc/roadmap/stdlib-mid.md)。
|
||||
- **`ext/linalg`**:L0–L6 + 公式文档面 **F1–F3**(中缀、`declare`、展示/`explicit` 默认化简、`T_ascii`、public「如何写公式文档」);示例 `linalg-transpose` · `linalg-svd` · `linalg-least-squares`。设计:[ext-linalg-formula-doc.md](doc/design/ext-linalg-formula-doc.md)。
|
||||
|
||||
### Fixed
|
||||
|
||||
Generated
+1
@@ -1037,6 +1037,7 @@ dependencies = [
|
||||
"libloading",
|
||||
"predicates",
|
||||
"pulldown-cmark",
|
||||
"regex",
|
||||
"serde_json",
|
||||
"thiserror 1.0.69",
|
||||
"tiny_http",
|
||||
|
||||
@@ -32,6 +32,8 @@ pulldown-cmark = "0.12"
|
||||
serde_json = "1"
|
||||
thiserror = "1"
|
||||
tiny_http = { version = "0.12", optional = true }
|
||||
# Mid M1: Unicode regex for lib/re (no backrefs; RE2-like).
|
||||
regex = { version = "=1.13.1", default-features = false, features = ["std", "unicode"] }
|
||||
# Pin for Cargo/rustc 1.81 (newer rustls/idna/zeroize need edition2024).
|
||||
ureq = { version = "=2.9.7", default-features = false, features = ["tls", "gzip"], optional = true }
|
||||
idna_adapter = { version = "=1.1.0", optional = true }
|
||||
|
||||
@@ -82,6 +82,7 @@ Marqdo 换 **Rust 或 C++** 都不改变「主前端不该是 Flex/Bison」这
|
||||
| **clap** | CLI | `marqdo run [path]` |
|
||||
| **serde** + **serde_yaml** | 元信息 | 仅解析 frontmatter 中的 YAML **键值**;`import x:x.mq.md` 仍按**行**抽取(见 Spike) |
|
||||
| **ureq** (=2.9.7) | HTTP(S) | `lib/net`;为 Cargo 1.81 另钉 `idna_adapter`/`zeroize`(见根 `Cargo.toml`) |
|
||||
| **regex** (=1.13.1) | 正则 | Mid M1 `lib/re`;`default-features=false` + `std`/`unicode`;无回溯引用 |
|
||||
|
||||
#### 强烈建议
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# `lib/encoding` — 编解码(Mid M1)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **已落地(M1)** |
|
||||
| 日期 | 2026-09-07 |
|
||||
| 相关 | [stdlib-mid.md](stdlib-mid.md) · [stdlib-re.md](stdlib-re.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) |
|
||||
| 导入 | `lib/encoding.mq.md` · `lib/编码.mq.md` |
|
||||
| Host | `host_encoding_*`(无第三方 crate:标准 Base64 / hex) |
|
||||
|
||||
---
|
||||
|
||||
## 1. API
|
||||
|
||||
| 英文 | 中文 | 形参 | 结果 |
|
||||
|------|------|------|------|
|
||||
| `base64_encode` | `基64编码` | `text` | 文本(UTF-8 字节 → 标准 Base64,含 `=` 填充) |
|
||||
| `base64_decode` | `基64解码` | `text` | 文本(解码后须为合法 UTF-8) |
|
||||
| `hex_encode` | `十六进制编码` | `text` | 小写 hex |
|
||||
| `hex_decode` | `十六进制解码` | `text` | 文本(偶数字节;合法 UTF-8) |
|
||||
|
||||
## 2. 与 `net.url_encode` 的边界
|
||||
|
||||
| 能力 | 归属 |
|
||||
|------|------|
|
||||
| `application/x-www-form-urlencoded` 风格 | `net.url_encode` |
|
||||
| Base64 / hex | **本库** |
|
||||
| 百分号编解码通用版 | 可日后加 `encoding.percent_*`;本波不做 |
|
||||
|
||||
## 3. 刻意不做(v1)
|
||||
|
||||
URL-safe Base64 变体开关、忽略空白的宽松解码、二进制 `bytes` 类型(仍经 UTF-8 文本往返)。
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **规划中(设计定稿 · 实现未开)** |
|
||||
| 状态 | **规划中 · M1(re + encoding)已实现** |
|
||||
| 日期 | 2026-09-07 |
|
||||
| 相关 | [stdlib.md](stdlib.md) · [stdlib-modules.md](stdlib-modules.md) · [ext-abi.md](ext-abi.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) |
|
||||
| 目标 | 在接下来数个发版周期内,把「通用编程」能力沉到 **L0.5 宿主 + L1 `.mq.md`**,减少「凡是稍有能力就必须 ABI 插件」的路径依赖 |
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **核心已落地**;**中层 Mid 见** [stdlib-mid.md](stdlib-mid.md) / [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) |
|
||||
| 状态 | **核心已落地**;**中层 Mid:M1(re/encoding)已落地** · [stdlib-mid.md](stdlib-mid.md) / [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) |
|
||||
| 日期 | 2026-09-07 |
|
||||
| 原则 | 全部经 frontmatter **导入**;除 JSON 外中英分文件;内核保持少而精;**通用能力优先 Mid,插件留给领域核** |
|
||||
| 相关 | [stdlib.md](stdlib.md) · [stdlib-i18n.md](stdlib-i18n.md) · [stdlib-mid.md](stdlib-mid.md) · [ext-abi.md](ext-abi.md) · [ext-llm.md](ext-llm.md) · [ext-agent.md](ext-agent.md) · [**module-namespace.md**](module-namespace.md)(导入命名空间;**M1/M2 已落地**:`库.成员` / `库.对象.成员` / `use`) |
|
||||
@@ -16,6 +16,8 @@
|
||||
| 模块族 | 英文库 | 中文库 | 状态 |
|
||||
|--------|--------|--------|------|
|
||||
| 文本 | `lib/text.mq.md` | `lib/文本.mq.md` | 已有 |
|
||||
| **正则** | `lib/re.mq.md` | `lib/正则.mq.md` | **Mid M1** |
|
||||
| **编解码** | `lib/encoding.mq.md` | `lib/编码.mq.md` | **Mid M1** |
|
||||
| 表 | `lib/table.mq.md` | `lib/表.mq.md` | 已有(`put`/`改` + list/map;见 [stdlib-table.md](stdlib-table.md)) |
|
||||
| 浏览器效应 | `lib/browser.mq.md` | `lib/浏览器.mq.md` | WASM 客户端效应助手(GFM + helpers;勿用 `json.set` 链) |
|
||||
| 文件 | `lib/fs.mq.md` | `lib/文件.mq.md` | 已有 |
|
||||
@@ -31,7 +33,7 @@
|
||||
|
||||
官方可选扩展(**非** stdlib):`ext/llm` · `ext/agent` · `ext/web` · `ext/quantum` · `ext/linalg` — 见各 `ext-*.md`。
|
||||
|
||||
**中层下一波候选(未落地):** `re` / `encoding` / `path` / `hash` / `secrets` / `csv` / … — 准入与波次见 [stdlib-mid.md](stdlib-mid.md)。
|
||||
**中层下一波候选(未落地):** `path` / `hash` / `secrets` / `csv` / … — 见 [stdlib-mid.md](stdlib-mid.md)。**M1 已落地:** `re` / `encoding`。
|
||||
|
||||
设计细节:[stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md)。
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# `lib/re` — 正则(Mid M1)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **已落地(M1)** |
|
||||
| 日期 | 2026-09-07 |
|
||||
| 相关 | [stdlib-mid.md](stdlib-mid.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) |
|
||||
| 导入 | `lib/re.mq.md` · `lib/正则.mq.md` |
|
||||
| Host | `host_re_*`(`regex` crate,默认 Unicode) |
|
||||
|
||||
---
|
||||
|
||||
## 1. API
|
||||
|
||||
| 英文 | 中文 | 形参 | 结果 |
|
||||
|------|------|------|------|
|
||||
| `is_match` | `匹配` | `text`, `pattern` | 布尔 |
|
||||
| `find` | `查找` | `text`, `pattern` | 首个匹配文本,或 `None` |
|
||||
| `find_all` | `查找全部` | `text`, `pattern` | 文本列表 |
|
||||
| `replace` | `替换` | `text`, `pattern`, `with`, 可选 `count` | 文本(`count` 缺省 = 全部) |
|
||||
| `split` | `拆分` | `text`, `pattern` | 文本列表 |
|
||||
|
||||
非法 pattern → 诊断失败(含 crate 错误信息)。
|
||||
|
||||
## 2. 语义
|
||||
|
||||
- 引擎:Rust [`regex`](https://docs.rs/regex)(无回溯引用;与 RE2 同族限制)。
|
||||
- 按 **UTF-8 文本**匹配,不做字节模式。
|
||||
- `find` / `find_all` 返回整段匹配(不含捕获组拆分;捕获组 v1 不做)。
|
||||
|
||||
## 3. 刻意不做(v1)
|
||||
|
||||
命名捕获、替换回调、`Regex` 对象缓存 API、字节模式。
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **规划 · 待按波次开工** |
|
||||
| 状态 | **M1 已落地(re + encoding)· M2–M6 规划中** |
|
||||
| 日期 | 2026-09-07 |
|
||||
| 设计 | [stdlib-mid.md](../design/stdlib-mid.md) |
|
||||
| 相关 | [stdlib-modules.md](../design/stdlib-modules.md) · [next-phase.md](next-phase.md) · [ext-cli.md](../design/ext-cli.md) |
|
||||
@@ -50,16 +50,16 @@ M6 可观测与标识 log + uuid(+ 可选 yaml)
|
||||
|
||||
## 2. 波次明细
|
||||
|
||||
### M1 — 正则与编解码(最高优先)
|
||||
### M1 — 正则与编解码(最高优先) — **done**
|
||||
|
||||
| 交付 | 说明 |
|
||||
|------|------|
|
||||
| `lib/re.mq.md` / `lib/正则.mq.md` | `is_match` / `find` / `find_all` / `replace` / `split`(命名可微调,冻前写短设计) |
|
||||
| `lib/encoding.mq.md` / `lib/编码.mq.md` | `base64_encode`/`decode`、`hex_encode`/`decode`;与 `net.url_encode` 的职责表 |
|
||||
| Host | `host_re_*`(建议 `regex` crate)、`host_encoding_*` |
|
||||
| 金样 | `tests/lib/re-*.mq.md`、`encoding-*.mq.md` |
|
||||
| 文档 | `doc/design/stdlib-re.md`、`stdlib-encoding.md`;`public/features` 各一页 |
|
||||
| 验收 | 无插件下完成:邮箱/路径片段校验、配置里的 base64 往返 |
|
||||
| `lib/re.mq.md` / `lib/正则.mq.md` | `is_match` / `find` / `find_all` / `replace` / `split` |
|
||||
| `lib/encoding.mq.md` / `lib/编码.mq.md` | `base64_*` / `hex_*` |
|
||||
| Host | `host_re_*`(`regex`)、`host_encoding_*`(无第三方编解码 crate) |
|
||||
| 金样 | `tests/lib/re-smoke` · `正则-烟测` · `encoding-smoke` · `编码-烟测` |
|
||||
| 文档 | [stdlib-re.md](../design/stdlib-re.md) · [stdlib-encoding.md](../design/stdlib-encoding.md) · public `08-re-encoding` |
|
||||
| 验收 | 无插件:邮箱式校验 + base64/hex 往返 |
|
||||
|
||||
**刻意不做:** 回溯引用极致兼容、替换回调、完整 PCRE 方言文档化——先 RE2/ Rust `regex` 语义并写清。
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
title: lib/encoding
|
||||
description: Base64 and hex encode/decode (Mid M1). UTF-8 text round-trip.
|
||||
---
|
||||
|
||||
## base64_encode
|
||||
+ `text`
|
||||
|
||||
**> host_encoding_base64_encode text=`text`**
|
||||
|
||||
## base64_decode
|
||||
+ `text`
|
||||
|
||||
**> host_encoding_base64_decode text=`text`**
|
||||
|
||||
## hex_encode
|
||||
+ `text`
|
||||
|
||||
**> host_encoding_hex_encode text=`text`**
|
||||
|
||||
## hex_decode
|
||||
+ `text`
|
||||
|
||||
**> host_encoding_hex_decode text=`text`**
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: lib/re
|
||||
description: Regular expressions (Mid M1). Unicode; no backreferences.
|
||||
---
|
||||
|
||||
## is_match
|
||||
+ `text`
|
||||
+ `pattern`
|
||||
|
||||
**> host_re_is_match text=`text` pattern=`pattern`**
|
||||
|
||||
## find
|
||||
+ `text`
|
||||
+ `pattern`
|
||||
|
||||
**> host_re_find text=`text` pattern=`pattern`**
|
||||
|
||||
## find_all
|
||||
+ `text`
|
||||
+ `pattern`
|
||||
|
||||
**> host_re_find_all text=`text` pattern=`pattern`**
|
||||
|
||||
## replace
|
||||
+ `text`
|
||||
+ `pattern`
|
||||
+ `with`
|
||||
+ `count`=None
|
||||
|
||||
Optional `count=` limits replacements (`None` = all).
|
||||
|
||||
**> host_re_replace text=`text` pattern=`pattern` with=`with` count=`count`**
|
||||
|
||||
## split
|
||||
+ `text`
|
||||
+ `pattern`
|
||||
|
||||
**> host_re_split text=`text` pattern=`pattern`**
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: lib/正则
|
||||
description: 正则表达式(中层 M1)。Unicode;无回溯引用。
|
||||
---
|
||||
|
||||
## 匹配
|
||||
+ `内容`
|
||||
+ `模式`
|
||||
|
||||
**> host_re_is_match text=`内容` pattern=`模式`**
|
||||
|
||||
## 查找
|
||||
+ `内容`
|
||||
+ `模式`
|
||||
|
||||
**> host_re_find text=`内容` pattern=`模式`**
|
||||
|
||||
## 查找全部
|
||||
+ `内容`
|
||||
+ `模式`
|
||||
|
||||
**> host_re_find_all text=`内容` pattern=`模式`**
|
||||
|
||||
## 替换
|
||||
+ `内容`
|
||||
+ `模式`
|
||||
+ `为`
|
||||
+ `次数`=None
|
||||
|
||||
可选 `次数=` 限制替换次数(缺省 = 全部)。
|
||||
|
||||
**> host_re_replace text=`内容` pattern=`模式` with=`为` count=`次数`**
|
||||
|
||||
## 拆分
|
||||
+ `内容`
|
||||
+ `模式`
|
||||
|
||||
**> host_re_split text=`内容` pattern=`模式`**
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
title: lib/编码
|
||||
description: Base64 与十六进制编解码(中层 M1)。UTF-8 文本往返。
|
||||
---
|
||||
|
||||
## 基64编码
|
||||
+ `内容`
|
||||
|
||||
**> host_encoding_base64_encode text=`内容`**
|
||||
|
||||
## 基64解码
|
||||
+ `内容`
|
||||
|
||||
**> host_encoding_base64_decode text=`内容`**
|
||||
|
||||
## 十六进制编码
|
||||
+ `内容`
|
||||
|
||||
**> host_encoding_hex_encode text=`内容`**
|
||||
|
||||
## 十六进制解码
|
||||
+ `内容`
|
||||
|
||||
**> host_encoding_hex_decode text=`内容`**
|
||||
@@ -14,6 +14,8 @@
|
||||
|
||||
官方扩展(非 stdlib):`ext/llm`、`ext/agent`、`ext/web`、`ext/quantum`、`ext/linalg` — 见 `features/05-*.mq.md`、`06-*.mq.md`、`07-linalg.mq.md` / `07-线性代数.mq.md` 与 `doc/design/ext-*.md`。
|
||||
|
||||
中层标准库(Mid):`features/08-re-encoding.mq.md` / `08-正则编解码.mq.md`(`lib/re` · `lib/encoding`)。
|
||||
|
||||
**不放** `errors/`:失败样例只在 `tests/errors/`。
|
||||
|
||||
开发文档在 [`doc/`](../doc/)。
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Mid stdlib — regex and encoding
|
||||
description: lib/re + lib/encoding without plugins (Mid M1)
|
||||
import re:lib/re.mq.md
|
||||
import enc:lib/encoding.mq.md
|
||||
---
|
||||
|
||||
# Regex and encoding in lib/
|
||||
|
||||
Mid-tier stdlib: everyday primitives stay in `lib/`, not ABI plugins.
|
||||
|
||||
# main
|
||||
|
||||
*`ok` = > re.is_match text="user@example.com" pattern="^[^@]+@[^@]+$"*
|
||||
*`tok` = > enc.base64_encode text="marqdo"*
|
||||
*`hex` = > enc.hex_encode text="ok"*
|
||||
> print text=`ok`
|
||||
> print text=`tok`
|
||||
> print text=`hex`
|
||||
1. `ok`
|
||||
> print text=mid-m1-ok
|
||||
2. *
|
||||
> print text=mid-m1-fail
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
title: 中层标准库 — 正则与编解码
|
||||
description: lib/正则 + lib/编码,无需插件(中层 M1)
|
||||
导入 正则:lib/正则.mq.md
|
||||
导入 编码:lib/编码.mq.md
|
||||
---
|
||||
|
||||
# 标准库中的正则与编解码
|
||||
|
||||
中层标准库:日常原语进 `lib/`,不必 ABI 插件。
|
||||
|
||||
# main
|
||||
|
||||
*`ok` = > 正则.匹配 内容="user@example.com" 模式="^[^@]+@[^@]+$"*
|
||||
*`tok` = > 编码.基64编码 内容="marqdo"*
|
||||
*`hex` = > 编码.十六进制编码 内容="ok"*
|
||||
> 打印 内容=`ok`
|
||||
> 打印 内容=`tok`
|
||||
> 打印 内容=`hex`
|
||||
1. `ok`
|
||||
> 打印 内容=mid-m1-ok
|
||||
2. *
|
||||
> 打印 内容=mid-m1-fail
|
||||
+60
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::{fs, json, math, net, sys, time, writeback, HostContext};
|
||||
use crate::host::{encoding, fs, json, math, net, re, sys, time, writeback, HostContext};
|
||||
#[cfg(feature = "exec-host")]
|
||||
use crate::host::{foreign, subtask};
|
||||
#[cfg(feature = "plugin-host")]
|
||||
@@ -128,6 +128,15 @@ pub enum HostFn {
|
||||
CookieParse = 122,
|
||||
MultipartParse = 123,
|
||||
MarkdownParse = 124,
|
||||
ReIsMatch = 125,
|
||||
ReFind = 126,
|
||||
ReFindAll = 127,
|
||||
ReReplace = 128,
|
||||
ReSplit = 129,
|
||||
EncodingBase64Encode = 130,
|
||||
EncodingBase64Decode = 131,
|
||||
EncodingHexEncode = 132,
|
||||
EncodingHexDecode = 133,
|
||||
}
|
||||
|
||||
|
||||
@@ -249,6 +258,15 @@ impl HostFn {
|
||||
122 => Self::CookieParse,
|
||||
123 => Self::MultipartParse,
|
||||
124 => Self::MarkdownParse,
|
||||
125 => Self::ReIsMatch,
|
||||
126 => Self::ReFind,
|
||||
127 => Self::ReFindAll,
|
||||
128 => Self::ReReplace,
|
||||
129 => Self::ReSplit,
|
||||
130 => Self::EncodingBase64Encode,
|
||||
131 => Self::EncodingBase64Decode,
|
||||
132 => Self::EncodingHexEncode,
|
||||
133 => Self::EncodingHexDecode,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -373,6 +391,15 @@ impl HostFn {
|
||||
"host_cookie_parse" | "cookie_parse" => Self::CookieParse,
|
||||
"host_multipart_parse" | "multipart_parse" => Self::MultipartParse,
|
||||
"host_markdown_parse" | "markdown_parse" => Self::MarkdownParse,
|
||||
"host_re_is_match" | "re_is_match" => Self::ReIsMatch,
|
||||
"host_re_find" | "re_find" => Self::ReFind,
|
||||
"host_re_find_all" | "re_find_all" => Self::ReFindAll,
|
||||
"host_re_replace" | "re_replace" => Self::ReReplace,
|
||||
"host_re_split" | "re_split" => Self::ReSplit,
|
||||
"host_encoding_base64_encode" | "encoding_base64_encode" => Self::EncodingBase64Encode,
|
||||
"host_encoding_base64_decode" | "encoding_base64_decode" => Self::EncodingBase64Decode,
|
||||
"host_encoding_hex_encode" | "encoding_hex_encode" => Self::EncodingHexEncode,
|
||||
"host_encoding_hex_decode" | "encoding_hex_decode" => Self::EncodingHexDecode,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -484,6 +511,15 @@ impl HostFn {
|
||||
Self::CookieParse => "host_cookie_parse",
|
||||
Self::MultipartParse => "host_multipart_parse",
|
||||
Self::MarkdownParse => "host_markdown_parse",
|
||||
Self::ReIsMatch => "host_re_is_match",
|
||||
Self::ReFind => "host_re_find",
|
||||
Self::ReFindAll => "host_re_find_all",
|
||||
Self::ReReplace => "host_re_replace",
|
||||
Self::ReSplit => "host_re_split",
|
||||
Self::EncodingBase64Encode => "host_encoding_base64_encode",
|
||||
Self::EncodingBase64Decode => "host_encoding_base64_decode",
|
||||
Self::EncodingHexEncode => "host_encoding_hex_encode",
|
||||
Self::EncodingHexDecode => "host_encoding_hex_decode",
|
||||
Self::WritebackRecord => "host_writeback_record",
|
||||
Self::WritebackGet => "host_writeback_get",
|
||||
Self::WritebackClear => "host_writeback_clear",
|
||||
@@ -569,6 +605,14 @@ impl HostFn {
|
||||
Self::CookieParse => &["text", "is_response"],
|
||||
Self::MultipartParse => &["body", "boundary"],
|
||||
Self::MarkdownParse => &["text"],
|
||||
Self::ReIsMatch | Self::ReFind | Self::ReFindAll | Self::ReSplit => {
|
||||
&["text", "pattern"]
|
||||
}
|
||||
Self::ReReplace => &["text", "pattern", "with"],
|
||||
Self::EncodingBase64Encode
|
||||
| Self::EncodingBase64Decode
|
||||
| Self::EncodingHexEncode
|
||||
| Self::EncodingHexDecode => &["text"],
|
||||
Self::WritebackRecord => &["value"],
|
||||
Self::WritebackGet | Self::WritebackClear => &[],
|
||||
Self::WritebackList => &[],
|
||||
@@ -601,6 +645,7 @@ impl HostFn {
|
||||
Self::WritebackEnsure => &["placeholder", "line"],
|
||||
Self::SubtaskSpawn => &["path", "fn", "args", "code", "lang", "source", "stdin", "quiet"],
|
||||
Self::ListSlice => &["end"],
|
||||
Self::ReReplace => &["count"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
@@ -970,6 +1015,20 @@ pub fn call_host(
|
||||
HostFn::CookieParse => net::cookie_parse(require(bound, "text")?, bound.get("is_response")),
|
||||
HostFn::MultipartParse => net::multipart_parse(require(bound, "body")?, require(bound, "boundary")?),
|
||||
HostFn::MarkdownParse => net::markdown_parse(require(bound, "text")?),
|
||||
HostFn::ReIsMatch => re::is_match(require(bound, "text")?, require(bound, "pattern")?),
|
||||
HostFn::ReFind => re::find(require(bound, "text")?, require(bound, "pattern")?),
|
||||
HostFn::ReFindAll => re::find_all(require(bound, "text")?, require(bound, "pattern")?),
|
||||
HostFn::ReReplace => re::replace(
|
||||
require(bound, "text")?,
|
||||
require(bound, "pattern")?,
|
||||
require(bound, "with")?,
|
||||
bound.get("count"),
|
||||
),
|
||||
HostFn::ReSplit => re::split(require(bound, "text")?, require(bound, "pattern")?),
|
||||
HostFn::EncodingBase64Encode => encoding::base64_encode(require(bound, "text")?),
|
||||
HostFn::EncodingBase64Decode => encoding::base64_decode(require(bound, "text")?),
|
||||
HostFn::EncodingHexEncode => encoding::hex_encode(require(bound, "text")?),
|
||||
HostFn::EncodingHexDecode => encoding::hex_decode(require(bound, "text")?),
|
||||
HostFn::OuterCallLine => Ok(Value::Int(
|
||||
ctx.call_site_lines
|
||||
.first()
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Base64 / hex encoding for Mid M1 (`lib/encoding`).
|
||||
//! No third-party crates — standard alphabet + padding.
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(s.as_str()),
|
||||
_ => Err(format!("{label} needs text")),
|
||||
}
|
||||
}
|
||||
|
||||
const B64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
pub fn base64_encode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
Ok(Value::Text(encode_base64(s.as_bytes())))
|
||||
}
|
||||
|
||||
pub fn base64_decode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
let bytes = decode_base64(s)?;
|
||||
let out = String::from_utf8(bytes).map_err(|e| format!("base64_decode: invalid utf-8: {e}"))?;
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn hex_encode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
let mut out = String::with_capacity(s.len() * 2);
|
||||
for b in s.as_bytes() {
|
||||
out.push_str(&format!("{b:02x}"));
|
||||
}
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn hex_decode(text: &Value) -> Result<Value, String> {
|
||||
let s = as_text(text, "text")?;
|
||||
if s.len() % 2 != 0 {
|
||||
return Err("hex_decode: length must be even".into());
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(s.len() / 2);
|
||||
// Require ASCII hex digits only (byte-oriented).
|
||||
let raw = s.as_bytes();
|
||||
if raw.len() != s.len() {
|
||||
return Err("hex_decode: needs ASCII hex".into());
|
||||
}
|
||||
for i in (0..raw.len()).step_by(2) {
|
||||
let hi = from_hex(raw[i])?;
|
||||
let lo = from_hex(raw[i + 1])?;
|
||||
bytes.push((hi << 4) | lo);
|
||||
}
|
||||
let out = String::from_utf8(bytes).map_err(|e| format!("hex_decode: invalid utf-8: {e}"))?;
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
fn from_hex(b: u8) -> Result<u8, String> {
|
||||
match b {
|
||||
b'0'..=b'9' => Ok(b - b'0'),
|
||||
b'a'..=b'f' => Ok(b - b'a' + 10),
|
||||
b'A'..=b'F' => Ok(b - b'A' + 10),
|
||||
_ => Err(format!("hex_decode: invalid digit {:?}", b as char)),
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_base64(input: &[u8]) -> String {
|
||||
let mut out = String::with_capacity((input.len() + 2) / 3 * 4);
|
||||
let mut i = 0;
|
||||
while i + 3 <= input.len() {
|
||||
let n = ((input[i] as u32) << 16) | ((input[i + 1] as u32) << 8) | (input[i + 2] as u32);
|
||||
out.push(B64[((n >> 18) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 12) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 6) & 63) as usize] as char);
|
||||
out.push(B64[(n & 63) as usize] as char);
|
||||
i += 3;
|
||||
}
|
||||
let rem = input.len() - i;
|
||||
if rem == 1 {
|
||||
let n = (input[i] as u32) << 16;
|
||||
out.push(B64[((n >> 18) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 12) & 63) as usize] as char);
|
||||
out.push('=');
|
||||
out.push('=');
|
||||
} else if rem == 2 {
|
||||
let n = ((input[i] as u32) << 16) | ((input[i + 1] as u32) << 8);
|
||||
out.push(B64[((n >> 18) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 12) & 63) as usize] as char);
|
||||
out.push(B64[((n >> 6) & 63) as usize] as char);
|
||||
out.push('=');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn decode_base64(input: &str) -> Result<Vec<u8>, String> {
|
||||
let raw = input.as_bytes();
|
||||
if raw.len() % 4 != 0 {
|
||||
return Err("base64_decode: length must be multiple of 4".into());
|
||||
}
|
||||
let mut out = Vec::with_capacity(raw.len() / 4 * 3);
|
||||
let mut i = 0;
|
||||
while i < raw.len() {
|
||||
let a = decode_b64_char(raw[i])?;
|
||||
let b = decode_b64_char(raw[i + 1])?;
|
||||
let c = raw[i + 2];
|
||||
let d = raw[i + 3];
|
||||
let c_val = if c == b'=' {
|
||||
0
|
||||
} else {
|
||||
decode_b64_char(c)?
|
||||
};
|
||||
let d_val = if d == b'=' {
|
||||
0
|
||||
} else {
|
||||
decode_b64_char(d)?
|
||||
};
|
||||
let n = (a << 18) | (b << 12) | (c_val << 6) | d_val;
|
||||
out.push(((n >> 16) & 0xff) as u8);
|
||||
if c != b'=' {
|
||||
out.push(((n >> 8) & 0xff) as u8);
|
||||
}
|
||||
if d != b'=' {
|
||||
out.push((n & 0xff) as u8);
|
||||
}
|
||||
if c == b'=' && d != b'=' {
|
||||
return Err("base64_decode: invalid padding".into());
|
||||
}
|
||||
i += 4;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn decode_b64_char(b: u8) -> Result<u32, String> {
|
||||
let v = match b {
|
||||
b'A'..=b'Z' => b - b'A',
|
||||
b'a'..=b'z' => b - b'a' + 26,
|
||||
b'0'..=b'9' => b - b'0' + 52,
|
||||
b'+' => 62,
|
||||
b'/' => 63,
|
||||
_ => return Err(format!("base64_decode: invalid character {:?}", b as char)),
|
||||
};
|
||||
Ok(v as u32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn roundtrip_hello() {
|
||||
let enc = base64_encode(&Value::Text("hello".into())).unwrap();
|
||||
assert_eq!(enc, Value::Text("aGVsbG8=".into()));
|
||||
let dec = base64_decode(&enc).unwrap();
|
||||
assert_eq!(dec, Value::Text("hello".into()));
|
||||
let hx = hex_encode(&Value::Text("hi".into())).unwrap();
|
||||
assert_eq!(hx, Value::Text("6869".into()));
|
||||
assert_eq!(hex_decode(&hx).unwrap(), Value::Text("hi".into()));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
pub mod agent_rt;
|
||||
pub mod collection;
|
||||
mod dispatch;
|
||||
mod encoding;
|
||||
pub mod event_bus;
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub mod foreign;
|
||||
@@ -14,6 +15,7 @@ mod fs;
|
||||
pub(crate) mod json;
|
||||
pub mod math;
|
||||
mod net;
|
||||
mod re;
|
||||
#[cfg(feature = "plugin-host")]
|
||||
pub mod plugin;
|
||||
#[cfg(not(feature = "plugin-host"))]
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
//! Regex host primitives for Mid M1 (`lib/re`).
|
||||
|
||||
use crate::value::Value;
|
||||
use regex::Regex;
|
||||
|
||||
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(s.as_str()),
|
||||
_ => Err(format!("{label} needs text")),
|
||||
}
|
||||
}
|
||||
|
||||
fn compile(pattern: &str) -> Result<Regex, String> {
|
||||
Regex::new(pattern).map_err(|e| format!("invalid regex: {e}"))
|
||||
}
|
||||
|
||||
pub fn is_match(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let re = compile(p)?;
|
||||
Ok(Value::Bool(re.is_match(t)))
|
||||
}
|
||||
|
||||
pub fn find(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let re = compile(p)?;
|
||||
Ok(match re.find(t) {
|
||||
Some(m) => Value::Text(m.as_str().to_string()),
|
||||
None => Value::None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn find_all(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let re = compile(p)?;
|
||||
let xs: Vec<Value> = re
|
||||
.find_iter(t)
|
||||
.map(|m| Value::Text(m.as_str().to_string()))
|
||||
.collect();
|
||||
Ok(Value::List(xs))
|
||||
}
|
||||
|
||||
pub fn replace(
|
||||
text: &Value,
|
||||
pattern: &Value,
|
||||
with: &Value,
|
||||
count: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let w = as_text(with, "with")?;
|
||||
let re = compile(p)?;
|
||||
let limit = match count {
|
||||
None | Some(Value::None) => None,
|
||||
Some(Value::Int(n)) => {
|
||||
if *n < 0 {
|
||||
return Err("count must be non-negative".into());
|
||||
}
|
||||
Some(*n as usize)
|
||||
}
|
||||
Some(_) => return Err("count needs int".into()),
|
||||
};
|
||||
let out = match limit {
|
||||
None => re.replace_all(t, w).into_owned(),
|
||||
Some(0) => t.to_string(),
|
||||
Some(n) => re.replacen(t, n, w).into_owned(),
|
||||
};
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
pub fn split(text: &Value, pattern: &Value) -> Result<Value, String> {
|
||||
let t = as_text(text, "text")?;
|
||||
let p = as_text(pattern, "pattern")?;
|
||||
let re = compile(p)?;
|
||||
let xs: Vec<Value> = re
|
||||
.split(t)
|
||||
.map(|s| Value::Text(s.to_string()))
|
||||
.collect();
|
||||
Ok(Value::List(xs))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn match_and_find() {
|
||||
assert_eq!(
|
||||
is_match(
|
||||
&Value::Text("abc123".into()),
|
||||
&Value::Text(r"\d+".into())
|
||||
)
|
||||
.unwrap(),
|
||||
Value::Bool(true)
|
||||
);
|
||||
assert_eq!(
|
||||
find(
|
||||
&Value::Text("ab12cd34".into()),
|
||||
&Value::Text(r"\d+".into())
|
||||
)
|
||||
.unwrap(),
|
||||
Value::Text("12".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1066,6 +1066,35 @@ fn lib_fs_read() {
|
||||
assert_out("tests/lib/fs-read.mq.md", "exists\nhello-lib");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_re_smoke() {
|
||||
assert_out(
|
||||
"tests/lib/re-smoke.mq.md",
|
||||
"True\n12\n1,22,333\naXbXc3\na|b|c",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_re_smoke_zh() {
|
||||
assert_out("tests/lib/正则-烟测.mq.md", "True\n12\n1,22,333");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_encoding_smoke() {
|
||||
assert_out(
|
||||
"tests/lib/encoding-smoke.mq.md",
|
||||
"aGVsbG8=\nhello\n6869\nhi",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_encoding_smoke_zh() {
|
||||
assert_out(
|
||||
"tests/lib/编码-烟测.mq.md",
|
||||
"aGVsbG8=\nhello\n6869\nhi",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_fs_read_zh() {
|
||||
assert_out("tests/lib/文件-读.mq.md", "存在\nhello-lib");
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
title: lib/encoding smoke
|
||||
import enc:lib/encoding.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*b = > enc.base64_encode text="hello"*
|
||||
> print text=`b`
|
||||
|
||||
*back = > enc.base64_decode text=`b`*
|
||||
> print text=`back`
|
||||
|
||||
*h = > enc.hex_encode text="hi"*
|
||||
> print text=`h`
|
||||
|
||||
*hb = > enc.hex_decode text=`h`*
|
||||
> print text=`hb`
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
title: lib/re smoke
|
||||
import re:lib/re.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*ok = > re.is_match text="abc123" pattern="\\d+"*
|
||||
> print text=`ok`
|
||||
|
||||
*m = > re.find text="ab12cd34" pattern="\\d+"*
|
||||
> print text=`m`
|
||||
|
||||
*all = > re.find_all text="a1b22c333" pattern="\\d+"*
|
||||
*joined = > join value=`all` sep=","*
|
||||
> print text=`joined`
|
||||
|
||||
*rep = > re.replace text="a1b2c3" pattern="\\d+" with="X" count=2*
|
||||
> print text=`rep`
|
||||
|
||||
*parts = > re.split text="a-b-c" pattern="-"*
|
||||
*pj = > join value=`parts` sep="|"*
|
||||
> print text=`pj`
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
title: lib/正则 烟测
|
||||
导入 正则:lib/正则.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*ok = > 正则.匹配 内容="abc123" 模式="\\d+"*
|
||||
> 打印 内容=`ok`
|
||||
|
||||
*m = > 正则.查找 内容="ab12cd34" 模式="\\d+"*
|
||||
> 打印 内容=`m`
|
||||
|
||||
*all = > 正则.查找全部 内容="a1b22c333" 模式="\\d+"*
|
||||
*joined = > join value=`all` sep=","*
|
||||
> 打印 内容=`joined`
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
title: lib/编码 烟测
|
||||
导入 编码:lib/编码.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*b = > 编码.基64编码 内容="hello"*
|
||||
> 打印 内容=`b`
|
||||
|
||||
*back = > 编码.基64解码 内容=`b`*
|
||||
> 打印 内容=`back`
|
||||
|
||||
*h = > 编码.十六进制编码 内容="hi"*
|
||||
> 打印 内容=`h`
|
||||
|
||||
*hb = > 编码.十六进制解码 内容=`h`*
|
||||
> 打印 内容=`hb`
|
||||
Reference in new issue
Block a user