diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index e367a3c..caf087d 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -134,6 +134,7 @@ title: example - Design: [module-namespace.md](../../doc/design/module-namespace.md). - Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm` / `add agent` (see `doc/design/ext-cli.md`). `ext/llm` — chat; `ext/agent` — document-driven agents: **step** (default writeback) / **plan** workbook ([ext-agent.md](../../doc/design/ext-agent.md), [ext-agent-plan.md](../../doc/design/ext-agent-plan.md)). - Native plugins: `lib/plugin` — `## load` / `unload` / `list`. C ABI: `include/marqdo_abi.h`. +- Prefer `table.put` / `表.改` for list/map element updates; keep `json` for parse/stringify/quote (see `doc/design/stdlib-table.md`). - Builtins (no import): `print`/`打印`, `input`/`输入`, `len`/`长度`, `str`/`文本`, `int`/`整数`; literals `True`/`真`, `False`/`假`, `None`/`空`; logic `and`/`且`, `or`/`或`, `not`/`非`. Stdlib map: [reference.md](reference.md). diff --git a/.cursor/skills/marqdo/reference.md b/.cursor/skills/marqdo/reference.md index 33d4ff5..36e70b1 100644 --- a/.cursor/skills/marqdo/reference.md +++ b/.cursor/skills/marqdo/reference.md @@ -43,7 +43,7 @@ Import one file; use **that** file’s function names. | EN import | ZH import | Typical APIs (EN / ZH) | |-----------|-----------|-------------------------| | `lib/text.mq.md` | `lib/文本.mq.md` | text helpers / 去空白·拆分·拼接… | -| `lib/table.mq.md` | `lib/表.mq.md` | table/rows helpers | +| `lib/table.mq.md` | `lib/表.mq.md` | `put`/`改` + list/map(见 `doc/design/stdlib-table.md`) | | `lib/fs.mq.md` | `lib/文件.mq.md` | filesystem | | `lib/sys.mq.md` | `lib/系统.mq.md` | process / cwd / load_dotenv | | `lib/plugin.mq.md` | `lib/插件.mq.md` | load native ABI plugins (`doc/design/ext-abi.md`) | diff --git a/doc/design/stdlib-i18n.md b/doc/design/stdlib-i18n.md index 62c5502..149cc5e 100644 --- a/doc/design/stdlib-i18n.md +++ b/doc/design/stdlib-i18n.md @@ -28,7 +28,7 @@ |------|-------------------| | `> lib/text.mq.md` | `trim` · `split` · `join` | | `> lib/文本.mq.md` | `去空白` · `拆分` · `拼接` | -| `> lib/table.mq.md` | `rows` · `row_at` | +| `> lib/table.mq.md` | `put` · `rows` · `row_at` · list/map(见 [stdlib-table.md](stdlib-table.md)) | | `> lib/表.mq.md` | `行数` · `取行` | 示例: diff --git a/doc/design/stdlib-modules.md b/doc/design/stdlib-modules.md index 0df5967..5740f38 100644 --- a/doc/design/stdlib-modules.md +++ b/doc/design/stdlib-modules.md @@ -16,7 +16,7 @@ | 模块族 | 英文库 | 中文库 | 状态 | |--------|--------|--------|------| | 文本 | `lib/text.mq.md` | `lib/文本.mq.md` | 已有 | -| 表 | `lib/table.mq.md` | `lib/表.mq.md` | 已有 | +| 表 | `lib/table.mq.md` | `lib/表.mq.md` | 已有(`put`/`改` + list/map;见 [stdlib-table.md](stdlib-table.md)) | | 文件 | `lib/fs.mq.md` | `lib/文件.mq.md` | 已有 | | 系统 | `lib/sys.mq.md` | `lib/系统.mq.md` | 已有(含 `load_dotenv`) | | 时间 | `lib/time.mq.md` | `lib/时间.mq.md` | 已有 | diff --git a/doc/design/stdlib-table.md b/doc/design/stdlib-table.md new file mode 100644 index 0000000..cef0947 --- /dev/null +++ b/doc/design/stdlib-table.md @@ -0,0 +1,82 @@ +# `lib/table` / `lib/表` — 列表与字典 + +| | | +|---|---| +| 状态 | **已落地**(可用级集合 API) | +| 相关 | [stdlib.md](stdlib.md) · [stdlib-modules.md](stdlib-modules.md) · [table-cell-expressions.md](table-cell-expressions.md) · [roadmap/tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md) | + +--- + +## 1. 读写对 + +| 读 | 写 | +|----|----| +| 脚注 `` `xs`[^1] `` / `` `m`[^key] `` / 嵌套 `` `m`[^a][^1] `` | **`table.put` / `表.改`** | + +`put` / `改` 的 `at=`(`于=`)与脚注同构:文本键、**1-based** 整数下标,或键/下标组成的路径列表。 + +```markdown +--- +> lib/table.mq.md +--- + +# main + +*`h` = > table.put in=None at=Authorization value=Bearer-x* + +`xs` = + +| v | +|---| +| a | +| b | + +*`xs` = > table.put in=`xs` at=1 value=A* +``` + +`in=None` 且 `at=` 为单个文本键 → 新建单键字典。值一律不可变更新(返回新集合)。 + +--- + +## 2. 索引约定 + +| API | 基数 | +|-----|------| +| `put` / `改` 路径中的整数;脚注 `[^n]` | **1-based** | +| `at` / `row_at` / `set_at` / `insert` / `remove_at` / `slice` / `index_of` | **0-based** | + +--- + +## 3. API 摘要(EN ↔ ZH) + +| EN | ZH | 说明 | +|----|----|------| +| `put` | `改` | 按路径改一元(首选写入) | +| `len` / `rows` | `长度` / `行数` | 长度 | +| `at` / `row_at` | `取` / `取行` | 0-based 取元 | +| `append` / `prepend` / `concat` | `追加` / `前插` / `拼接` | 列表 | +| `insert` / `set_at` / `remove_at` / `pop` | `插入` / `改位` / `删位` / `弹出` | 列表位操作 | +| `first` / `last` / `slice` | `首` / `末` / `切片` | | +| `contains` / `index_of` / `reverse` | `含有` / `下标` / `反转` | | +| `clear` | `清空` | 列表或字典 | +| `get` / `set` / `delete` / `has` | `取键` / `设` / `删键` / `有键` | 浅层字典 | +| `keys` / `values` / `items` / `merge` / `size` | `键表` / `值表` / `项表` / `合并` / `键数` | | +| `empty_list` / `empty_map` | `空表` / `空字典` | | + +嵌套改写优先 `put`/`改`;`set`/`set_at` 仅浅层。 + +--- + +## 4. 与 `lib/json` + +| 用途 | 用 | +|------|----| +| 解析 / 序列化 / `quote` | `json.parse` · `json.stringify` · `json.quote` | +| 集合读写 | **`table.*` / `表.*`** | +| 兼容 | `json.set` / `json.append` / `json.get` / `json.keys` 仍为别名,新代码勿依赖 | + +--- + +## 5. 宿主 + +`host_collection_put` + list/map 原语(见 `src/host/collection.rs`)。作者面经 `lib/table` / `lib/表` 调用,不直接写 `host_*`。 diff --git a/doc/design/stdlib.md b/doc/design/stdlib.md index 921627d..70e8c9d 100644 --- a/doc/design/stdlib.md +++ b/doc/design/stdlib.md @@ -77,8 +77,8 @@ Frontmatter 导入**绑定库名**(默认 = 文件名茎;`as` / `作为` 可 | `lib/subtask.mq.md` / `lib/子任务.mq.md` | `spawn` `poll` `wait` `kill` `wait_all` | | `lib/text.mq.md` | `str_trim` `str_split` `str_join` | | `lib/文本.mq.md` | `去空白` `拆分` `拼接` | -| `lib/table.mq.md` | `rows` `row_at` | -| `lib/表.mq.md` | `行数` `取行` | +| `lib/table.mq.md` | `put` 为首选写入;`rows`/`row_at` 及完整 list/map API — 见 [stdlib-table.md](stdlib-table.md) | +| `lib/表.mq.md` | `改` 为首选写入;`行数`/`取行` 及完整 list/map API | 完整清单见 [stdlib-modules.md](stdlib-modules.md)。 diff --git a/doc/design/view.md b/doc/design/view.md index 623ac44..4e85ade 100644 --- a/doc/design/view.md +++ b/doc/design/view.md @@ -90,8 +90,16 @@ marqdo view output tests/structure/hello.mq.md -o /tmp/hello-doc ## 4. 信息架构 -侧栏文件索引 + 主区:结构(AST+注释;旁侧函数大纲可搜索)· 执行 · 源码。表达式为表面语法。 -**断点调试**不在 view 内,见 [`marqdo debug`](view-debug.md)。 +侧栏文件索引 + 主区:结构(AST+注释)· 执行 · 源码。结构旁**右侧栏**(现有 outline 槽)为: + +| 区块 | 内容 | +|------|------| +| **Functions** | 原函数大纲 + 搜索;可折叠(默认展开) | +| **Variables** | 跑完后的入口(`# main`)顶层绑定只读快照;List/Map/`@` 行向渲成 HTML 表;可折叠(默认展开) | + +view Variables ≠ debug Variables:前者是跑后快照,后者是暂停时的 locals。`--no-exec` 时 Variables 显示 skipped。Live `/api/run` 终态帧可带 `bindings_html` 刷新该面板。 + +表达式为表面语法。**断点调试**不在 view 内,见 [`marqdo debug`](view-debug.md)。 --- diff --git a/ext/ai/llm.mq.md b/ext/ai/llm.mq.md index 922bcdb..904f41d 100644 --- a/ext/ai/llm.mq.md +++ b/ext/ai/llm.mq.md @@ -4,6 +4,7 @@ description: OpenAI-compatible LLM object (English). Import ext/ai/llm.mq.md. > lib/sys.mq.md > lib/net.mq.md > lib/json.mq.md +> lib/table.mq.md --- ## load_env @@ -18,14 +19,14 @@ Load `.env` from cwd (optional named arg `path=`). Does not override existing va Reduce a `complete stream=True` event list to the final `done.result` text (or `error.message`). Unknown event types abort. -*answer = "" * +*answer = ""* - [ev](events) - *t = ev[^type] * + *t = ev[^type]* 1. `t` == "done" - *answer = ev[^result] * + *answer = ev[^result]* 2. `t` == "error" - *answer = ev[^message] * + *answer = ev[^message]* 3. `t` == "delta" 4. * > print text=ext/ai/llm: unexpected SSE event type @@ -38,25 +39,25 @@ Reduce a `complete stream=True` event list to the final `done.result` text (or ` Construct an LLM handle from `OPENAI_*` / `MARQDO_LLM_*`. -*api_key = > sys.env_get name=OPENAI_API_KEY * +*api_key = > sys.env_get name=OPENAI_API_KEY* 1. not `api_key` - *api_key = > sys.env_get name=MARQDO_LLM_API_KEY * + *api_key = > sys.env_get name=MARQDO_LLM_API_KEY* 1. not `api_key` > print text=ext/ai/llm: set OPENAI_API_KEY or MARQDO_LLM_API_KEY > sys.exit code=1 -*base_url = > sys.env_get name=OPENAI_BASE_URL * +*base_url = > sys.env_get name=OPENAI_BASE_URL* 1. not `base_url` - *base_url = > sys.env_get name=MARQDO_LLM_BASE_URL * + *base_url = > sys.env_get name=MARQDO_LLM_BASE_URL* 1. not `base_url` - *base_url = "https://api.openai.com/v1" * + *base_url = "https://api.openai.com/v1"* -*model = > sys.env_get name=OPENAI_MODEL * +*model = > sys.env_get name=OPENAI_MODEL* 1. not `model` - *model = > sys.env_get name=MARQDO_LLM_MODEL * + *model = > sys.env_get name=MARQDO_LLM_MODEL* 1. not `model` - *model = "gpt-4o-mini" * + *model = "gpt-4o-mini"* `h` = @@ -73,19 +74,17 @@ Construct an LLM handle from `OPENAI_*` / `MARQDO_LLM_*`. Chat completion using `self` handle fields. -Wire body is `{model, messages:[{role,content}], stream?}` — message row is a table; `stream` flag still needs a map set when true. Headers use one `json.set` because a 1-col table is a List, not a Map. +Wire body is `{model, messages:[{role,content}], stream?}`. Messages are an `@` row table; headers and optional `stream` use `table.put`. `json` is only for stringify/parse. -*url = self[^base_url] + self[^suffix] * -*auth = self[^bearer] + self[^api_key] * -*headers = > json.set map=None key=Authorization value=`auth` * +*url = self[^base_url] + self[^suffix]* +*auth = self[^bearer] + self[^api_key]* +*headers = > table.put in=None at=Authorization value=`auth`* -`msg` = +`messages` = -| role | content | -|------|---------| -| user | `prompt` | - -*messages = > json.append list=None item=`msg` * +| @ | role | content | +|---|------|---------| +| 1 | user | `prompt` | `req` = @@ -94,9 +93,9 @@ Wire body is `{model, messages:[{role,content}], stream?}` — message row is a | self[^model] | `messages` | 1. `stream` - *req = > json.set map=`req` key=stream value=True * - *body = > json.stringify value=`req` * - *resp = > net.http_post_sse url=`url` body=`body` headers=`headers` echo=`echo` * + *req = > table.put in=`req` at=stream value=True* + *body = > json.stringify value=`req`* + *resp = > net.http_post_sse url=`url` body=`body` headers=`headers` echo=`echo`* 1. resp[^status] == 200 **resp[^events]** 2. * @@ -104,10 +103,10 @@ Wire body is `{model, messages:[{role,content}], stream?}` — message row is a > print text=resp[^status] > sys.exit code=1 2. * - *body = > json.stringify value=`req` * - *resp = > net.http_post url=`url` body=`body` headers=`headers` * + *body = > json.stringify value=`req`* + *resp = > net.http_post url=`url` body=`body` headers=`headers`* 1. resp[^status] == 200 - *data = > json.parse text=resp[^body] * + *data = > json.parse text=resp[^body]* **data[^choices][^1][^message][^content]** 2. * > print text=ext/ai/llm: HTTP error diff --git a/ext/ai/大模型.mq.md b/ext/ai/大模型.mq.md index 00ab50e..dd4a88e 100644 --- a/ext/ai/大模型.mq.md +++ b/ext/ai/大模型.mq.md @@ -4,6 +4,7 @@ description: OpenAI 兼容大模型对象(中文)。导入 ext/ai/大模型. > lib/系统.mq.md > lib/网络.mq.md > lib/json.mq.md +> lib/表.mq.md --- ## 加载环境 @@ -18,14 +19,14 @@ description: OpenAI 兼容大模型对象(中文)。导入 ext/ai/大模型. 把 `运行 流式=真` 的事件列表收成最终 `done.result`(或 `error.message`)。未知事件类型直接失败。 -*answer = "" * +*answer = ""* - [ev](事件) - *t = ev[^type] * + *t = ev[^type]* 1. `t` == "done" - *answer = ev[^result] * + *answer = ev[^result]* 2. `t` == "error" - *answer = ev[^message] * + *answer = ev[^message]* 3. `t` == "delta" 4. * > 打印 内容=ext/ai/大模型: 未预期的 SSE 事件类型 @@ -38,25 +39,25 @@ description: OpenAI 兼容大模型对象(中文)。导入 ext/ai/大模型. 从 `OPENAI_*` / `MARQDO_LLM_*` 构造句柄。 -*api_key = > 系统.取环境 名=OPENAI_API_KEY * +*api_key = > 系统.取环境 名=OPENAI_API_KEY* 1. 非 `api_key` - *api_key = > 系统.取环境 名=MARQDO_LLM_API_KEY * + *api_key = > 系统.取环境 名=MARQDO_LLM_API_KEY* 1. 非 `api_key` > 打印 内容=ext/ai/大模型: 请设置 OPENAI_API_KEY 或 MARQDO_LLM_API_KEY > 系统.退出 码=1 -*base_url = > 系统.取环境 名=OPENAI_BASE_URL * +*base_url = > 系统.取环境 名=OPENAI_BASE_URL* 1. 非 `base_url` - *base_url = > 系统.取环境 名=MARQDO_LLM_BASE_URL * + *base_url = > 系统.取环境 名=MARQDO_LLM_BASE_URL* 1. 非 `base_url` - *base_url = "https://api.openai.com/v1" * + *base_url = "https://api.openai.com/v1"* -*model = > 系统.取环境 名=OPENAI_MODEL * +*model = > 系统.取环境 名=OPENAI_MODEL* 1. 非 `model` - *model = > 系统.取环境 名=MARQDO_LLM_MODEL * + *model = > 系统.取环境 名=MARQDO_LLM_MODEL* 1. 非 `model` - *model = "gpt-4o-mini" * + *model = "gpt-4o-mini"* `h` = @@ -73,19 +74,17 @@ description: OpenAI 兼容大模型对象(中文)。导入 ext/ai/大模型. 使用 `自` 句柄字段做聊天补全。 -线上 body 为 `{model, messages:[{role,content}], stream?}`——消息行用表;`流式` 为真时仍需一次 `json.set`。单键 headers 用一次 `json.set`(单列表是 List 不是 Map)。 +线上 body 为 `{model, messages:[{role,content}], stream?}`。消息用 `@` 行向表;headers 与可选 `stream` 用 `表.改`。`json` 只做 stringify/parse。 -*url = 自[^base_url] + 自[^suffix] * -*auth = 自[^bearer] + 自[^api_key] * -*headers = > json.set map=None key=Authorization value=`auth` * +*url = 自[^base_url] + 自[^suffix]* +*auth = 自[^bearer] + 自[^api_key]* +*headers = > 表.改 入=None 于=Authorization 值=`auth`* -`msg` = +`messages` = -| role | content | -|------|---------| -| user | `提示` | - -*messages = > json.append list=None item=`msg` * +| @ | role | content | +|---|------|---------| +| 1 | user | `提示` | `req` = @@ -94,9 +93,9 @@ description: OpenAI 兼容大模型对象(中文)。导入 ext/ai/大模型. | 自[^model] | `messages` | 1. `流式` - *req = > json.set map=`req` key=stream value=True * - *body = > json.stringify value=`req` * - *resp = > 网络.提交流式 地址=`url` 内容=`body` headers=`headers` 打印增量=`打印增量` * + *req = > 表.改 入=`req` 于=stream 值=True* + *body = > json.stringify value=`req`* + *resp = > 网络.提交流式 地址=`url` 内容=`body` headers=`headers` 打印增量=`打印增量`* 1. resp[^status] == 200 **resp[^events]** 2. * @@ -104,10 +103,10 @@ description: OpenAI 兼容大模型对象(中文)。导入 ext/ai/大模型. > 打印 内容=resp[^status] > 系统.退出 码=1 2. * - *body = > json.stringify value=`req` * - *resp = > 网络.提交 地址=`url` 内容=`body` headers=`headers` * + *body = > json.stringify value=`req`* + *resp = > 网络.提交 地址=`url` 内容=`body` headers=`headers`* 1. resp[^status] == 200 - *data = > json.parse text=resp[^body] * + *data = > json.parse text=resp[^body]* **data[^choices][^1][^message][^content]** 2. * > 打印 内容=ext/ai/大模型: HTTP 错误 diff --git a/lib/table.mq.md b/lib/table.mq.md index 05cca86..9ea2e90 100644 --- a/lib/table.mq.md +++ b/lib/table.mq.md @@ -1,15 +1,204 @@ --- title: lib/table -description: English list helpers over len / at (prefer footnote index for one-shots) +description: >- + List and map helpers. Prefer put (1-based path, same as footnotes); at/set_at/slice + are 0-based. json is for parse/stringify. --- +## put + + `in` + + `at` + + `value` + +Directly update one element. `at=` is a text key, a **1-based** list index, or a list path of keys/indices (same nesting as footnotes). + +**> host_collection_put in=`in` at=`at` value=`value`** + +## len + + `xs` + +**> len `xs`** + ## rows + `xs` **> len `xs`** +## at + + `xs` + + `i` + +Index is zero-based (same as builtin `at`). Out of range → `None`. + +**> at value=`xs` index=`i`** + ## row_at + `xs` + `i` **> at value=`xs` index=`i`** + +## append + + `list` + + `item` + +**> host_list_append list=`list` item=`item`** + +## prepend + + `list` + + `item` + +**> host_list_prepend list=`list` item=`item`** + +## concat + + `a` + + `b` + +**> host_list_concat a=`a` b=`b`** + +## insert + + `list` + + `index` + + `item` + +Index is zero-based (may insert at `len` to append). + +**> host_list_insert list=`list` index=`index` item=`item`** + +## set_at + + `list` + + `index` + + `item` + +Zero-based replace. Prefer `put` with 1-based index for author-facing edits. + +**> host_list_set_at list=`list` index=`index` item=`item`** + +## remove_at + + `list` + + `index` + +**> host_list_remove_at list=`list` index=`index`** + +## pop + + `list` + +Drop the last item (errors if empty). Use `last` first when you need the removed value. + +*`n` = > len `list`* +1. `n` > 0 + **> host_list_remove_at list=`list` index=`n` - 1** +2. * + **> host_list_remove_at list=`list` index=0** + +## first + + `list` + +**> host_list_first list=`list`** + +## last + + `list` + +**> host_list_last list=`list`** + +## slice + + `list` + + `start` + + `end`=None + +Zero-based half-open range from `start` to `end`. + +**> host_list_slice list=`list` start=`start` end=`end`** + +## contains + + `list` + + `item` + +**> host_list_contains list=`list` item=`item`** + +## index_of + + `list` + + `item` + +Zero-based index or `None`. + +**> host_list_index_of list=`list` item=`item`** + +## reverse + + `list` + +**> host_list_reverse list=`list`** + +## clear + + `value` + +Empty list or empty map (by type). + +**> host_collection_clear value=`value`** + +## get + + `map` + + `key` + +Missing key → `None`. + +**> host_map_get map=`map` key=`key`** + +## set + + `map` + + `key` + + `value` + +Shallow map update. Prefer `put` for nested paths. + +**> host_map_set map=`map` key=`key` value=`value`** + +## delete + + `map` + + `key` + +**> host_map_delete map=`map` key=`key`** + +## has + + `map` + + `key` + +**> host_map_has map=`map` key=`key`** + +## keys + + `map` + +**> host_map_keys map=`map`** + +## values + + `map` + +**> host_map_values map=`map`** + +## items + + `map` + +Rows shaped as key/value maps. + +**> host_map_items map=`map`** + +## merge + + `a` + + `b` + +Right-hand keys win. + +**> host_map_merge a=`a` b=`b`** + +## size + + `map` + +**> host_map_size map=`map`** + +## empty_list + +**> host_list_concat a=None b=None** + +## empty_map + +**> host_map_merge a=None b=None** diff --git a/lib/表.mq.md b/lib/表.mq.md index 9623e30..4e925af 100644 --- a/lib/表.mq.md +++ b/lib/表.mq.md @@ -1,15 +1,202 @@ --- title: lib/表 -description: 中文表库:行数 / 取行 +description: >- + 列表与字典。优先用「改」(路径 1-based,与脚注同构);取/改位/切片为 0-based。 + json 只管解析/序列化。 --- +## 改 + + `入` + + `于` + + `值` + +直接改某一元。`于=` 为文本键、**1-based** 下标,或键/下标组成的路径列表(与脚注嵌套同构)。 + +**> host_collection_put in=`入` at=`于` value=`值`** + +## 长度 + + `xs` + +**> len `xs`** + ## 行数 + `xs` **> len `xs`** +## 取 + + `xs` + + `i` + +下标从零起(与内置 `at` 相同)。越界 → `None`。 + +**> at value=`xs` index=`i`** + ## 取行 + `xs` + `i` **> at value=`xs` index=`i`** + +## 追加 + + `list` + + `item` + +**> host_list_append list=`list` item=`item`** + +## 前插 + + `list` + + `item` + +**> host_list_prepend list=`list` item=`item`** + +## 拼接 + + `a` + + `b` + +**> host_list_concat a=`a` b=`b`** + +## 插入 + + `list` + + `index` + + `item` + +下标从零起。 + +**> host_list_insert list=`list` index=`index` item=`item`** + +## 改位 + + `list` + + `index` + + `item` + +从零起替换;日常嵌套改写请用「改」。 + +**> host_list_set_at list=`list` index=`index` item=`item`** + +## 删位 + + `list` + + `index` + +**> host_list_remove_at list=`list` index=`index`** + +## 弹出 + + `list` + +去掉末项(空表报错)。需要末值时先「末」。 + +*`n` = > len `list`* +1. `n` > 0 + **> host_list_remove_at list=`list` index=`n` - 1** +2. * + **> host_list_remove_at list=`list` index=0** + +## 首 + + `list` + +**> host_list_first list=`list`** + +## 末 + + `list` + +**> host_list_last list=`list`** + +## 切片 + + `list` + + `start` + + `end`=None + +从零起的半开区间,从 `start` 到 `end`。 + +**> host_list_slice list=`list` start=`start` end=`end`** + +## 含有 + + `list` + + `item` + +**> host_list_contains list=`list` item=`item`** + +## 下标 + + `list` + + `item` + +从零起的下标;没有 → `None`。 + +**> host_list_index_of list=`list` item=`item`** + +## 反转 + + `list` + +**> host_list_reverse list=`list`** + +## 清空 + + `value` + +**> host_collection_clear value=`value`** + +## 取键 + + `map` + + `key` + +缺键 → `None`。 + +**> host_map_get map=`map` key=`key`** + +## 设 + + `map` + + `key` + + `value` + +浅层设键;嵌套请用「改」。 + +**> host_map_set map=`map` key=`key` value=`value`** + +## 删键 + + `map` + + `key` + +**> host_map_delete map=`map` key=`key`** + +## 有键 + + `map` + + `key` + +**> host_map_has map=`map` key=`key`** + +## 键表 + + `map` + +**> host_map_keys map=`map`** + +## 值表 + + `map` + +**> host_map_values map=`map`** + +## 项表 + + `map` + +键值对行表。 + +**> host_map_items map=`map`** + +## 合并 + + `a` + + `b` + +右侧覆盖左侧。 + +**> host_map_merge a=`a` b=`b`** + +## 键数 + + `map` + +**> host_map_size map=`map`** + +## 空表 + +**> host_list_concat a=None b=None** + +## 空字典 + +**> host_map_merge a=None b=None** diff --git a/public/stdlib/table.mq.md b/public/stdlib/table.mq.md index 7219064..17a62b4 100644 --- a/public/stdlib/table.mq.md +++ b/public/stdlib/table.mq.md @@ -1,12 +1,14 @@ --- -title: lib/table — lists -description: Row count and index helpers +title: lib/table — collections +description: put, append, and map helpers > lib/table.mq.md --- # main -Import lib/table.mq.md. Functions: rows(xs), row_at(xs, i). Single-column tables are lists; multi-column tables are maps (see structure/07-map). Prefer `` `xs`[^1] `` for 1-based index; `row_at` stays 0-based. +Prefer `table.put` for element updates (`at=` text key, **1-based** int, or list path). Use `json` for parse/stringify only. + +*`h` = > table.put in=None at=Authorization value=Bearer-demo* `xs` = @@ -15,10 +17,9 @@ Import lib/table.mq.md. Functions: rows(xs), row_at(xs, i). Single-column tables | a | | b | +*`xs` = > table.put in=`xs` at=1 value=A* *`n` = > table.rows xs=`xs`* +> print text=`h`[^Authorization] +> print text=`xs`[^1] > print text=`n` - -*`r` = > table.row_at xs=`xs` i=0* - -> print text=`r` diff --git a/src/capture.rs b/src/capture.rs index e5867ae..8d90017 100644 --- a/src/capture.rs +++ b/src/capture.rs @@ -8,4 +8,6 @@ pub struct RunCapture { pub stdout: String, pub value: Value, pub plots: Vec, + /// Entry-function bindings after a successful tree-backend run (empty for bytecode). + pub bindings: std::collections::HashMap, } diff --git a/src/host/agent_rt.rs b/src/host/agent_rt.rs index 45d74ad..30357c4 100644 --- a/src/host/agent_rt.rs +++ b/src/host/agent_rt.rs @@ -125,35 +125,11 @@ fn skill_search_roots(ctx: &HostContext) -> Vec { } pub fn map_set(map: &Value, key: &Value, value: &Value) -> Result { - let k = match key { - Value::Text(s) => s.clone(), - _ => return Err("map_set key must be text".into()), - }; - match map { - Value::Map(entries) => { - let mut out = entries.clone(); - if let Some((_, slot)) = out.iter_mut().find(|(kk, _)| *kk == k) { - *slot = value.clone(); - } else { - out.push((k, value.clone())); - } - Ok(Value::Map(out)) - } - Value::None => Ok(Value::Map(vec![(k, value.clone())])), - _ => Err("map_set needs map".into()), - } + crate::host::collection::map_set(map, key, value) } pub fn list_append(list: &Value, item: &Value) -> Result { - match list { - Value::List(xs) => { - let mut out = xs.clone(); - out.push(item.clone()); - Ok(Value::List(out)) - } - Value::None => Ok(Value::List(vec![item.clone()])), - _ => Err("list_append needs list".into()), - } + crate::host::collection::list_append(list, item) } #[cfg(test)] diff --git a/src/host/collection.rs b/src/host/collection.rs new file mode 100644 index 0000000..e2448bd --- /dev/null +++ b/src/host/collection.rs @@ -0,0 +1,442 @@ +//! List / map collection primitives for `lib/table` (and json compat aliases). + +use crate::value::Value; + +#[derive(Clone)] +enum PathSeg { + Key(String), + /// 1-based list index (aligned with footnote `[^1]`). + Index1(usize), +} + +fn path_segments(at: &Value) -> Result, String> { + match at { + Value::Text(s) => Ok(vec![PathSeg::Key(s.clone())]), + Value::Int(n) => { + if *n < 1 { + return Err("put path index must be >= 1 (1-based)".into()); + } + Ok(vec![PathSeg::Index1(*n as usize)]) + } + Value::List(xs) => { + if xs.is_empty() { + return Err("put path must not be empty".into()); + } + let mut out = Vec::with_capacity(xs.len()); + for (i, seg) in xs.iter().enumerate() { + match seg { + Value::Text(s) => out.push(PathSeg::Key(s.clone())), + Value::Int(n) => { + if *n < 1 { + return Err(format!( + "put path segment {i}: index must be >= 1 (1-based)" + )); + } + out.push(PathSeg::Index1(*n as usize)); + } + _ => { + return Err(format!( + "put path segment {i}: need text key or int index" + )); + } + } + } + Ok(out) + } + _ => Err("put at= needs text, int, or list path".into()), + } +} + +/// Deep put: `in` collection, `at` path (1-based ints), `value` leaf. +/// `in=None` + single text key → new one-entry map. +pub fn collection_put(input: &Value, at: &Value, value: &Value) -> Result { + let path = path_segments(at)?; + if matches!(input, Value::None) { + if path.len() == 1 { + if let PathSeg::Key(k) = &path[0] { + return Ok(Value::Map(vec![(k.clone(), value.clone())])); + } + } + return Err("put in=None only allowed with a single text key".into()); + } + put_rec(input, &path, value) +} + +fn put_rec(cur: &Value, path: &[PathSeg], value: &Value) -> Result { + let Some((head, rest)) = path.split_first() else { + return Ok(value.clone()); + }; + if rest.is_empty() { + return put_leaf(cur, head, value); + } + match head { + PathSeg::Key(k) => { + let Value::Map(entries) = cur else { + return Err(format!("put: expected map at key `{k}`")); + }; + let child = entries + .iter() + .find(|(kk, _)| kk == k) + .map(|(_, v)| v.clone()) + .ok_or_else(|| format!("put: missing key `{k}` on path"))?; + let new_child = put_rec(&child, rest, value)?; + map_set(cur, &Value::Text(k.clone()), &new_child) + } + PathSeg::Index1(i1) => { + let Value::List(xs) = cur else { + return Err(format!("put: expected list at index {i1}")); + }; + let i0 = i1 - 1; + if i0 >= xs.len() { + return Err(format!("put: list index {i1} out of range (len {})", xs.len())); + } + let new_child = put_rec(&xs[i0], rest, value)?; + list_set_at(cur, i0 as i64, &new_child) + } + } +} + +fn put_leaf(cur: &Value, head: &PathSeg, value: &Value) -> Result { + match head { + PathSeg::Key(k) => map_set(cur, &Value::Text(k.clone()), value), + PathSeg::Index1(i1) => { + let i0 = (*i1 as i64) - 1; + list_set_at(cur, i0, value) + } + } +} + +pub fn map_set(map: &Value, key: &Value, value: &Value) -> Result { + let k = match key { + Value::Text(s) => s.clone(), + _ => return Err("map_set key must be text".into()), + }; + match map { + Value::Map(entries) => { + let mut out = entries.clone(); + if let Some((_, slot)) = out.iter_mut().find(|(kk, _)| *kk == k) { + *slot = value.clone(); + } else { + out.push((k, value.clone())); + } + Ok(Value::Map(out)) + } + Value::None => Ok(Value::Map(vec![(k, value.clone())])), + _ => Err("map_set needs map".into()), + } +} + +pub fn map_get(map: &Value, key: &Value) -> Result { + let k = match key { + Value::Text(s) => s.as_str(), + _ => return Err("map_get key must be text".into()), + }; + match map { + Value::Map(entries) => Ok(entries + .iter() + .find(|(kk, _)| kk == k) + .map(|(_, v)| v.clone()) + .unwrap_or(Value::None)), + Value::None => Ok(Value::None), + _ => Err("map_get needs map".into()), + } +} + +pub fn map_delete(map: &Value, key: &Value) -> Result { + let k = match key { + Value::Text(s) => s.as_str(), + _ => return Err("map_delete key must be text".into()), + }; + match map { + Value::Map(entries) => { + let out: Vec<_> = entries.iter().filter(|(kk, _)| kk != k).cloned().collect(); + Ok(Value::Map(out)) + } + Value::None => Ok(Value::Map(vec![])), + _ => Err("map_delete needs map".into()), + } +} + +pub fn map_has(map: &Value, key: &Value) -> Result { + let k = match key { + Value::Text(s) => s.as_str(), + _ => return Err("map_has key must be text".into()), + }; + match map { + Value::Map(entries) => Ok(Value::Bool(entries.iter().any(|(kk, _)| kk == k))), + Value::None => Ok(Value::Bool(false)), + _ => Err("map_has needs map".into()), + } +} + +pub fn map_keys(map: &Value) -> Result { + match map { + Value::Map(entries) => Ok(Value::List( + entries + .iter() + .map(|(k, _)| Value::Text(k.clone())) + .collect(), + )), + Value::None => Ok(Value::List(vec![])), + _ => Err("map_keys needs map".into()), + } +} + +pub fn map_values(map: &Value) -> Result { + match map { + Value::Map(entries) => Ok(Value::List(entries.iter().map(|(_, v)| v.clone()).collect())), + Value::None => Ok(Value::List(vec![])), + _ => Err("map_values needs map".into()), + } +} + +pub fn map_items(map: &Value) -> Result { + match map { + Value::Map(entries) => { + let rows: Vec = entries + .iter() + .map(|(k, v)| { + Value::Map(vec![ + ("key".into(), Value::Text(k.clone())), + ("value".into(), v.clone()), + ]) + }) + .collect(); + Ok(Value::List(rows)) + } + Value::None => Ok(Value::List(vec![])), + _ => Err("map_items needs map".into()), + } +} + +pub fn map_merge(left: &Value, right: &Value) -> Result { + let mut out = match left { + Value::Map(e) => e.clone(), + Value::None => vec![], + _ => return Err("map_merge left needs map".into()), + }; + let right_entries = match right { + Value::Map(e) => e, + Value::None => return Ok(Value::Map(out)), + _ => return Err("map_merge right needs map".into()), + }; + for (k, v) in right_entries { + if let Some((_, slot)) = out.iter_mut().find(|(kk, _)| kk == k) { + *slot = v.clone(); + } else { + out.push((k.clone(), v.clone())); + } + } + Ok(Value::Map(out)) +} + +pub fn map_size(map: &Value) -> Result { + match map { + Value::Map(entries) => Ok(Value::Int(entries.len() as i64)), + Value::None => Ok(Value::Int(0)), + _ => Err("map_size needs map".into()), + } +} + +pub fn list_append(list: &Value, item: &Value) -> Result { + match list { + Value::List(xs) => { + let mut out = xs.clone(); + out.push(item.clone()); + Ok(Value::List(out)) + } + Value::None => Ok(Value::List(vec![item.clone()])), + _ => Err("list_append needs list".into()), + } +} + +pub fn list_prepend(list: &Value, item: &Value) -> Result { + match list { + Value::List(xs) => { + let mut out = vec![item.clone()]; + out.extend(xs.iter().cloned()); + Ok(Value::List(out)) + } + Value::None => Ok(Value::List(vec![item.clone()])), + _ => Err("list_prepend needs list".into()), + } +} + +pub fn list_concat(a: &Value, b: &Value) -> Result { + let left = match a { + Value::List(xs) => xs.clone(), + Value::None => vec![], + _ => return Err("list_concat left needs list".into()), + }; + let right = match b { + Value::List(xs) => xs, + Value::None => return Ok(Value::List(left)), + _ => return Err("list_concat right needs list".into()), + }; + let mut out = left; + out.extend(right.iter().cloned()); + Ok(Value::List(out)) +} + +pub fn list_insert(list: &Value, index: i64, item: &Value) -> Result { + let mut xs = match list { + Value::List(xs) => xs.clone(), + Value::None => vec![], + _ => return Err("list_insert needs list".into()), + }; + if index < 0 || index as usize > xs.len() { + return Err(format!( + "list_insert index {index} out of range (len {})", + xs.len() + )); + } + xs.insert(index as usize, item.clone()); + Ok(Value::List(xs)) +} + +pub fn list_set_at(list: &Value, index: i64, item: &Value) -> Result { + let Value::List(xs) = list else { + return Err("list_set_at needs list".into()); + }; + if index < 0 || index as usize >= xs.len() { + return Err(format!( + "list_set_at index {index} out of range (len {})", + xs.len() + )); + } + let mut out = xs.clone(); + out[index as usize] = item.clone(); + Ok(Value::List(out)) +} + +pub fn list_remove_at(list: &Value, index: i64) -> Result { + let Value::List(xs) = list else { + return Err("list_remove_at needs list".into()); + }; + if index < 0 || index as usize >= xs.len() { + return Err(format!( + "list_remove_at index {index} out of range (len {})", + xs.len() + )); + } + let mut out = xs.clone(); + out.remove(index as usize); + Ok(Value::List(out)) +} + +pub fn list_slice(list: &Value, start: i64, end: Option) -> Result { + let Value::List(xs) = list else { + return Err("list_slice needs list".into()); + }; + let n = xs.len() as i64; + let s = start.clamp(0, n) as usize; + let e = end.unwrap_or(n).clamp(0, n) as usize; + if e < s { + return Ok(Value::List(vec![])); + } + Ok(Value::List(xs[s..e].to_vec())) +} + +pub fn list_contains(list: &Value, item: &Value) -> Result { + match list { + Value::List(xs) => Ok(Value::Bool(xs.iter().any(|x| x == item))), + Value::None => Ok(Value::Bool(false)), + _ => Err("list_contains needs list".into()), + } +} + +pub fn list_index_of(list: &Value, item: &Value) -> Result { + match list { + Value::List(xs) => Ok(xs + .iter() + .position(|x| x == item) + .map(|i| Value::Int(i as i64)) + .unwrap_or(Value::None)), + Value::None => Ok(Value::None), + _ => Err("list_index_of needs list".into()), + } +} + +pub fn list_reverse(list: &Value) -> Result { + match list { + Value::List(xs) => { + let mut out = xs.clone(); + out.reverse(); + Ok(Value::List(out)) + } + Value::None => Ok(Value::List(vec![])), + _ => Err("list_reverse needs list".into()), + } +} + +pub fn list_first(list: &Value) -> Result { + match list { + Value::List(xs) => Ok(xs.first().cloned().unwrap_or(Value::None)), + Value::None => Ok(Value::None), + _ => Err("list_first needs list".into()), + } +} + +pub fn list_last(list: &Value) -> Result { + match list { + Value::List(xs) => Ok(xs.last().cloned().unwrap_or(Value::None)), + Value::None => Ok(Value::None), + _ => Err("list_last needs list".into()), + } +} + +pub fn collection_clear(value: &Value) -> Result { + match value { + Value::List(_) | Value::None => Ok(Value::List(vec![])), + Value::Map(_) => Ok(Value::Map(vec![])), + _ => Err("clear needs list or map".into()), + } +} + +fn require_i64(v: &Value, name: &str) -> Result { + match v { + Value::Int(n) => Ok(*n), + _ => Err(format!("{name} must be int")), + } +} + +/// Bind helper used by dispatch for optional end=. +pub fn list_slice_bound(list: &Value, start: &Value, end: Option<&Value>) -> Result { + let s = require_i64(start, "start")?; + let e = match end { + None | Some(Value::None) => None, + Some(v) => Some(require_i64(v, "end")?), + }; + list_slice(list, s, e) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn put_map_key_and_nested() { + let m = Value::Map(vec![("a".into(), Value::Int(1))]); + let m2 = collection_put(&m, &Value::Text("b".into()), &Value::Int(2)).unwrap(); + assert!(matches!(map_get(&m2, &Value::Text("b".into())).unwrap(), Value::Int(2))); + + let rows = Value::List(vec![Value::Map(vec![("qty".into(), Value::Int(1))])]); + let path = Value::List(vec![Value::Int(1), Value::Text("qty".into())]); + let rows2 = collection_put(&rows, &path, &Value::Int(9)).unwrap(); + let row = match &rows2 { + Value::List(xs) => &xs[0], + _ => panic!(), + }; + assert!(matches!( + map_get(row, &Value::Text("qty".into())).unwrap(), + Value::Int(9) + )); + } + + #[test] + fn put_none_single_key() { + let m = collection_put(&Value::None, &Value::Text("k".into()), &Value::Text("v".into())) + .unwrap(); + assert!(matches!(m, Value::Map(_))); + } +} diff --git a/src/host/dispatch.rs b/src/host/dispatch.rs index e7cfff6..30d442a 100644 --- a/src/host/dispatch.rs +++ b/src/host/dispatch.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; -use crate::host::{agent_rt, foreign, fs, json, math, net, plugin, subtask, sys, time, writeback, HostContext}; +use crate::host::{foreign, fs, json, math, net, plugin, subtask, sys, time, writeback, HostContext}; use crate::value::Value; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -100,8 +100,30 @@ pub enum HostFn { HttpPostSse = 98, OpenAiSseParse = 99, StreamPublish = 100, + CollectionPut = 101, + ListPrepend = 102, + ListConcat = 103, + ListInsert = 104, + ListSetAt = 105, + ListRemoveAt = 106, + ListSlice = 107, + ListContains = 108, + ListIndexOf = 109, + ListReverse = 110, + ListFirst = 111, + ListLast = 112, + MapGet = 113, + MapDelete = 114, + MapHas = 115, + MapKeys = 116, + MapValues = 117, + MapItems = 118, + MapMerge = 119, + MapSize = 120, + CollectionClear = 121, } + impl HostFn { pub fn from_u16(id: u16) -> Option { Some(match id { @@ -196,6 +218,27 @@ impl HostFn { 98 => Self::HttpPostSse, 99 => Self::OpenAiSseParse, 100 => Self::StreamPublish, + 101 => Self::CollectionPut, + 102 => Self::ListPrepend, + 103 => Self::ListConcat, + 104 => Self::ListInsert, + 105 => Self::ListSetAt, + 106 => Self::ListRemoveAt, + 107 => Self::ListSlice, + 108 => Self::ListContains, + 109 => Self::ListIndexOf, + 110 => Self::ListReverse, + 111 => Self::ListFirst, + 112 => Self::ListLast, + 113 => Self::MapGet, + 114 => Self::MapDelete, + 115 => Self::MapHas, + 116 => Self::MapKeys, + 117 => Self::MapValues, + 118 => Self::MapItems, + 119 => Self::MapMerge, + 120 => Self::MapSize, + 121 => Self::CollectionClear, _ => return None, }) } @@ -296,6 +339,27 @@ impl HostFn { "host_subtask_join" | "subtask_join" => Self::SubtaskJoin, "host_subtask_kill" | "subtask_kill" => Self::SubtaskKill, "host_subtask_wait_all" | "subtask_wait_all" => Self::SubtaskWaitAll, + "host_collection_put" | "collection_put" => Self::CollectionPut, + "host_list_prepend" | "list_prepend" => Self::ListPrepend, + "host_list_concat" | "list_concat" => Self::ListConcat, + "host_list_insert" | "list_insert" => Self::ListInsert, + "host_list_set_at" | "list_set_at" => Self::ListSetAt, + "host_list_remove_at" | "list_remove_at" => Self::ListRemoveAt, + "host_list_slice" | "list_slice" => Self::ListSlice, + "host_list_contains" | "list_contains" => Self::ListContains, + "host_list_index_of" | "list_index_of" => Self::ListIndexOf, + "host_list_reverse" | "list_reverse" => Self::ListReverse, + "host_list_first" | "list_first" => Self::ListFirst, + "host_list_last" | "list_last" => Self::ListLast, + "host_map_get" | "map_get" => Self::MapGet, + "host_map_delete" | "map_delete" => Self::MapDelete, + "host_map_has" | "map_has" => Self::MapHas, + "host_map_keys" | "map_keys" => Self::MapKeys, + "host_map_values" | "map_values" => Self::MapValues, + "host_map_items" | "map_items" => Self::MapItems, + "host_map_merge" | "map_merge" => Self::MapMerge, + "host_map_size" | "map_size" => Self::MapSize, + "host_collection_clear" | "collection_clear" => Self::CollectionClear, _ => return None, }) } @@ -383,6 +447,27 @@ impl HostFn { Self::ExtNativePath => "host_ext_native_path", Self::MapSet => "host_map_set", Self::ListAppend => "host_list_append", + Self::CollectionPut => "host_collection_put", + Self::ListPrepend => "host_list_prepend", + Self::ListConcat => "host_list_concat", + Self::ListInsert => "host_list_insert", + Self::ListSetAt => "host_list_set_at", + Self::ListRemoveAt => "host_list_remove_at", + Self::ListSlice => "host_list_slice", + Self::ListContains => "host_list_contains", + Self::ListIndexOf => "host_list_index_of", + Self::ListReverse => "host_list_reverse", + Self::ListFirst => "host_list_first", + Self::ListLast => "host_list_last", + Self::MapGet => "host_map_get", + Self::MapDelete => "host_map_delete", + Self::MapHas => "host_map_has", + Self::MapKeys => "host_map_keys", + Self::MapValues => "host_map_values", + Self::MapItems => "host_map_items", + Self::MapMerge => "host_map_merge", + Self::MapSize => "host_map_size", + Self::CollectionClear => "host_collection_clear", Self::WritebackRecord => "host_writeback_record", Self::WritebackGet => "host_writeback_get", Self::WritebackClear => "host_writeback_clear", @@ -451,6 +536,20 @@ impl HostFn { Self::WritebackScanPath => &["path"], Self::MapSet => &["map", "key", "value"], Self::ListAppend => &["list", "item"], + Self::CollectionPut => &["in", "at", "value"], + Self::ListPrepend => &["list", "item"], + Self::ListConcat => &["a", "b"], + Self::ListInsert => &["list", "index", "item"], + Self::ListSetAt => &["list", "index", "item"], + Self::ListRemoveAt => &["list", "index"], + Self::ListSlice => &["list", "start"], + Self::ListContains => &["list", "item"], + Self::ListIndexOf => &["list", "item"], + Self::ListReverse | Self::ListFirst | Self::ListLast => &["list"], + Self::MapGet | Self::MapDelete | Self::MapHas => &["map", "key"], + Self::MapKeys | Self::MapValues | Self::MapItems | Self::MapSize => &["map"], + Self::MapMerge => &["a", "b"], + Self::CollectionClear => &["value"], Self::WritebackRecord => &["value"], Self::WritebackGet | Self::WritebackClear => &[], Self::WritebackList => &[], @@ -482,6 +581,7 @@ impl HostFn { } Self::WritebackEnsure => &["placeholder", "line"], Self::SubtaskSpawn => &["path", "fn", "args", "code", "lang", "source", "stdin", "quiet"], + Self::ListSlice => &["end"], _ => &[], } } @@ -670,11 +770,66 @@ pub fn call_host( }) } HostFn::MapSet => { - agent_rt::map_set(require(bound, "map")?, require(bound, "key")?, require(bound, "value")?) + super::collection::map_set(require(bound, "map")?, require(bound, "key")?, require(bound, "value")?) } HostFn::ListAppend => { - agent_rt::list_append(require(bound, "list")?, require(bound, "item")?) + super::collection::list_append(require(bound, "list")?, require(bound, "item")?) } + HostFn::CollectionPut => super::collection::collection_put( + require(bound, "in")?, + require(bound, "at")?, + require(bound, "value")?, + ), + HostFn::ListPrepend => { + super::collection::list_prepend(require(bound, "list")?, require(bound, "item")?) + } + HostFn::ListConcat => { + super::collection::list_concat(require(bound, "a")?, require(bound, "b")?) + } + HostFn::ListInsert => { + let idx = match require(bound, "index")? { + Value::Int(n) => *n, + _ => return Err("index must be int".into()), + }; + super::collection::list_insert(require(bound, "list")?, idx, require(bound, "item")?) + } + HostFn::ListSetAt => { + let idx = match require(bound, "index")? { + Value::Int(n) => *n, + _ => return Err("index must be int".into()), + }; + super::collection::list_set_at(require(bound, "list")?, idx, require(bound, "item")?) + } + HostFn::ListRemoveAt => { + let idx = match require(bound, "index")? { + Value::Int(n) => *n, + _ => return Err("index must be int".into()), + }; + super::collection::list_remove_at(require(bound, "list")?, idx) + } + HostFn::ListSlice => super::collection::list_slice_bound( + require(bound, "list")?, + require(bound, "start")?, + bound.get("end"), + ), + HostFn::ListContains => { + super::collection::list_contains(require(bound, "list")?, require(bound, "item")?) + } + HostFn::ListIndexOf => { + super::collection::list_index_of(require(bound, "list")?, require(bound, "item")?) + } + HostFn::ListReverse => super::collection::list_reverse(require(bound, "list")?), + HostFn::ListFirst => super::collection::list_first(require(bound, "list")?), + HostFn::ListLast => super::collection::list_last(require(bound, "list")?), + HostFn::MapGet => super::collection::map_get(require(bound, "map")?, require(bound, "key")?), + HostFn::MapDelete => super::collection::map_delete(require(bound, "map")?, require(bound, "key")?), + HostFn::MapHas => super::collection::map_has(require(bound, "map")?, require(bound, "key")?), + HostFn::MapKeys => super::collection::map_keys(require(bound, "map")?), + HostFn::MapValues => super::collection::map_values(require(bound, "map")?), + HostFn::MapItems => super::collection::map_items(require(bound, "map")?), + HostFn::MapMerge => super::collection::map_merge(require(bound, "a")?, require(bound, "b")?), + HostFn::MapSize => super::collection::map_size(require(bound, "map")?), + HostFn::CollectionClear => super::collection::collection_clear(require(bound, "value")?), HostFn::OuterCallLine => Ok(Value::Int( ctx.call_site_lines .first() diff --git a/src/host/mod.rs b/src/host/mod.rs index 07fe964..3f13f23 100644 --- a/src/host/mod.rs +++ b/src/host/mod.rs @@ -5,6 +5,7 @@ //! Soft side-effects (no process::exit; sleep clamp) apply under view / capture only. pub mod agent_rt; +pub mod collection; mod dispatch; pub mod event_bus; pub mod foreign; diff --git a/src/interp.rs b/src/interp.rs index ae38293..40ff2da 100644 --- a/src/interp.rs +++ b/src/interp.rs @@ -24,6 +24,8 @@ pub struct Interpreter { pub trace: bool, capture: bool, pub captured_stdout: String, + /// Bindings in the entry (`# main` / sole object) env after it finishes. + pub entry_bindings: HashMap, current_span: Span, input: InputFeed, host: HostContext, @@ -50,6 +52,10 @@ impl Env { fn set(&mut self, name: String, value: Value) { self.vars.insert(name, value); } + + fn vars_clone(&self) -> HashMap { + self.vars.clone() + } } pub(crate) enum EvArg { @@ -64,6 +70,7 @@ impl Interpreter { trace, capture: false, captured_stdout: String::new(), + entry_bindings: HashMap::new(), current_span: Span::new(1, 1), input: InputFeed::new(false, Vec::new()), host: HostContext::for_run(path, Default::default(), Vec::new()), @@ -78,6 +85,7 @@ impl Interpreter { trace, capture: true, captured_stdout: String::new(), + entry_bindings: HashMap::new(), current_span: Span::new(1, 1), input: InputFeed::new(true, Vec::new()), host: HostContext::for_capture(path, Default::default()), @@ -140,7 +148,7 @@ impl Interpreter { ) -> Result { let fun = find_function_anywhere(module, name) .ok_or_else(|| self.err(format!("unknown function `{name}`")))?; - self.run_function(module, fun, Env::new(), args) + self.run_function(module, fun, Env::new(), args, false) } pub fn run_module(&mut self, module: &Module) -> Result { @@ -148,7 +156,7 @@ impl Interpreter { self.site_module = Some(module as *const Module); let result = (|| { if let Some(main) = find_top(module, "main") { - return self.run_function(module, main, Env::new(), &[]); + return self.run_function(module, main, Env::new(), &[], true); } // Document-as-entry: sole top-level `#` object with no params (e.g. `# Hello World`). let entries: Vec<&Function> = module @@ -157,7 +165,7 @@ impl Interpreter { .filter(|f| f.is_object() && f.params.is_empty()) .collect(); if entries.len() == 1 { - return self.run_function(module, entries[0], Env::new(), &[]); + return self.run_function(module, entries[0], Env::new(), &[], true); } bail!("no `# main` object to run"); })(); @@ -216,6 +224,7 @@ impl Interpreter { fun: &Function, mut env: Env, args: &[(String, Value)], + capture_entry_env: bool, ) -> Result { if self.trace { emit_trace( @@ -246,6 +255,9 @@ impl Interpreter { })(); self.host.pop_call_frame(); let ret = body_result?; + if capture_entry_env { + self.entry_bindings = env.vars_clone(); + } if self.trace { let display = ret.as_display(); emit_trace( @@ -669,7 +681,7 @@ impl Interpreter { "call_fn: `{name}` must have no parameters" ))); } - return self.run_function(module, target, Env::new(), &[]); + return self.run_function(module, target, Env::new(), &[], false); } other if HostFn::from_name(other).is_some() => { let hf = HostFn::from_name(other).unwrap(); @@ -707,7 +719,7 @@ impl Interpreter { } self.host.push_call_site_line(self.host.current_line); - let result = self.run_function(module, target, call_env, &[]); + let result = self.run_function(module, target, call_env, &[], false); self.host.pop_call_site_line(); let result = result?; if target.is_object() { @@ -774,7 +786,7 @@ impl Interpreter { } self.host.push_call_site_line(self.host.current_line); - let result = self.run_function(lib, node, call_env, &[]); + let result = self.run_function(lib, node, call_env, &[], false); self.host.pop_call_site_line(); let result = result?; if node.is_object() { @@ -821,7 +833,7 @@ impl Interpreter { call_env.set("自".into(), recv.clone()); call_env.set("self".into(), recv); self.host.push_call_site_line(self.host.current_line); - let result = self.run_function(owner, target, call_env, &[]); + let result = self.run_function(owner, target, call_env, &[], false); self.host.pop_call_site_line(); result } diff --git a/src/lib.rs b/src/lib.rs index 91de2f4..35ed71b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -265,6 +265,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result { stdout: interp.captured_stdout, value, plots, + bindings: interp.entry_bindings, }) } Backend::Bytecode => { @@ -287,6 +288,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result { stdout: vm.captured_stdout, value, plots, + bindings: Default::default(), }) } } diff --git a/src/view/html.rs b/src/view/html.rs index 1a66fce..3c7715f 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -391,17 +391,89 @@ section.block > h2 { } @media (max-width: 960px) { .struct-wrap { grid-template-columns: 1fr; } - .outline-panel { position: static; } + .outline-rail, .outline-panel { position: static; } } -.outline-panel { +.outline-rail { position: sticky; top: 1rem; + display: flex; + flex-direction: column; + gap: 0.55rem; + min-width: 0; +} +.outline-section { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); - padding: 0.55rem 0.6rem 0.65rem; + padding: 0.35rem 0.55rem 0.55rem; box-shadow: 0 1px 0 rgba(0,0,0,0.02); } +.outline-summary { + cursor: pointer; + font: 600 0.72rem/1.3 var(--sans); + color: var(--muted); + letter-spacing: 0.02em; + text-transform: uppercase; + list-style: none; + padding: 0.2rem 0 0.35rem; +} +.outline-summary::-webkit-details-marker { display: none; } +.outline-panel { + position: static; + background: transparent; + border: none; + border-radius: 0; + padding: 0; + box-shadow: none; +} +.vars-panel { + max-height: min(50vh, 28rem); + overflow: auto; + font: 0.72rem/1.35 var(--mono); +} +.vars-list { + list-style: none; + margin: 0; + padding: 0; +} +.vars-item { + margin: 0 0 0.55rem; + padding-bottom: 0.45rem; + border-bottom: 1px solid var(--line); +} +.vars-item:last-child { + margin-bottom: 0; + padding-bottom: 0; + border-bottom: none; +} +.vars-name { + font-weight: 600; + color: var(--ink); + margin-bottom: 0.2rem; + word-break: break-all; +} +.vars-table { + width: 100%; + border-collapse: collapse; + font: inherit; +} +.vars-table th, +.vars-table td { + border: 1px solid var(--line); + padding: 0.15rem 0.3rem; + text-align: left; + vertical-align: top; + word-break: break-word; +} +.vars-table th { + background: #f5f5f7; + font-weight: 600; + color: var(--muted); +} +.vars-idx, .vars-key { color: var(--muted); white-space: nowrap; } +.vars-scalar { white-space: pre-wrap; } +.vars-empty, .vars-skipped { color: var(--muted); margin: 0.2rem 0; } +.vars-nested > summary { cursor: pointer; color: var(--muted); } .fn-search { width: 100%; box-sizing: border-box; @@ -1423,6 +1495,13 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String { scrollIfPinned(); }} if (thinkingEl && (answerNode && answerNode.data)) thinkingEl.open = false; + if (typeof ev.bindings_html === "string") {{ + var vp = document.getElementById("vars-panel"); + if (vp) {{ + vp.innerHTML = ev.bindings_html + || "

