feat(stdlib): Mid M5 list algorithms and cli.parse
Thicken table with sort/unique/chunk/zip/flatten and add lib/cli flag parsing, with golds and public demos. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
506de65dae
commit
7d86ed1d9c
20 files changed
+608
-14
No files matched your search
+2
-1
@@ -3,11 +3,12 @@
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
- **中层标准库 M5**:`table`/`表` 加厚(sort/sort_by/unique/chunk/zip/flatten)与 `lib/cli`/`命令行`(parse);金样与 public `12-list-cli`。设计 [stdlib-list-cli.md](doc/design/stdlib-list-cli.md)。
|
||||
- **中层标准库 M4**:`lib/csv` / `逗号表`(parse/stringify)与 `lib/text` / `文本` 加厚(contains/replace/case/pad/…);金样与 public `11-csv-text`。设计 [stdlib-csv.md](doc/design/stdlib-csv.md) · [stdlib-text-mid.md](doc/design/stdlib-text-mid.md)。
|
||||
- **中层标准库 M3**:`lib/hash` / `哈希`(sha256/sha1/md5/hmac_sha256)与 `lib/secrets` / `机密`(token_hex/token_urlsafe);金样与 public `10-hash-secrets`。设计 [stdlib-hash.md](doc/design/stdlib-hash.md) · [stdlib-secrets.md](doc/design/stdlib-secrets.md)。
|
||||
- **中层标准库 M2**:`lib/path` / `lib/路径`(join/split/normalize/…)与 `fs`/`文件` 加厚(`copy_file`/`move`/`make_temp`);金样与 public `09-path-fs`。设计 [stdlib-path.md](doc/design/stdlib-path.md) · [stdlib-fs-mid.md](doc/design/stdlib-fs-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/`(listx/cli/log …),减少「事事 ABI 插件」。路线 [stdlib-mid.md](doc/roadmap/stdlib-mid.md)。
|
||||
- **中层标准库(规划)**:M6 log/uuid 收口。路线 [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
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# `lib/table` 集合加厚 + `lib/cli`(Mid M5)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **已落地(M5)** |
|
||||
| 日期 | 2026-09-07 |
|
||||
| 相关 | [stdlib-mid.md](stdlib-mid.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) |
|
||||
| 集合 | 加厚现有 `lib/table` / `lib/表`(不另开 `listx`) |
|
||||
| CLI | `lib/cli.mq.md` / `lib/命令行.mq.md` |
|
||||
|
||||
---
|
||||
|
||||
## 1. 集合新增
|
||||
|
||||
| 英文 | 中文 | 形参 | 结果 |
|
||||
|------|------|------|------|
|
||||
| `sort` | `排序` | `list` | 升序列表(int/num/text 优先;其它按显示文本) |
|
||||
| `sort_by` | `按键排序` | `list`, `key` | 对 **map 列表**按键值排序 |
|
||||
| `unique` | `去重` | `list` | 保序去重 |
|
||||
| `chunk` | `分块` | `list`, `size` | 列表的列表 |
|
||||
| `zip` | `拉链` | `a`, `b` | `[[a0,b0], …]`(取较短长度) |
|
||||
| `flatten` | `展平` | `list` | 一层展平 |
|
||||
|
||||
`reverse` 已有。
|
||||
|
||||
## 2. CLI
|
||||
|
||||
| 英文 | 中文 | 形参 | 结果 |
|
||||
|------|------|------|------|
|
||||
| `parse` | `解析` | 可选 `args` | map:`--k v` / `--k=v` → 文本;裸 `--flag` → `True`;位置参 → 键 `_` 列表 |
|
||||
|
||||
`args` 缺省时用 `sys.args`(经宿主 `argv`)。
|
||||
|
||||
## 3. 刻意不做
|
||||
|
||||
稳定自定义比较器、惰性迭代器、完整 argparse 互斥组。
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **规划中 · M1–M4 已实现** |
|
||||
| 状态 | **规划中 · M1–M5 已实现** |
|
||||
| 日期 | 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 插件」的路径依赖 |
|
||||
@@ -122,7 +122,7 @@ OS / 算法库(精选 crate,默认 features 最小化)
|
||||
| **M2** | `path` / `路径` · `fs` 加厚 | join / normalize;copy / move / temp | **done** |
|
||||
| **M3** | `hash` / `哈希` · `secrets` / `机密` | sha256 / hmac;token | **done** |
|
||||
| **M4** | `csv` / `逗号表` · `text` 加厚 | parse / stringify;contains / replace | **done** |
|
||||
| **M5** | `listx` 或 `table` 加厚 · `cli` | sort / zip;flags | 优先纯 mq |
|
||||
| **M5** | `table` 加厚 · `cli` / `命令行` | sort / zip;flags | **done** |
|
||||
| **M6** | `log` / `日志` · `uuid` / `标识` | level 日志;v4 | 薄 host 或纯 mq |
|
||||
| **可选** | `yaml` / `Toml` | 仅当 public/catalog 强需求 | 慎入 |
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **核心已落地**;**中层 Mid:M1–M4 已落地** · [stdlib-mid.md](stdlib-mid.md) / [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) |
|
||||
| 状态 | **核心已落地**;**中层 Mid:M1–M5 已落地** · [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`) |
|
||||
@@ -22,7 +22,8 @@
|
||||
| **哈希** | `lib/hash.mq.md` | `lib/哈希.mq.md` | **Mid M3** |
|
||||
| **机密** | `lib/secrets.mq.md` | `lib/机密.mq.md` | **Mid M3** |
|
||||
| **逗号表** | `lib/csv.mq.md` | `lib/逗号表.mq.md` | **Mid M4** |
|
||||
| 表 | `lib/table.mq.md` | `lib/表.mq.md` | 已有(`put`/`改` + list/map;见 [stdlib-table.md](stdlib-table.md)) |
|
||||
| 表 | `lib/table.mq.md` | `lib/表.mq.md` | 已有 + Mid M4/M5:`sort`/`unique`/`zip`/… |
|
||||
| **命令行** | `lib/cli.mq.md` | `lib/命令行.mq.md` | **Mid M5** |
|
||||
| 浏览器效应 | `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`) |
|
||||
@@ -37,7 +38,7 @@
|
||||
|
||||
官方可选扩展(**非** stdlib):`ext/llm` · `ext/agent` · `ext/web` · `ext/quantum` · `ext/linalg` — 见各 `ext-*.md`。
|
||||
|
||||
**中层下一波候选(未落地):** table/listx + cli / log / uuid — 见 [stdlib-mid.md](stdlib-mid.md)。**已落地:** M1–M4。
|
||||
**中层下一波候选(未落地):** log / uuid — 见 [stdlib-mid.md](stdlib-mid.md)。**已落地:** M1–M5。
|
||||
|
||||
设计细节:[stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md)。
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **M1–M4 已落地 · M5–M6 规划中** |
|
||||
| 状态 | **M1–M5 已落地 · 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) |
|
||||
@@ -110,13 +110,16 @@ M6 可观测与标识 log + uuid(+ 可选 yaml)
|
||||
|
||||
---
|
||||
|
||||
### M5 — 集合算法与 CLI
|
||||
### M5 — 集合算法与 CLI — **done**
|
||||
|
||||
| 交付 | 说明 |
|
||||
|------|------|
|
||||
| `table` 或 `listx` | `sort` / `sort_by` / `unique` / `reverse`(已有 host 则接线)/ `chunk` / `zip` / `flatten` |
|
||||
| `lib/cli.mq.md` / `lib/命令行.mq.md` | 从 `sys.args` 解析 `--key value` / `--flag`;纯 mq 优先 |
|
||||
| 验收 | 一个「过滤 CSV + 排序 + 打印」脚本零插件;一个带 `--input` 的 CLI 例 |
|
||||
| `lib/table` / `表` 加厚 | `sort` / `sort_by` / `unique` / `chunk` / `zip` / `flatten`(`reverse` 已有) |
|
||||
| `lib/cli.mq.md` / `lib/命令行.mq.md` | `parse`(`--k v` / `--k=v` / `--flag`;位置参 `_`) |
|
||||
| Host | `host_list_sort*` / `unique` / `chunk` / `zip` / `flatten`、`host_cli_parse` |
|
||||
| 金样 | `table-list-mid` · `cli-sort-smoke` · `表-命令行-烟测` |
|
||||
| 文档 | [stdlib-list-cli.md](../design/stdlib-list-cli.md) · public `12-list-cli` |
|
||||
| 验收 | CSV 按键排序 + 参数解析 |
|
||||
|
||||
**刻意不做:** 泛型迭代器协议、惰性流、完整 argparse 互斥组。
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
---
|
||||
title: lib/cli
|
||||
description: Parse argv flags (Mid M5). --key value / --key=value / --flag; positionals under _.
|
||||
---
|
||||
|
||||
## parse
|
||||
+ `args`=None
|
||||
|
||||
Parse `--key value` / `--key=value` / `--flag`. A bare `--flag` must not be followed by a non-option token if you need it as boolean (put flags last, or use `--flag=true`). Positionals land under `_`.
|
||||
|
||||
**> host_cli_parse args=`args`**
|
||||
@@ -129,6 +129,49 @@ Zero-based index or `None`.
|
||||
|
||||
**> host_list_reverse list=`list`**
|
||||
|
||||
## sort
|
||||
+ `list`
|
||||
|
||||
Ascending sort (int/num/text preferred).
|
||||
|
||||
**> host_list_sort list=`list`**
|
||||
|
||||
## sort_by
|
||||
+ `list`
|
||||
+ `key`
|
||||
|
||||
Sort a list of maps by `key`.
|
||||
|
||||
**> host_list_sort_by list=`list` key=`key`**
|
||||
|
||||
## unique
|
||||
+ `list`
|
||||
|
||||
Stable unique (first wins).
|
||||
|
||||
**> host_list_unique list=`list`**
|
||||
|
||||
## chunk
|
||||
+ `list`
|
||||
+ `size`
|
||||
|
||||
**> host_list_chunk list=`list` size=`size`**
|
||||
|
||||
## zip
|
||||
+ `a`
|
||||
+ `b`
|
||||
|
||||
Pairs until the shorter list ends.
|
||||
|
||||
**> host_list_zip a=`a` b=`b`**
|
||||
|
||||
## flatten
|
||||
+ `list`
|
||||
|
||||
One-level flatten.
|
||||
|
||||
**> host_list_flatten list=`list`**
|
||||
|
||||
## clear
|
||||
+ `value`
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
---
|
||||
title: lib/命令行
|
||||
description: 解析命令行参数(中层 M5)。--键 值 / --键=值 / --开关;位置参在 _。
|
||||
---
|
||||
|
||||
## 解析
|
||||
+ `参数`=None
|
||||
|
||||
省略 `参数` 时用进程 argv(系统.参数表)。
|
||||
|
||||
**> host_cli_parse args=`参数`**
|
||||
+43
@@ -129,6 +129,49 @@ description: >-
|
||||
|
||||
**> host_list_reverse list=`list`**
|
||||
|
||||
## 排序
|
||||
+ `list`
|
||||
|
||||
升序(优先 int/num/text)。
|
||||
|
||||
**> host_list_sort list=`list`**
|
||||
|
||||
## 按键排序
|
||||
+ `list`
|
||||
+ `key`
|
||||
|
||||
对 map 列表按键排序。
|
||||
|
||||
**> host_list_sort_by list=`list` key=`key`**
|
||||
|
||||
## 去重
|
||||
+ `list`
|
||||
|
||||
保序去重(保留首次)。
|
||||
|
||||
**> host_list_unique list=`list`**
|
||||
|
||||
## 分块
|
||||
+ `list`
|
||||
+ `size`
|
||||
|
||||
**> host_list_chunk list=`list` size=`size`**
|
||||
|
||||
## 拉链
|
||||
+ `a`
|
||||
+ `b`
|
||||
|
||||
取较短长度配对。
|
||||
|
||||
**> host_list_zip a=`a` b=`b`**
|
||||
|
||||
## 展平
|
||||
+ `list`
|
||||
|
||||
一层展平。
|
||||
|
||||
**> host_list_flatten list=`list`**
|
||||
|
||||
## 清空
|
||||
+ `value`
|
||||
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@
|
||||
|
||||
官方扩展(非 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):`08-re-encoding` · `09-path-fs` · `10-hash-secrets` · `11-csv-text`(及对应中文页)。
|
||||
中层标准库(Mid):`08`–`12`(re/encoding · path/fs · hash/secrets · csv/text · list/cli;及对应中文页)。
|
||||
|
||||
**不放** `errors/`:失败样例只在 `tests/errors/`。
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
title: Mid stdlib — lists and cli
|
||||
description: table sort/unique/zip + cli.parse (Mid M5)
|
||||
import table:lib/table.mq.md
|
||||
import csv:lib/csv.mq.md
|
||||
import cli:lib/cli.mq.md
|
||||
---
|
||||
|
||||
# Sort CSV rows and parse flags
|
||||
|
||||
Zero plugins: parse CSV, sort by key, parse `--input`.
|
||||
|
||||
# main
|
||||
|
||||
*raw = "name,score\nbob,2\nalice,10\n"*
|
||||
*rows = > csv.parse text=`raw`*
|
||||
*rows = > table.sort_by list=`rows` key="name"*
|
||||
*r0 = > at value=`rows` index=0*
|
||||
> print text=`r0`[^name]
|
||||
|
||||
*args = > split value="--input,scores.csv,--pretty" sep=","*
|
||||
*flags = > cli.parse args=`args`*
|
||||
> print text=`flags`[^input]
|
||||
1. `flags`[^pretty]
|
||||
> print text=mid-m5-ok
|
||||
2. *
|
||||
> print text=mid-m5-fail
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
title: 中层标准库 — 列表与命令行
|
||||
description: 表排序/去重 + 命令行解析(中层 M5)
|
||||
导入 表:lib/表.mq.md
|
||||
导入 逗号表:lib/逗号表.mq.md
|
||||
导入 命令行:lib/命令行.mq.md
|
||||
---
|
||||
|
||||
# 排序 CSV 并解析参数
|
||||
|
||||
零插件:解析 CSV、按键排序、解析 `--input`。
|
||||
|
||||
# main
|
||||
|
||||
*raw = "name,score\nbob,2\nalice,10\n"*
|
||||
*rows = > 逗号表.解析 内容=`raw`*
|
||||
*rows = > 表.按键排序 list=`rows` key="name"*
|
||||
*r0 = > at value=`rows` index=0*
|
||||
> 打印 内容=`r0`[^name]
|
||||
|
||||
*args = > split value="--input,scores.csv,--pretty" sep=","*
|
||||
*flags = > 命令行.解析 参数=`args`*
|
||||
> 打印 内容=`flags`[^input]
|
||||
1. `flags`[^pretty]
|
||||
> 打印 内容=mid-m5-ok
|
||||
2. *
|
||||
> 打印 内容=mid-m5-fail
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
//! CLI arg parsing for Mid M5 (`lib/cli`).
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
fn as_text_list(v: &Value) -> Result<Vec<String>, String> {
|
||||
match v {
|
||||
Value::List(xs) => {
|
||||
let mut out = Vec::new();
|
||||
for x in xs {
|
||||
match x {
|
||||
Value::Text(s) => out.push(s.clone()),
|
||||
_ => return Err("cli.parse: args must be list of text".into()),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
Value::None => Ok(vec![]),
|
||||
_ => Err("cli.parse: args needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse `--key value` / `--key=value` / `--flag` / positionals into a map.
|
||||
/// Positionals are stored under key `_` as a list.
|
||||
pub fn parse(ctx: &HostContext, args: Option<&Value>) -> Result<Value, String> {
|
||||
let argv = match args {
|
||||
None | Some(Value::None) => ctx.argv.clone(),
|
||||
Some(v) => as_text_list(v)?,
|
||||
};
|
||||
let mut map: Vec<(String, Value)> = Vec::new();
|
||||
let mut positionals: Vec<Value> = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i < argv.len() {
|
||||
let a = &argv[i];
|
||||
if let Some(rest) = a.strip_prefix("--") {
|
||||
if rest.is_empty() {
|
||||
// bare `--` — remaining are positionals
|
||||
i += 1;
|
||||
while i < argv.len() {
|
||||
positionals.push(Value::Text(argv[i].clone()));
|
||||
i += 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if let Some((k, v)) = rest.split_once('=') {
|
||||
upsert(&mut map, k.to_string(), Value::Text(v.to_string()));
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let key = rest.to_string();
|
||||
if i + 1 < argv.len() && !argv[i + 1].starts_with('-') {
|
||||
upsert(&mut map, key, Value::Text(argv[i + 1].clone()));
|
||||
i += 2;
|
||||
} else {
|
||||
upsert(&mut map, key, Value::Bool(true));
|
||||
i += 1;
|
||||
}
|
||||
} else if let Some(rest) = a.strip_prefix('-') {
|
||||
// short flags: -abc → a/b/c True; -k val not special-cased beyond single letter groups
|
||||
if rest.is_empty() {
|
||||
positionals.push(Value::Text(a.clone()));
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if rest.len() == 1 && i + 1 < argv.len() && !argv[i + 1].starts_with('-') {
|
||||
upsert(&mut map, rest.to_string(), Value::Text(argv[i + 1].clone()));
|
||||
i += 2;
|
||||
} else {
|
||||
for ch in rest.chars() {
|
||||
upsert(&mut map, ch.to_string(), Value::Bool(true));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
} else {
|
||||
positionals.push(Value::Text(a.clone()));
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
if !positionals.is_empty() {
|
||||
upsert(&mut map, "_".into(), Value::List(positionals));
|
||||
}
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
|
||||
fn upsert(map: &mut Vec<(String, Value)>, key: String, value: Value) {
|
||||
if let Some((_, slot)) = map.iter_mut().find(|(k, _)| *k == key) {
|
||||
*slot = value;
|
||||
} else {
|
||||
map.push((key, value));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_flags() {
|
||||
let ctx = HostContext::default();
|
||||
let args = Value::List(vec![
|
||||
Value::Text("--input".into()),
|
||||
Value::Text("a.csv".into()),
|
||||
Value::Text("x".into()),
|
||||
Value::Text("--verbose".into()),
|
||||
]);
|
||||
let m = parse(&ctx, Some(&args)).unwrap();
|
||||
match m {
|
||||
Value::Map(entries) => {
|
||||
assert!(entries
|
||||
.iter()
|
||||
.any(|(k, v)| k == "input" && *v == Value::Text("a.csv".into())));
|
||||
assert!(entries
|
||||
.iter()
|
||||
.any(|(k, v)| k == "verbose" && *v == Value::Bool(true)));
|
||||
assert!(entries
|
||||
.iter()
|
||||
.any(|(k, v)| k == "_" && matches!(v, Value::List(_))));
|
||||
}
|
||||
_ => panic!("map"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -385,6 +385,136 @@ pub fn list_last(list: &Value) -> Result<Value, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn cmp_value(a: &Value, b: &Value) -> std::cmp::Ordering {
|
||||
use std::cmp::Ordering;
|
||||
match (a, b) {
|
||||
(Value::Int(x), Value::Int(y)) => x.cmp(y),
|
||||
(Value::Num(x), Value::Num(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
|
||||
(Value::Int(x), Value::Num(y)) => (*x as f64).partial_cmp(y).unwrap_or(Ordering::Equal),
|
||||
(Value::Num(x), Value::Int(y)) => x.partial_cmp(&(*y as f64)).unwrap_or(Ordering::Equal),
|
||||
(Value::Text(x), Value::Text(y)) => x.cmp(y),
|
||||
(Value::Bool(x), Value::Bool(y)) => x.cmp(y),
|
||||
_ => a.as_display().cmp(&b.as_display()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_sort(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = xs.clone();
|
||||
out.sort_by(cmp_value);
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_sort needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_sort_by(list: &Value, key: &Value) -> Result<Value, String> {
|
||||
let key = match key {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("sort_by key needs text".into()),
|
||||
};
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = xs.clone();
|
||||
out.sort_by(|a, b| {
|
||||
let ka = match a {
|
||||
Value::Map(m) => m
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v)
|
||||
.unwrap_or(&Value::None),
|
||||
_ => &Value::None,
|
||||
};
|
||||
let kb = match b {
|
||||
Value::Map(m) => m
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v)
|
||||
.unwrap_or(&Value::None),
|
||||
_ => &Value::None,
|
||||
};
|
||||
cmp_value(ka, kb)
|
||||
});
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_sort_by needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_unique(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = Vec::new();
|
||||
for x in xs {
|
||||
if !out.iter().any(|y| y == x) {
|
||||
out.push(x.clone());
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_unique needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_chunk(list: &Value, size: &Value) -> Result<Value, String> {
|
||||
let n = match size {
|
||||
Value::Int(i) if *i > 0 => *i as usize,
|
||||
Value::Int(_) => return Err("chunk size must be positive".into()),
|
||||
_ => return Err("chunk size needs int".into()),
|
||||
};
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < xs.len() {
|
||||
let end = (i + n).min(xs.len());
|
||||
out.push(Value::List(xs[i..end].to_vec()));
|
||||
i = end;
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_chunk needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_zip(a: &Value, b: &Value) -> Result<Value, String> {
|
||||
let (aa, bb) = match (a, b) {
|
||||
(Value::List(x), Value::List(y)) => (x, y),
|
||||
(Value::None, Value::List(y)) => (&Vec::new(), y),
|
||||
(Value::List(x), Value::None) => (x, &Vec::new()),
|
||||
(Value::None, Value::None) => return Ok(Value::List(vec![])),
|
||||
_ => return Err("list_zip needs two lists".into()),
|
||||
};
|
||||
let n = aa.len().min(bb.len());
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
out.push(Value::List(vec![aa[i].clone(), bb[i].clone()]));
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
|
||||
pub fn list_flatten(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = Vec::new();
|
||||
for x in xs {
|
||||
match x {
|
||||
Value::List(inner) => out.extend(inner.iter().cloned()),
|
||||
other => out.push(other.clone()),
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_flatten needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn collection_clear(value: &Value) -> Result<Value, String> {
|
||||
match value {
|
||||
Value::List(_) | Value::None => Ok(Value::List(vec![])),
|
||||
|
||||
+49
-2
@@ -3,8 +3,8 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::{
|
||||
csv, encoding, fs, hash, json, math, net, path, re, secrets, sys, text_ops, time, writeback,
|
||||
HostContext,
|
||||
cli, csv, encoding, fs, hash, json, math, net, path, re, secrets, sys, text_ops, time,
|
||||
writeback, HostContext,
|
||||
};
|
||||
#[cfg(feature = "exec-host")]
|
||||
use crate::host::{foreign, subtask};
|
||||
@@ -166,6 +166,13 @@ pub enum HostFn {
|
||||
TextPad = 157,
|
||||
CsvParse = 158,
|
||||
CsvStringify = 159,
|
||||
ListSort = 160,
|
||||
ListSortBy = 161,
|
||||
ListUnique = 162,
|
||||
ListChunk = 163,
|
||||
ListZip = 164,
|
||||
ListFlatten = 165,
|
||||
CliParse = 166,
|
||||
}
|
||||
|
||||
|
||||
@@ -322,6 +329,13 @@ impl HostFn {
|
||||
157 => Self::TextPad,
|
||||
158 => Self::CsvParse,
|
||||
159 => Self::CsvStringify,
|
||||
160 => Self::ListSort,
|
||||
161 => Self::ListSortBy,
|
||||
162 => Self::ListUnique,
|
||||
163 => Self::ListChunk,
|
||||
164 => Self::ListZip,
|
||||
165 => Self::ListFlatten,
|
||||
166 => Self::CliParse,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -481,6 +495,13 @@ impl HostFn {
|
||||
"host_text_pad" | "text_pad" => Self::TextPad,
|
||||
"host_csv_parse" | "csv_parse" => Self::CsvParse,
|
||||
"host_csv_stringify" | "csv_stringify" => Self::CsvStringify,
|
||||
"host_list_sort" | "list_sort" => Self::ListSort,
|
||||
"host_list_sort_by" | "list_sort_by" => Self::ListSortBy,
|
||||
"host_list_unique" | "list_unique" => Self::ListUnique,
|
||||
"host_list_chunk" | "list_chunk" => Self::ListChunk,
|
||||
"host_list_zip" | "list_zip" => Self::ListZip,
|
||||
"host_list_flatten" | "list_flatten" => Self::ListFlatten,
|
||||
"host_cli_parse" | "cli_parse" => Self::CliParse,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -627,6 +648,13 @@ impl HostFn {
|
||||
Self::TextPad => "host_text_pad",
|
||||
Self::CsvParse => "host_csv_parse",
|
||||
Self::CsvStringify => "host_csv_stringify",
|
||||
Self::ListSort => "host_list_sort",
|
||||
Self::ListSortBy => "host_list_sort_by",
|
||||
Self::ListUnique => "host_list_unique",
|
||||
Self::ListChunk => "host_list_chunk",
|
||||
Self::ListZip => "host_list_zip",
|
||||
Self::ListFlatten => "host_list_flatten",
|
||||
Self::CliParse => "host_cli_parse",
|
||||
Self::WritebackRecord => "host_writeback_record",
|
||||
Self::WritebackGet => "host_writeback_get",
|
||||
Self::WritebackClear => "host_writeback_clear",
|
||||
@@ -741,6 +769,11 @@ impl HostFn {
|
||||
Self::TextPad => &["text", "width"],
|
||||
Self::CsvParse => &["text"],
|
||||
Self::CsvStringify => &["rows"],
|
||||
Self::ListSort | Self::ListUnique | Self::ListFlatten => &["list"],
|
||||
Self::ListSortBy => &["list", "key"],
|
||||
Self::ListChunk => &["list", "size"],
|
||||
Self::ListZip => &["a", "b"],
|
||||
Self::CliParse => &[],
|
||||
Self::WritebackRecord => &["value"],
|
||||
Self::WritebackGet | Self::WritebackClear => &[],
|
||||
Self::WritebackList => &[],
|
||||
@@ -778,6 +811,7 @@ impl HostFn {
|
||||
Self::SecretsTokenHex | Self::SecretsTokenUrlsafe => &["n"],
|
||||
Self::TextReplace => &["count"],
|
||||
Self::TextPad => &["fill", "align"],
|
||||
Self::CliParse => &["args"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
@@ -1207,6 +1241,19 @@ pub fn call_host(
|
||||
),
|
||||
HostFn::CsvParse => csv::parse(require(bound, "text")?),
|
||||
HostFn::CsvStringify => csv::stringify(require(bound, "rows")?),
|
||||
HostFn::ListSort => super::collection::list_sort(require(bound, "list")?),
|
||||
HostFn::ListSortBy => {
|
||||
super::collection::list_sort_by(require(bound, "list")?, require(bound, "key")?)
|
||||
}
|
||||
HostFn::ListUnique => super::collection::list_unique(require(bound, "list")?),
|
||||
HostFn::ListChunk => {
|
||||
super::collection::list_chunk(require(bound, "list")?, require(bound, "size")?)
|
||||
}
|
||||
HostFn::ListZip => {
|
||||
super::collection::list_zip(require(bound, "a")?, require(bound, "b")?)
|
||||
}
|
||||
HostFn::ListFlatten => super::collection::list_flatten(require(bound, "list")?),
|
||||
HostFn::CliParse => cli::parse(ctx, bound.get("args")),
|
||||
HostFn::OuterCallLine => Ok(Value::Int(
|
||||
ctx.call_site_lines
|
||||
.first()
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
pub mod agent_rt;
|
||||
pub mod collection;
|
||||
mod dispatch;
|
||||
mod cli;
|
||||
mod csv;
|
||||
mod encoding;
|
||||
pub mod event_bus;
|
||||
|
||||
@@ -1147,6 +1147,27 @@ fn lib_csv_smoke_zh() {
|
||||
assert_out("tests/lib/逗号表-烟测.mq.md", "1\n1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_table_list_mid() {
|
||||
assert_out(
|
||||
"tests/lib/table-list-mid.mq.md",
|
||||
"1,1,2,3\n1,2,3\n2\n2\na,b,1,2,3",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_cli_sort_smoke() {
|
||||
assert_out(
|
||||
"tests/lib/cli-sort-smoke.mq.md",
|
||||
"alice\ndata.csv\nTrue\nrest",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_cli_zh_smoke() {
|
||||
assert_out("tests/lib/表-命令行-烟测.mq.md", "a,b,c\n1\nTrue");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_re_smoke() {
|
||||
assert_out(
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
title: table sort_by + cli
|
||||
import table:lib/table.mq.md
|
||||
import csv:lib/csv.mq.md
|
||||
import cli:lib/cli.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*raw = "name,score\nbob,2\nalice,10\n"*
|
||||
*rows = > csv.parse text=`raw`*
|
||||
*rows = > table.sort_by list=`rows` key="name"*
|
||||
*r0 = > at value=`rows` index=0*
|
||||
> print text=`r0`[^name]
|
||||
|
||||
*args = > split value="--input,data.csv,rest,--verbose" sep=","*
|
||||
*flags = > cli.parse args=`args`*
|
||||
> print text=`flags`[^input]
|
||||
> print text=`flags`[^verbose]
|
||||
*pos = `flags`[^_]*
|
||||
*p0 = > at value=`pos` index=0*
|
||||
> print text=`p0`
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
title: table list mid smoke
|
||||
import table:lib/table.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*xs = > split value="3,1,2,1" sep=","*
|
||||
*xs = > table.sort list=`xs`*
|
||||
*s = > join value=`xs` sep=","*
|
||||
> print text=`s`
|
||||
|
||||
*u = > table.unique list=`xs`*
|
||||
*uj = > join value=`u` sep=","*
|
||||
> print text=`uj`
|
||||
|
||||
*ch = > table.chunk list=`xs` size=2*
|
||||
*n = > len `ch`*
|
||||
> print text=`n`
|
||||
|
||||
*a = > split value="a,b" sep=","*
|
||||
*b = > split value="1,2,3" sep=","*
|
||||
*z = > table.zip a=`a` b=`b`*
|
||||
*zn = > len `z`*
|
||||
> print text=`zn`
|
||||
|
||||
*nested = > table.append list=None item=`a`*
|
||||
*nested = > table.append list=`nested` item=`b`*
|
||||
*flat = > table.flatten list=`nested`*
|
||||
*fj = > join value=`flat` sep=","*
|
||||
> print text=`fj`
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
title: 表与命令行 烟测
|
||||
导入 表:lib/表.mq.md
|
||||
导入 命令行:lib/命令行.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*xs = > split value="c,a,b" sep=","*
|
||||
*xs = > 表.排序 list=`xs`*
|
||||
*s = > join value=`xs` sep=","*
|
||||
> 打印 内容=`s`
|
||||
|
||||
*args = > split value="--x,1,--flag" sep=","*
|
||||
*flags = > 命令行.解析 参数=`args`*
|
||||
> 打印 内容=`flags`[^x]
|
||||
> 打印 内容=`flags`[^flag]
|
||||
Reference in new issue
Block a user