From 435f36b6e9984c6e148b9545452e33ee11e3a007 Mon Sep 17 00:00:00 2001 From: cflmy Date: Wed, 9 Sep 2026 09:22:00 +0800 Subject: [PATCH] feat(stdlib): Mid2 M8 toml, html escape, and base32 Add read-only TOML subset parse, HTML escape/unescape, and RFC 4648 base32 on encoding; gold tests and public demos included. Co-authored-by: Cursor --- CHANGELOG.md | 1 + doc/README.md | 2 + doc/design/stdlib-html.md | 19 ++ doc/design/stdlib-mid2.md | 2 +- doc/design/stdlib-modules.md | 6 +- doc/design/stdlib-toml.md | 24 ++ doc/research/stdlib-gaps-after-mid.md | 2 +- doc/roadmap/stdlib-mid2.md | 16 +- lib/encoding.mq.md | 14 +- lib/html.mq.md | 14 + lib/toml.mq.md | 9 + lib/编码.mq.md | 12 +- lib/超文本.mq.md | 14 + lib/配置表.mq.md | 9 + public/features/15-toml-html-encoding.mq.md | 24 ++ public/features/15-配置表超文本编码.mq.md | 20 ++ src/host/dispatch.rs | 34 +- src/host/encoding.rs | 71 ++++ src/host/html_ops.rs | 71 ++++ src/host/mod.rs | 4 +- src/host/toml_ops.rs | 340 ++++++++++++++++++++ tests/gold.rs | 16 + tests/lib/toml-html-encoding-smoke.mq.md | 24 ++ tests/lib/配置表-超文本-编码-烟测.mq.md | 18 ++ 24 files changed, 748 insertions(+), 18 deletions(-) create mode 100644 doc/design/stdlib-html.md create mode 100644 doc/design/stdlib-toml.md create mode 100644 lib/html.mq.md create mode 100644 lib/toml.mq.md create mode 100644 lib/超文本.mq.md create mode 100644 lib/配置表.mq.md create mode 100644 public/features/15-toml-html-encoding.mq.md create mode 100644 public/features/15-配置表超文本编码.mq.md create mode 100644 src/host/html_ops.rs create mode 100644 src/host/toml_ops.rs create mode 100644 tests/lib/toml-html-encoding-smoke.mq.md create mode 100644 tests/lib/配置表-超文本-编码-烟测.mq.md diff --git a/CHANGELOG.md b/CHANGELOG.md index c4a5dfb..0d82e0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased ### Added +- **中层标准库 Mid2 M8**:`lib/toml` / `配置表`(只读子集)、`lib/html` / `超文本`(escape/unescape)、`encoding` base32;金样与 public `15-toml-html-encoding`。设计 [stdlib-toml.md](doc/design/stdlib-toml.md) · [stdlib-html.md](doc/design/stdlib-html.md)。 - **中层标准库 Mid2 M7**:`lib/datetime` / `日期时间`(`{unix,zone,iso}` · parse/format/add/in_zone)与 `lib/url` / `地址`(parse · query_parse/stringify);金样与 public `14-datetime-url`。设计 [stdlib-datetime.md](doc/design/stdlib-datetime.md) · [stdlib-url.md](doc/design/stdlib-url.md)。 - **文档**:中层标准库 Mid 之后缺口盘点与 Mid2(M7–M10)设计/路线——[stdlib-gaps-after-mid.md](doc/research/stdlib-gaps-after-mid.md) · [stdlib-mid2.md](doc/design/stdlib-mid2.md) · [stdlib-mid2.md](doc/roadmap/stdlib-mid2.md)。 diff --git a/doc/README.md b/doc/README.md index b72eede..0bbece10 100644 --- a/doc/README.md +++ b/doc/README.md @@ -36,6 +36,8 @@ | [design/stdlib-mid2.md](design/stdlib-mid2.md) | **中层 Mid2:datetime / url / toml / html / fs++** | | [design/stdlib-datetime.md](design/stdlib-datetime.md) | **`lib/datetime`(Mid2 M7)** | | [design/stdlib-url.md](design/stdlib-url.md) | **`lib/url`(Mid2 M7)** | +| [design/stdlib-toml.md](design/stdlib-toml.md) | **`lib/toml`(Mid2 M8)** | +| [design/stdlib-html.md](design/stdlib-html.md) | **`lib/html`(Mid2 M8)** | | [research/stdlib-gaps-after-mid.md](research/stdlib-gaps-after-mid.md) | **Mid 之后缺口盘点**(对照 Python/Go) | | [roadmap/stdlib-mid.md](roadmap/stdlib-mid.md) | **Mid M1–M6 路线(done)** | | [roadmap/stdlib-mid2.md](roadmap/stdlib-mid2.md) | **Mid2 M7–M10 路线(规划)** | diff --git a/doc/design/stdlib-html.md b/doc/design/stdlib-html.md new file mode 100644 index 0000000..d79d306 --- /dev/null +++ b/doc/design/stdlib-html.md @@ -0,0 +1,19 @@ +# 设计:`lib/html` / `lib/超文本`(Mid2 M8) + +| | | +|---|---| +| 状态 | **已落地** | +| 日期 | 2026-09-09 | +| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §3.2 | +| 宿主 | `src/host/html_ops.rs` · `host_html_escape` / `host_html_unescape` | + +--- + +## API + +| EN | ZH | 行为 | +|----|-----|------| +| `escape` | `转义` | `& < > " '` → 实体(`'` → `'`) | +| `unescape` | `还原` | 上述实体(含 `'` / `'`) | + +**不做** DOM / 模板引擎。 diff --git a/doc/design/stdlib-mid2.md b/doc/design/stdlib-mid2.md index 8b6d61c..6bd36ac 100644 --- a/doc/design/stdlib-mid2.md +++ b/doc/design/stdlib-mid2.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Draft · M7 已落地;M8–M10 锁定方向** | +| 状态 | **Draft · M7–M8 已落地;M9–M10 锁定方向** | | 日期 | 2026-09-09 | | 缺口盘点 | [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) | | 路线图 | [stdlib-mid2.md](../roadmap/stdlib-mid2.md) | diff --git a/doc/design/stdlib-modules.md b/doc/design/stdlib-modules.md index 4e0f267..5b83b2e 100644 --- a/doc/design/stdlib-modules.md +++ b/doc/design/stdlib-modules.md @@ -17,7 +17,7 @@ |--------|--------|--------|------| | 文本 | `lib/text.mq.md` | `lib/文本.mq.md` | 已有 + **Mid M4** 加厚 | | **正则** | `lib/re.mq.md` | `lib/正则.mq.md` | **Mid M1** | -| **编解码** | `lib/encoding.mq.md` | `lib/编码.mq.md` | **Mid M1** | +| **编解码** | `lib/encoding.mq.md` | `lib/编码.mq.md` | **Mid M1** + Mid2 M8 base32 | | **路径** | `lib/path.mq.md` | `lib/路径.mq.md` | **Mid M2** | | **哈希** | `lib/hash.mq.md` | `lib/哈希.mq.md` | **Mid M3** | | **机密** | `lib/secrets.mq.md` | `lib/机密.mq.md` | **Mid M3** | @@ -28,6 +28,8 @@ | **标识** | `lib/uuid.mq.md` | `lib/标识.mq.md` | **Mid M6** | | **日期时间** | `lib/datetime.mq.md` | `lib/日期时间.mq.md` | **Mid2 M7** | | **地址** | `lib/url.mq.md` | `lib/地址.mq.md` | **Mid2 M7** | +| **配置表** | `lib/toml.mq.md` | `lib/配置表.mq.md` | **Mid2 M8** | +| **超文本** | `lib/html.mq.md` | `lib/超文本.mq.md` | **Mid2 M8** | | 浏览器效应 | `lib/browser.mq.md` | `lib/浏览器.mq.md` | WASM 客户端效应助手(GFM + helpers;勿用 `json.set` 链) | | 文件 | `lib/fs.mq.md` | `lib/文件.mq.md` | 已有 + Mid M2:`copy_file` / `move` / `make_temp` | | 系统 | `lib/sys.mq.md` | `lib/系统.mq.md` | 已有(含 `load_dotenv`) | @@ -44,7 +46,7 @@ **中层已落地:** M1–M6(含 log / uuid)— 见 [stdlib-mid.md](stdlib-mid.md) · [stdlib-log-uuid.md](stdlib-log-uuid.md)。 -**Mid2:** **M7 done**(`datetime` · `url`)— [stdlib-datetime.md](stdlib-datetime.md) · [stdlib-url.md](stdlib-url.md);M8+ 见 [stdlib-mid2.md](stdlib-mid2.md) · [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md)。 +**Mid2:** **M7–M8 done**(`datetime` · `url` · `toml` · `html` · base32)— [stdlib-datetime.md](stdlib-datetime.md) · [stdlib-url.md](stdlib-url.md) · [stdlib-toml.md](stdlib-toml.md) · [stdlib-html.md](stdlib-html.md);M9+ 见 [stdlib-mid2.md](stdlib-mid2.md)。 设计细节:[stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md)。 diff --git a/doc/design/stdlib-toml.md b/doc/design/stdlib-toml.md new file mode 100644 index 0000000..261900b --- /dev/null +++ b/doc/design/stdlib-toml.md @@ -0,0 +1,24 @@ +# 设计:`lib/toml` / `lib/配置表`(Mid2 M8) + +| | | +|---|---| +| 状态 | **已落地** | +| 日期 | 2026-09-09 | +| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §3.1 | +| 宿主 | `src/host/toml_ops.rs` · `host_toml_parse`(手写子集,无 `toml` crate) | + +--- + +## 1. API + +| EN | ZH | 行为 | +|----|-----|------| +| `parse` | `解析` | TOML 文本 → map/list | + +**不做** `stringify`;写出继续用 JSON。 + +## 2. 子集 + +支持:`#` 注释、基本/字面字符串、int/float/bool、标量数组、`[table]` 与 dotted key。 + +**不支持:** `[[array of tables]]`、内联表、TOML datetime、多行字符串。 diff --git a/doc/research/stdlib-gaps-after-mid.md b/doc/research/stdlib-gaps-after-mid.md index 996f607..d06185d 100644 --- a/doc/research/stdlib-gaps-after-mid.md +++ b/doc/research/stdlib-gaps-after-mid.md @@ -127,7 +127,7 @@ catalog / 工具配置若走向 TOML,只读 `toml.parse` 性价比高。YAML | 优先级 | 波次草案 | 内容 | |--------|----------|------| | **高** | **M7** | `datetime` + `url` — **done** | -| **高** | **M8** | `toml` 只读 + `html.escape` + `encoding` base32 | +| **高** | **M8** | `toml` 只读 + `html.escape` + `encoding` base32 — **done** | | **中** | **M9** | `fs` 加厚(dirs/stat/walk) | | **低** | **M10** | `stats` 薄 · 可选 zip · 结构化 log 字段 | | **won't** | — | 完整 YAML · 模板引擎 · sqlite 进 `lib/` | diff --git a/doc/roadmap/stdlib-mid2.md b/doc/roadmap/stdlib-mid2.md index 6b9b97d..be9b7d7 100644 --- a/doc/roadmap/stdlib-mid2.md +++ b/doc/roadmap/stdlib-mid2.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Active · M7 已落地 · M8–M10 规划** | +| 状态 | **Active · M7–M8 已落地 · M9–M10 规划** | | 日期 | 2026-09-09 | | 设计 | [stdlib-mid2.md](../design/stdlib-mid2.md) | | 缺口 | [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) | @@ -43,16 +43,16 @@ M10 收口糖(可选) stats 薄 · log 字段 · (zip 默认跳过) | public | `14-datetime-url` · `14-日期时间地址` | | 设计 | [stdlib-datetime.md](../design/stdlib-datetime.md) · [stdlib-url.md](../design/stdlib-url.md) | -### M8 — toml + html + encoding — **todo** +### M8 — toml + html + encoding — **done** | 交付 | 说明 | |------|------| -| `lib/toml` 只读 `parse` | 配置引导 | -| `lib/html` `escape`/`unescape` | XSS 底线 | +| `lib/toml` · `配置表` | 只读子集 `parse` | +| `lib/html` · `超文本` | `escape` / `unescape` | | `encoding` base32 | RFC 4648 | -| 金样 | `toml-smoke` · `html-escape-smoke` · `encoding-base32` | - -**刻意不做:** YAML;TOML stringify(可后期)。 +| 金样 | `toml-html-encoding-smoke`(中英) | +| public | `15-toml-html-encoding` · `15-配置表超文本编码` | +| 设计 | [stdlib-toml.md](../design/stdlib-toml.md) · [stdlib-html.md](../design/stdlib-html.md) | ### M9 — fs 加厚 — **todo** @@ -74,7 +74,7 @@ M10 收口糖(可选) stats 薄 · log 字段 · (zip 默认跳过) ## 2. 进度勾选 - [x] M7 datetime + url -- [ ] M8 toml + html + base32 +- [x] M8 toml + html + base32 - [ ] M9 fs 加厚 - [ ] M10 可选 - [ ] 研究文高优先级缺口 → closed diff --git a/lib/encoding.mq.md b/lib/encoding.mq.md index 833775c..47338e8 100644 --- a/lib/encoding.mq.md +++ b/lib/encoding.mq.md @@ -1,6 +1,6 @@ --- title: lib/encoding -description: Base64 and hex encode/decode (Mid M1). UTF-8 text round-trip. +description: Base64, hex, and base32 encode/decode (Mid M1 + Mid2 M8). UTF-8 text round-trip. --- ## base64_encode @@ -22,3 +22,15 @@ description: Base64 and hex encode/decode (Mid M1). UTF-8 text round-trip. + `text` **> host_encoding_hex_decode text=`text`** + +## base32_encode + + `text` + +RFC 4648 alphabet; padding with `=`. + +**> host_encoding_base32_encode text=`text`** + +## base32_decode + + `text` + +**> host_encoding_base32_decode text=`text`** diff --git a/lib/html.mq.md b/lib/html.mq.md new file mode 100644 index 0000000..95a1665 --- /dev/null +++ b/lib/html.mq.md @@ -0,0 +1,14 @@ +--- +title: lib/html +description: HTML escape / unescape (Mid2 M8). XSS floor for string assembly. +--- + +## escape + + `text` + +**> host_html_escape text=`text`** + +## unescape + + `text` + +**> host_html_unescape text=`text`** diff --git a/lib/toml.mq.md b/lib/toml.mq.md new file mode 100644 index 0000000..5e72408 --- /dev/null +++ b/lib/toml.mq.md @@ -0,0 +1,9 @@ +--- +title: lib/toml +description: Read-only TOML subset parse (Mid2 M8). Tables, scalars, arrays; no array-of-tables. +--- + +## parse + + `text` + +**> host_toml_parse text=`text`** diff --git a/lib/编码.mq.md b/lib/编码.mq.md index 549edff..c3ecaa1 100644 --- a/lib/编码.mq.md +++ b/lib/编码.mq.md @@ -1,6 +1,6 @@ --- title: lib/编码 -description: Base64 与十六进制编解码(中层 M1)。UTF-8 文本往返。 +description: Base64、十六进制与基32编解码(中层 M1 + Mid2 M8)。UTF-8 文本往返。 --- ## 基64编码 @@ -22,3 +22,13 @@ description: Base64 与十六进制编解码(中层 M1)。UTF-8 文本往返 + `内容` **> host_encoding_hex_decode text=`内容`** + +## 基32编码 + + `内容` + +**> host_encoding_base32_encode text=`内容`** + +## 基32解码 + + `内容` + +**> host_encoding_base32_decode text=`内容`** diff --git a/lib/超文本.mq.md b/lib/超文本.mq.md new file mode 100644 index 0000000..fa7672d --- /dev/null +++ b/lib/超文本.mq.md @@ -0,0 +1,14 @@ +--- +title: lib/超文本 +description: HTML 转义 / 还原(中层 Mid2 M8)。拼装字符串时的 XSS 底线。 +--- + +## 转义 + + `内容` + +**> host_html_escape text=`内容`** + +## 还原 + + `内容` + +**> host_html_unescape text=`内容`** diff --git a/lib/配置表.mq.md b/lib/配置表.mq.md new file mode 100644 index 0000000..ad54de3 --- /dev/null +++ b/lib/配置表.mq.md @@ -0,0 +1,9 @@ +--- +title: lib/配置表 +description: 只读 TOML 子集解析(中层 Mid2 M8)。表 / 标量 / 数组;无数组表。 +--- + +## 解析 + + `内容` + +**> host_toml_parse text=`内容`** diff --git a/public/features/15-toml-html-encoding.mq.md b/public/features/15-toml-html-encoding.mq.md new file mode 100644 index 0000000..53f8552 --- /dev/null +++ b/public/features/15-toml-html-encoding.mq.md @@ -0,0 +1,24 @@ +--- +title: Mid stdlib — toml, html, base32 +description: Config TOML + HTML escape + base32 (Mid2 M8) +import toml:lib/toml.mq.md +import html:lib/html.mq.md +import enc:lib/encoding.mq.md +--- + +# Config and safe text without plugins + +Parse a TOML subset for tools, escape HTML before assembly, encode with base32. + +# main + +*cfg = > toml.parse text="app = \"demo\"\n[server]\nport = 8080\n"* +> print text=`cfg`[^app] +*srv = `cfg`[^server]* +> print text=`srv`[^port] + +*safe = > html.escape text=""* +> print text=`safe` + +*b = > enc.base32_encode text="ok"* +> print text=`b` diff --git a/public/features/15-配置表超文本编码.mq.md b/public/features/15-配置表超文本编码.mq.md new file mode 100644 index 0000000..366add9 --- /dev/null +++ b/public/features/15-配置表超文本编码.mq.md @@ -0,0 +1,20 @@ +--- +title: 中层标准库 — 配置表、超文本、基32 +description: TOML 配置 + HTML 转义 + base32(Mid2 M8) +导入 配置:lib/配置表.mq.md +导入 超:lib/超文本.mq.md +导入 编:lib/编码.mq.md +--- + +# 无需插件的配置与安全字面 + +# main + +*cfg = > 配置.解析 内容="app = \"演示\"\n"* +> print text=`cfg`[^app] + +*safe = > 超.转义 内容=""* +> print text=`safe` + +*b = > 编.基32编码 内容="ok"* +> print text=`b` diff --git a/src/host/dispatch.rs b/src/host/dispatch.rs index 416d0f5..6880482 100644 --- a/src/host/dispatch.rs +++ b/src/host/dispatch.rs @@ -3,8 +3,8 @@ use std::collections::HashMap; use crate::host::{ - cli, csv, datetime, encoding, fs, hash, json, log, math, net, path, re, secrets, sys, text_ops, - time, url_ops, uuid_ops, writeback, HostContext, + cli, csv, datetime, encoding, fs, hash, html_ops, json, log, math, net, path, re, secrets, sys, + text_ops, time, toml_ops, url_ops, uuid_ops, writeback, HostContext, }; #[cfg(feature = "exec-host")] use crate::host::{foreign, subtask}; @@ -186,6 +186,11 @@ pub enum HostFn { UrlParse = 177, UrlQueryParse = 178, UrlQueryStringify = 179, + TomlParse = 180, + HtmlEscape = 181, + HtmlUnescape = 182, + EncodingBase32Encode = 183, + EncodingBase32Decode = 184, } @@ -362,6 +367,11 @@ impl HostFn { 177 => Self::UrlParse, 178 => Self::UrlQueryParse, 179 => Self::UrlQueryStringify, + 180 => Self::TomlParse, + 181 => Self::HtmlEscape, + 182 => Self::HtmlUnescape, + 183 => Self::EncodingBase32Encode, + 184 => Self::EncodingBase32Decode, _ => return None, }) } @@ -541,6 +551,11 @@ impl HostFn { "host_url_parse" | "url_parse" => Self::UrlParse, "host_url_query_parse" | "url_query_parse" => Self::UrlQueryParse, "host_url_query_stringify" | "url_query_stringify" => Self::UrlQueryStringify, + "host_toml_parse" | "toml_parse" => Self::TomlParse, + "host_html_escape" | "html_escape" => Self::HtmlEscape, + "host_html_unescape" | "html_unescape" => Self::HtmlUnescape, + "host_encoding_base32_encode" | "encoding_base32_encode" => Self::EncodingBase32Encode, + "host_encoding_base32_decode" | "encoding_base32_decode" => Self::EncodingBase32Decode, _ => return None, }) } @@ -707,6 +722,11 @@ impl HostFn { Self::UrlParse => "host_url_parse", Self::UrlQueryParse => "host_url_query_parse", Self::UrlQueryStringify => "host_url_query_stringify", + Self::TomlParse => "host_toml_parse", + Self::HtmlEscape => "host_html_escape", + Self::HtmlUnescape => "host_html_unescape", + Self::EncodingBase32Encode => "host_encoding_base32_encode", + Self::EncodingBase32Decode => "host_encoding_base32_decode", Self::WritebackRecord => "host_writeback_record", Self::WritebackGet => "host_writeback_get", Self::WritebackClear => "host_writeback_clear", @@ -799,7 +819,9 @@ impl HostFn { Self::EncodingBase64Encode | Self::EncodingBase64Decode | Self::EncodingHexEncode - | Self::EncodingHexDecode => &["text"], + | Self::EncodingHexDecode + | Self::EncodingBase32Encode + | Self::EncodingBase32Decode => &["text"], Self::PathJoin => &["a", "b"], Self::PathSplit | Self::PathFileName @@ -838,6 +860,7 @@ impl HostFn { Self::DatetimeInZone => &["dt", "zone"], Self::UrlParse | Self::UrlQueryParse => &["text"], Self::UrlQueryStringify => &["map"], + Self::TomlParse | Self::HtmlEscape | Self::HtmlUnescape => &["text"], Self::WritebackRecord => &["value"], Self::WritebackGet | Self::WritebackClear => &[], Self::WritebackList => &[], @@ -1263,6 +1286,11 @@ pub fn call_host( 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::EncodingBase32Encode => encoding::base32_encode(require(bound, "text")?), + HostFn::EncodingBase32Decode => encoding::base32_decode(require(bound, "text")?), + HostFn::TomlParse => toml_ops::parse(require(bound, "text")?), + HostFn::HtmlEscape => html_ops::escape(require(bound, "text")?), + HostFn::HtmlUnescape => html_ops::unescape(require(bound, "text")?), HostFn::PathJoin => path::join(require(bound, "a")?, require(bound, "b")?), HostFn::PathSplit => path::split(require(bound, "path")?), HostFn::PathFileName => path::file_name(require(bound, "path")?), diff --git a/src/host/encoding.rs b/src/host/encoding.rs index e1bdcb1..5ce6a2a 100644 --- a/src/host/encoding.rs +++ b/src/host/encoding.rs @@ -53,6 +53,74 @@ pub fn hex_decode(text: &Value) -> Result { Ok(Value::Text(out)) } +const B32: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + +pub fn base32_encode(text: &Value) -> Result { + let s = as_text(text, "text")?; + Ok(Value::Text(encode_base32(s.as_bytes()))) +} + +pub fn base32_decode(text: &Value) -> Result { + let s = as_text(text, "text")?; + let bytes = decode_base32(s)?; + let out = String::from_utf8(bytes).map_err(|e| format!("base32_decode: invalid utf-8: {e}"))?; + Ok(Value::Text(out)) +} + +fn encode_base32(input: &[u8]) -> String { + let mut out = String::new(); + let mut buffer: u64 = 0; + let mut bits = 0u32; + for &b in input { + buffer = (buffer << 8) | (b as u64); + bits += 8; + while bits >= 5 { + bits -= 5; + let idx = ((buffer >> bits) & 31) as usize; + out.push(B32[idx] as char); + } + } + if bits > 0 { + let idx = ((buffer << (5 - bits)) & 31) as usize; + out.push(B32[idx] as char); + } + while out.len() % 8 != 0 { + out.push('='); + } + out +} + +fn decode_base32(input: &str) -> Result, String> { + let cleaned: String = input + .chars() + .filter(|c| !c.is_whitespace()) + .map(|c| c.to_ascii_uppercase()) + .collect(); + if cleaned.len() % 8 != 0 { + return Err("base32_decode: length must be multiple of 8".into()); + } + let mut out = Vec::new(); + let mut buffer: u64 = 0; + let mut bits = 0u32; + for c in cleaned.bytes() { + if c == b'=' { + break; + } + let v = match c { + b'A'..=b'Z' => c - b'A', + b'2'..=b'7' => c - b'2' + 26, + _ => return Err(format!("base32_decode: invalid character {:?}", c as char)), + } as u64; + buffer = (buffer << 5) | v; + bits += 5; + if bits >= 8 { + bits -= 8; + out.push(((buffer >> bits) & 0xff) as u8); + } + } + Ok(out) +} + fn from_hex(b: u8) -> Result { match b { b'0'..=b'9' => Ok(b - b'0'), @@ -153,5 +221,8 @@ mod tests { 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())); + let b32 = base32_encode(&Value::Text("hello".into())).unwrap(); + assert_eq!(b32, Value::Text("NBSWY3DP".into())); + assert_eq!(base32_decode(&b32).unwrap(), Value::Text("hello".into())); } } diff --git a/src/host/html_ops.rs b/src/host/html_ops.rs new file mode 100644 index 0000000..785a938 --- /dev/null +++ b/src/host/html_ops.rs @@ -0,0 +1,71 @@ +//! HTML escape / unescape for Mid2 M8 (`lib/html`). + +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} must be text")), + } +} + +pub fn escape(text: &Value) -> Result { + let s = as_text(text, "text")?; + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + _ => out.push(c), + } + } + Ok(Value::Text(out)) +} + +pub fn unescape(text: &Value) -> Result { + let s = as_text(text, "text")?; + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(i) = rest.find('&') { + out.push_str(&rest[..i]); + rest = &rest[i..]; + if let Some(end) = rest.find(';') { + let ent = &rest[..=end]; + let ch = match ent { + "&" => Some('&'), + "<" => Some('<'), + ">" => Some('>'), + """ => Some('"'), + "'" | "'" | "'" => Some('\''), + _ => None, + }; + if let Some(c) = ch { + out.push(c); + rest = &rest[end + 1..]; + continue; + } + } + out.push('&'); + rest = &rest[1..]; + } + out.push_str(rest); + Ok(Value::Text(out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn roundtrip() { + let e = escape(&Value::Text(r#"a&"c'"#.into())).unwrap(); + assert_eq!( + e, + Value::Text("a<b>&"c'".into()) + ); + assert_eq!(unescape(&e).unwrap(), Value::Text(r#"a&"c'"#.into())); + } +} diff --git a/src/host/mod.rs b/src/host/mod.rs index 703f650..b1e9a13 100644 --- a/src/host/mod.rs +++ b/src/host/mod.rs @@ -16,6 +16,7 @@ pub mod event_bus; pub mod foreign; mod fs; mod hash; +mod html_ops; pub(crate) mod json; mod log; pub mod math; @@ -24,6 +25,8 @@ mod path; mod re; mod secrets; mod text_ops; +mod time; +mod toml_ops; mod url_ops; mod uuid_ops; #[cfg(feature = "plugin-host")] @@ -37,7 +40,6 @@ pub mod subtask; #[path = "subtask_stub.rs"] pub mod subtask; mod sys; -mod time; pub mod writeback; pub use dispatch::{call_host, HostFn}; diff --git a/src/host/toml_ops.rs b/src/host/toml_ops.rs new file mode 100644 index 0000000..5794ed7 --- /dev/null +++ b/src/host/toml_ops.rs @@ -0,0 +1,340 @@ +//! Minimal TOML → Marqdo Value for Mid2 M8 (`lib/toml`). +//! Subset: comments, keys, strings, ints, floats, bools, arrays of scalars, +//! `[table]` / dotted tables. No datetime, inline tables, or array-of-tables. + +use crate::host::json::json_to_value; +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} must be text")), + } +} + +pub fn parse(text: &Value) -> Result { + let raw = as_text(text, "text")?; + let json = toml_to_json(raw)?; + json_to_value(&json) +} + +fn toml_to_json(src: &str) -> Result { + let mut root = serde_json::Map::new(); + let mut current_path: Vec = Vec::new(); + for (lineno, line) in src.lines().enumerate() { + let line_no = lineno + 1; + let stripped = strip_comment(line); + let t = stripped.trim(); + if t.is_empty() { + continue; + } + if t.starts_with('[') { + if !t.ends_with(']') { + return Err(format!("toml.parse:{line_no}: bad table header")); + } + if t.starts_with("[[") { + return Err(format!( + "toml.parse:{line_no}: array-of-tables [[...]] not supported" + )); + } + let inner = t[1..t.len() - 1].trim(); + current_path = split_dotted_keys(inner, line_no)?; + ensure_table_path(&mut root, ¤t_path, line_no)?; + continue; + } + let (key, val) = t + .split_once('=') + .ok_or_else(|| format!("toml.parse:{line_no}: expected key = value"))?; + let key = key.trim(); + if key.is_empty() { + return Err(format!("toml.parse:{line_no}: empty key")); + } + let key_parts = split_dotted_keys(key, line_no)?; + let value = parse_value(val.trim(), line_no)?; + let parent = table_at_path(&mut root, ¤t_path, line_no)?; + insert_dotted(parent, &key_parts, value, line_no)?; + } + Ok(serde_json::Value::Object(root)) +} + +fn strip_comment(line: &str) -> String { + // Strip unquoted `#` comments. + let mut out = String::new(); + let mut in_str = false; + let mut chars = line.chars().peekable(); + while let Some(c) = chars.next() { + if !in_str && c == '#' { + break; + } + if c == '"' { + out.push(c); + in_str = !in_str; + continue; + } + if in_str && c == '\\' { + out.push(c); + if let Some(n) = chars.next() { + out.push(n); + } + continue; + } + out.push(c); + } + out +} + +fn split_dotted_keys(s: &str, line_no: usize) -> Result, String> { + let mut parts = Vec::new(); + let mut cur = String::new(); + let mut in_quote = false; + let mut chars = s.chars().peekable(); + while let Some(c) = chars.next() { + if c == '"' { + in_quote = !in_quote; + continue; + } + if c == '.' && !in_quote { + if cur.is_empty() { + return Err(format!("toml.parse:{line_no}: empty key segment")); + } + parts.push(std::mem::take(&mut cur)); + continue; + } + cur.push(c); + } + if in_quote { + return Err(format!("toml.parse:{line_no}: unclosed quoted key")); + } + if !cur.is_empty() { + parts.push(cur); + } + if parts.is_empty() { + return Err(format!("toml.parse:{line_no}: empty path")); + } + Ok(parts) +} + +fn ensure_table_path( + root: &mut serde_json::Map, + path: &[String], + line_no: usize, +) -> Result<(), String> { + let mut cur = root; + for seg in path { + if !cur.contains_key(seg) { + cur.insert(seg.clone(), serde_json::Value::Object(serde_json::Map::new())); + } + cur = match cur.get_mut(seg) { + Some(serde_json::Value::Object(m)) => m, + Some(_) => { + return Err(format!("toml.parse:{line_no}: {seg} is not a table")); + } + None => unreachable!(), + }; + } + Ok(()) +} + +fn table_at_path<'a>( + root: &'a mut serde_json::Map, + path: &[String], + line_no: usize, +) -> Result<&'a mut serde_json::Map, String> { + let mut cur = root; + for seg in path { + cur = match cur.get_mut(seg) { + Some(serde_json::Value::Object(m)) => m, + Some(_) => { + return Err(format!("toml.parse:{line_no}: {seg} is not a table")); + } + None => { + return Err(format!("toml.parse:{line_no}: missing table {seg}")); + } + }; + } + Ok(cur) +} + +fn insert_dotted( + parent: &mut serde_json::Map, + parts: &[String], + value: serde_json::Value, + line_no: usize, +) -> Result<(), String> { + if parts.len() == 1 { + if parent.contains_key(&parts[0]) { + return Err(format!( + "toml.parse:{line_no}: duplicate key {}", + parts[0] + )); + } + parent.insert(parts[0].clone(), value); + return Ok(()); + } + let head = &parts[0]; + let entry = parent + .entry(head.clone()) + .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new())); + let obj = match entry { + serde_json::Value::Object(m) => m, + _ => { + return Err(format!("toml.parse:{line_no}: {head} is not a table")); + } + }; + insert_dotted(obj, &parts[1..], value, line_no) +} + +fn parse_value(s: &str, line_no: usize) -> Result { + if s.is_empty() { + return Err(format!("toml.parse:{line_no}: empty value")); + } + if s == "true" { + return Ok(serde_json::Value::Bool(true)); + } + if s == "false" { + return Ok(serde_json::Value::Bool(false)); + } + if s.starts_with('"') { + return Ok(serde_json::Value::String(parse_basic_string(s, line_no)?)); + } + if s.starts_with('\'') { + return Ok(serde_json::Value::String(parse_literal_string(s, line_no)?)); + } + if s.starts_with('[') { + return parse_array(s, line_no); + } + if let Ok(i) = s.replace('_', "").parse::() { + return Ok(serde_json::Value::Number(i.into())); + } + if let Ok(f) = s.replace('_', "").parse::() { + if let Some(n) = serde_json::Number::from_f64(f) { + return Ok(serde_json::Value::Number(n)); + } + } + Err(format!("toml.parse:{line_no}: unsupported value {s:?}")) +} + +fn parse_basic_string(s: &str, line_no: usize) -> Result { + if !s.ends_with('"') || s.len() < 2 { + return Err(format!("toml.parse:{line_no}: bad string")); + } + let inner = &s[1..s.len() - 1]; + let mut out = String::new(); + let mut chars = inner.chars(); + while let Some(c) = chars.next() { + if c == '\\' { + match chars.next() { + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some('r') => out.push('\r'), + Some('\\') => out.push('\\'), + Some('"') => out.push('"'), + Some(other) => { + return Err(format!( + "toml.parse:{line_no}: bad escape \\{other}" + )); + } + None => return Err(format!("toml.parse:{line_no}: trailing escape")), + } + } else { + out.push(c); + } + } + Ok(out) +} + +fn parse_literal_string(s: &str, line_no: usize) -> Result { + if !s.ends_with('\'') || s.len() < 2 { + return Err(format!("toml.parse:{line_no}: bad literal string")); + } + Ok(s[1..s.len() - 1].to_string()) +} + +fn parse_array(s: &str, line_no: usize) -> Result { + if !s.ends_with(']') { + return Err(format!("toml.parse:{line_no}: bad array")); + } + let inner = s[1..s.len() - 1].trim(); + if inner.is_empty() { + return Ok(serde_json::Value::Array(vec![])); + } + let mut items = Vec::new(); + let mut cur = String::new(); + let mut depth = 0i32; + let mut in_str = false; + let mut str_ch = '"'; + let mut chars = inner.chars().peekable(); + while let Some(c) = chars.next() { + if in_str { + cur.push(c); + if c == '\\' { + if let Some(n) = chars.next() { + cur.push(n); + } + continue; + } + if c == str_ch { + in_str = false; + } + continue; + } + match c { + '"' | '\'' => { + in_str = true; + str_ch = c; + cur.push(c); + } + '[' => { + depth += 1; + cur.push(c); + } + ']' => { + depth -= 1; + cur.push(c); + } + ',' if depth == 0 => { + items.push(parse_value(cur.trim(), line_no)?); + cur.clear(); + } + _ => cur.push(c), + } + } + if !cur.trim().is_empty() { + items.push(parse_value(cur.trim(), line_no)?); + } + Ok(serde_json::Value::Array(items)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_simple() { + let t = r#" +# comment +name = "marqdo" +count = 3 +ok = true +[pkg] +version = "0.1" +"#; + let v = parse(&Value::Text(t.into())).unwrap(); + let Value::Map(entries) = v else { panic!() }; + let get = |k: &str| { + entries + .iter() + .find(|(kk, _)| kk == k) + .map(|(_, v)| v.clone()) + .unwrap() + }; + assert_eq!(get("name"), Value::Text("marqdo".into())); + assert_eq!(get("count"), Value::Int(3)); + assert_eq!(get("ok"), Value::Bool(true)); + let Value::Map(pkg) = get("pkg") else { panic!() }; + assert_eq!( + pkg.iter().find(|(k, _)| k == "version").unwrap().1, + Value::Text("0.1".into()) + ); + } +} diff --git a/tests/gold.rs b/tests/gold.rs index c00254f..9ead7b5 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -1213,6 +1213,22 @@ fn lib_url_smoke_zh() { ); } +#[test] +fn lib_toml_html_encoding_smoke() { + assert_out( + "tests/lib/toml-html-encoding-smoke.mq.md", + "marqdo\n2\n1\na<b>&"c'\na&\"c'\nNBSWY3DP\nhello", + ); +} + +#[test] +fn lib_toml_html_encoding_smoke_zh() { + assert_out( + "tests/lib/配置表-超文本-编码-烟测.mq.md", + "中文\nTrue\na<b>\nNBUQ====", + ); +} + #[test] fn lib_re_smoke() { assert_out( diff --git a/tests/lib/toml-html-encoding-smoke.mq.md b/tests/lib/toml-html-encoding-smoke.mq.md new file mode 100644 index 0000000..dd9d3fd --- /dev/null +++ b/tests/lib/toml-html-encoding-smoke.mq.md @@ -0,0 +1,24 @@ +--- +title: lib/toml html encoding M8 smoke +import toml:lib/toml.mq.md +import html:lib/html.mq.md +import enc:lib/encoding.mq.md +--- + +# main + +*cfg = > toml.parse text="name = \"marqdo\"\ncount = 2\n[pkg]\nver = \"1\"\n"* +> print text=`cfg`[^name] +> print text=`cfg`[^count] +*pkg = `cfg`[^pkg]* +> print text=`pkg`[^ver] + +*e = > html.escape text="a&\"c'"* +> print text=`e` +*u = > html.unescape text=`e`* +> print text=`u` + +*b = > enc.base32_encode text="hello"* +> print text=`b` +*back = > enc.base32_decode text=`b`* +> print text=`back` diff --git a/tests/lib/配置表-超文本-编码-烟测.mq.md b/tests/lib/配置表-超文本-编码-烟测.mq.md new file mode 100644 index 0000000..57cb044 --- /dev/null +++ b/tests/lib/配置表-超文本-编码-烟测.mq.md @@ -0,0 +1,18 @@ +--- +title: lib/配置表 超文本 编码 烟测 +导入 配置:lib/配置表.mq.md +导入 超:lib/超文本.mq.md +导入 编:lib/编码.mq.md +--- + +# main + +*cfg = > 配置.解析 内容="name = \"中文\"\nok = true\n"* +> print text=`cfg`[^name] +> print text=`cfg`[^ok] + +*e = > 超.转义 内容="a"* +> print text=`e` + +*b = > 编.基32编码 内容="hi"* +> print text=`b`