No bindings

"; + }} + }} }} }} }} diff --git a/src/view/mod.rs b/src/view/mod.rs index 26fcd88..54c2dad 100644 --- a/src/view/mod.rs +++ b/src/view/mod.rs @@ -23,7 +23,10 @@ use tiny_http::{Header, Method, Request, Response, Server, StatusCode}; use crate::input_feed::{effective_stdin, extract_frontmatter_stdin, split_stdin_text}; use crate::view::debug_page::{build_debug_model, page_debug}; use crate::view::html::{escape, page_file, page_index, LinkMode}; -use crate::view::render::{collect_input_prompts, render_module_structure, FileViewModel}; +use crate::view::render::{ + collect_input_prompts, render_bindings_html, render_module_structure, render_right_rail, + FileViewModel, +}; use crate::{run_file_capture, RunOptions}; pub struct ViewOptions { @@ -306,18 +309,21 @@ pub(crate) fn build_file_view( ) -> Result { let mut source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?; // Structure shows this file only — do not merge imported lib bodies into the tree. - let (mut structure, mut outline, input_prompts) = match crate::parse::parse_source(&source) { - Ok(module) => ( - render_module_structure(&module, &source), - crate::view::render::render_function_outline(&module), - collect_input_prompts(&module), - ), + let (mut structure, mut module_opt, input_prompts) = match crate::parse::parse_source(&source) { + Ok(module) => { + let prompts = collect_input_prompts(&module); + ( + render_module_structure(&module, &source), + Some(module), + prompts, + ) + } Err(e) => ( format!( "
parse/load error: {}
", escape(&tidy_user_error(&format!("{e:#}"), abs, rel)) ), - String::new(), + None, Vec::new(), ), }; @@ -332,8 +338,14 @@ pub(crate) fn build_file_view( opts.sleep_limit_ms = if live { Some(30_000) } else { Some(0) }; // Optional: sandbox to the whole view tree so sibling folders are reachable. opts.fs_root = Some(root.root.clone()); - let (stdout, stderr, ok, plots) = if awaiting_input || auto_stream { - (String::new(), String::new(), true, Vec::new()) + let (stdout, stderr, ok, plots, mut bindings_html) = if awaiting_input || auto_stream { + ( + String::new(), + String::new(), + true, + Vec::new(), + String::new(), + ) } else { match run_file_capture(abs, &opts) { Ok(cap) => ( @@ -341,12 +353,14 @@ pub(crate) fn build_file_view( String::new(), true, cap.plots.into_iter().map(|p| p.svg).collect(), + render_bindings_html(&cap.bindings), ), Err(e) => ( String::new(), tidy_user_error(&format!("{e:#}"), abs, rel), false, Vec::new(), + String::new(), ), } }; @@ -356,11 +370,21 @@ pub(crate) fn build_file_view( source = next; if let Ok(module) = crate::parse::parse_source(&source) { structure = render_module_structure(&module, &source); - outline = crate::view::render::render_function_outline(&module); + module_opt = Some(module); } } } - outline.push_str(&crate::view::render::render_writeback_outline(&source)); + let wb = crate::view::render::render_writeback_outline(&source); + let outline = match &module_opt { + Some(module) => render_right_rail(module, &bindings_html, &wb), + None => { + if bindings_html.is_empty() && wb.is_empty() { + String::new() + } else { + render_right_rail(&crate::ast::Module::default(), &bindings_html, &wb) + } + } + }; Ok(FileViewModel { rel_path: rel.to_string(), source, @@ -374,6 +398,7 @@ pub(crate) fn build_file_view( awaiting_input, auto_stream, plots, + bindings_html: std::mem::take(&mut bindings_html), }) } @@ -607,12 +632,14 @@ fn api_run(root: &ViewRoot, mut request: Request) -> Result<()> { Ok(cap) => { // Keep the terminal frame small — tokens already streamed via bus. let preview: String = cap.stdout.chars().take(500).collect(); + let bindings_html = render_bindings_html(&cap.bindings); let done = serde_json::json!({ "type": "done", "run_id": run_id, "path": rel_clone, "ok": true, "result": preview, + "bindings_html": bindings_html, }); crate::host::event_bus::EventBus::global().publish_json(&done.to_string()); } diff --git a/src/view/output.rs b/src/view/output.rs index 0edcc78..5ef951e 100644 --- a/src/view/output.rs +++ b/src/view/output.rs @@ -31,6 +31,13 @@ pub fn write_static(opts: OutputOptions) -> Result<()> { vm.stderr = "execution skipped (--no-exec)".into(); vm.ok = true; vm.plots.clear(); + vm.bindings_html = String::from(r#"

skipped

"#); + // Rebuild outline so Variables shows skipped. + if let Ok(module) = crate::parse::parse_source(&vm.source) { + let wb = crate::view::render::render_writeback_outline(&vm.source); + vm.outline_html = + crate::view::render::render_right_rail(&module, &vm.bindings_html, &wb); + } } let links = LinkMode::Static { from: Some(rel.clone()), diff --git a/src/view/render.rs b/src/view/render.rs index f5fb780..fc2baf5 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -41,6 +41,8 @@ pub struct FileViewModel { pub auto_stream: bool, /// SVG plots from math lib (embedded in Execution). pub plots: Vec, + /// HTML for Variables panel (entry bindings after run). + pub bindings_html: String, } /// Collect prompt strings from every `input` / `输入` call in the module (pre-order). @@ -237,6 +239,184 @@ pub fn render_function_outline(module: &Module) -> String { out } +/// Right rail: collapsible Functions + Variables (+ optional writeback HTML appended by caller). +pub fn render_right_rail(module: &Module, bindings_html: &str, writeback_html: &str) -> String { + let fn_inner = if module.functions.is_empty() { + r#"

No functions

"#.to_string() + } else { + let mut tree = String::from( + r#" +
    "#, + ); + for fun in &module.functions { + tree.push_str(&outline_fun(fun, "")); + } + tree.push_str("
"); + tree + }; + let vars = if bindings_html.is_empty() { + r#"

No bindings

"# + } else { + bindings_html + }; + format!( + r#"
+
+Functions +
{fn_inner}
+
+
+Variables +
{vars}
+
+{wb} +
"#, + fn_inner = fn_inner, + vars = vars, + wb = writeback_html, + ) +} + +/// Render entry bindings as HTML tables (List / Map / records). +pub fn render_bindings_html(bindings: &HashMap) -> String { + if bindings.is_empty() { + return String::new(); + } + let mut names: Vec<&String> = bindings.keys().collect(); + names.sort(); + let mut out = String::from(r#"
    "#); + for name in names { + let Some(val) = bindings.get(name) else { + continue; + }; + out.push_str(&format!( + r#"
  • {}
    {}
  • "#, + escape(name), + render_value_html(val, 0) + )); + } + out.push_str("
"); + out +} + +const BIND_MAX_DEPTH: usize = 2; + +fn render_value_html(v: &crate::value::Value, depth: usize) -> String { + use crate::value::Value; + match v { + Value::List(xs) => { + if let Some(keys) = record_keys(xs) { + return render_records_table(xs, &keys, depth); + } + let mut s = String::from(r#""#); + for (i, item) in xs.iter().enumerate() { + s.push_str(&format!( + "", + i + 1, + cell_html(item, depth) + )); + } + if xs.is_empty() { + s.push_str(r#""#); + } + s.push_str("
#value
{}{}
∅
"); + s + } + Value::Map(pairs) => { + let mut s = String::from( + r#""#, + ); + for (k, val) in pairs { + s.push_str(&format!( + "", + escape(k), + cell_html(val, depth) + )); + } + if pairs.is_empty() { + s.push_str(r#""#); + } + s.push_str("
keyvalue
{}{}
∅
"); + s + } + other => format!(r#"{}"#, escape(&other.as_display())), + } +} + +fn cell_html(v: &crate::value::Value, depth: usize) -> String { + use crate::value::Value; + match v { + Value::List(_) | Value::Map(_) if depth >= BIND_MAX_DEPTH => { + format!( + r#"
{}{}
"#, + escape(&brief_type(v)), + escape(&v.as_display()) + ) + } + Value::List(_) | Value::Map(_) => render_value_html(v, depth + 1), + other => escape(&other.as_display()), + } +} + +fn brief_type(v: &crate::value::Value) -> String { + use crate::value::Value; + match v { + Value::List(xs) => format!("List({})", xs.len()), + Value::Map(xs) => format!("Map({})", xs.len()), + _ => "…".into(), + } +} + +fn record_keys(xs: &[crate::value::Value]) -> Option> { + use crate::value::Value; + if xs.is_empty() { + return None; + } + let mut keys: Vec = Vec::new(); + for (i, item) in xs.iter().enumerate() { + let Value::Map(pairs) = item else { + return None; + }; + if i == 0 { + keys = pairs.iter().map(|(k, _)| k.clone()).collect(); + if keys.is_empty() { + return None; + } + } + } + Some(keys) +} + +fn render_records_table( + xs: &[crate::value::Value], + keys: &[String], + depth: usize, +) -> String { + use crate::value::Value; + let mut s = String::from(r#""#); + for k in keys { + s.push_str(&format!("", escape(k))); + } + s.push_str(""); + for (i, item) in xs.iter().enumerate() { + let Value::Map(pairs) = item else { + continue; + }; + s.push_str(&format!(r#""#, i + 1)); + for k in keys { + let cell = pairs + .iter() + .find(|(kk, _)| kk == k) + .map(|(_, v)| cell_html(v, depth)) + .unwrap_or_else(|| String::from("")); + s.push_str(&format!("")); + } + s.push_str(""); + } + s.push_str("
#{}
{}{cell}
"); + s +} + fn outline_fun(fun: &Function, parent_path: &str) -> String { let fn_path = fn_path(parent_path, &fun.name); let mut s = format!( @@ -998,4 +1178,25 @@ mod tests { assert!(outline.contains("href=\"#fn-"), "{outline}"); assert!(outline.contains("ol-meta\">h"), "{outline}"); } + + #[test] + fn right_rail_has_functions_and_variables() { + let src = include_str!("../../tests/structure/hello.mq.md"); + let module = crate::parse::parse_source(src).unwrap(); + let mut bind = HashMap::new(); + bind.insert( + "xs".into(), + crate::value::Value::List(vec![ + crate::value::Value::Text("a".into()), + crate::value::Value::Text("b".into()), + ]), + ); + let html = render_right_rail(&module, &render_bindings_html(&bind), ""); + assert!(html.contains("outline-rail"), "{html}"); + assert!(html.contains("Functions"), "{html}"); + assert!(html.contains("Variables"), "{html}"); + assert!(html.contains("vars-panel"), "{html}"); + assert!(html.contains("vars-table"), "{html}"); + assert!(html.contains(">xs<") || html.contains("vars-name\">xs"), "{html}"); + } } diff --git a/tests/gold.rs b/tests/gold.rs index 5ddd44e..4b78d99 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -1036,6 +1036,19 @@ fn lib_json_roundtrip() { ); } +#[test] +fn lib_table_collections() { + assert_out( + "tests/lib/table-collections.mq.md", + "Bearer-x\nA\nb\nhi\nTrue\n3\n[Authorization, role, content]\n0", + ); +} + +#[test] +fn lib_table_collections_zh() { + assert_out("tests/lib/表-集合.mq.md", "Bearer-x\nA\n3"); +} + #[test] fn lib_sys_cwd() { assert_out("tests/lib/sys-cwd.mq.md", "cwd-ok"); diff --git a/tests/lib/table-collections.mq.md b/tests/lib/table-collections.mq.md new file mode 100644 index 0000000..d1b4ee4 --- /dev/null +++ b/tests/lib/table-collections.mq.md @@ -0,0 +1,47 @@ +--- +title: table collections +description: put + list/map helpers +> lib/table.mq.md +--- + +# main + +*`h` = > table.put in=None at=Authorization value=Bearer-x* +> print text=`h`[^Authorization] + +`xs` = + +| v | +|---| +| a | +| b | + +*`xs` = > table.put in=`xs` at=1 value=A* +> print text=`xs`[^1] +> print text=`xs`[^2] + +`req` = + +| model | messages | +|-------|----------| +| m1 | None | + +*`msg` = > table.put in=None at=role value=user* +*`msg` = > table.put in=`msg` at=content value=hi* +*`messages` = > table.append list=None item=`msg`* +*`req` = > table.put in=`req` at=messages value=`messages`* +*`req` = > table.put in=`req` at=stream value=True* +> print text=`req`[^messages][^1][^content] +> print text=`req`[^stream] + +*`xs` = > table.append list=`xs` item=c* +*`n` = > table.len xs=`xs`* +> print text=`n` + +*`m` = > table.merge a=`h` b=`msg`* +*`ks` = > table.keys map=`m`* +> print text=`ks` + +*`empty` = > table.empty_map* +*`sz` = > table.size map=`empty`* +> print text=`sz` diff --git a/tests/lib/表-集合.mq.md b/tests/lib/表-集合.mq.md new file mode 100644 index 0000000..f598b94 --- /dev/null +++ b/tests/lib/表-集合.mq.md @@ -0,0 +1,24 @@ +--- +title: 表集合 +description: 改 + 列表字典 +> lib/表.mq.md +--- + +# main + +*`h` = > 表.改 入=None 于=Authorization 值=Bearer-x* +> 打印 内容=`h`[^Authorization] + +`xs` = + +| v | +|---| +| a | +| b | + +*`xs` = > 表.改 入=`xs` 于=1 值=A* +> 打印 内容=`xs`[^1] + +*`xs` = > 表.追加 list=`xs` item=c* +*`n` = > 表.长度 xs=`xs`* +> 打印 内容=`n`