feat(migrate): M7 迁移与版本门 — per-file markup + migrate labels + 全仓迁移
原计划的"翻转默认 + 旧形硬报错"不可行:`[键](集合)` 与 `[描述](实现)` 外形相同, 翻转会让 506 处取元静默变义,硬报错又拿不到证据。改为**按文件声明**。 一、per-file markup - frontmatter `markup: occlusion`(或 `标记: 遮蔽`)决定该文件模式 - load.rs 先取模式,用 parse::expr::with_markup(线程局部压栈)包住解析 - 同一进程可同时加载两种模式的文件(imports);MARQDO_MARKUP 仍作进程默认 - 好处:迁移逐文件、可增量、可回滚,不存在半迁移的静默错义 二、`marqdo migrate labels [--write|--json]` 改写规则: [键](集合) → [键](access(集合, "键")) [`名`](集合) → [名](access(集合, `名`)) - [项](集合) → - [项](遍历 集合 为 项) 安全模型:改写 → 重解析 → 证明等价 → 才写 - 原文件按 classic 解析得 AST-A;改写后按 occlusion 解析得 AST-B - 反归一化 B(标签与键同名且 payload 为 access 的遮蔽还原成 Index) - Debug(A) == Debug(反归一化(B))(抹掉行号)才写入,否则原文件一字不动 只改代码行(LineKind::Code);表格行只改 **…** 单元格,散文 markdown 链接不碰; 链式索引由内向外改写,已迁移的有守卫不二次改。 三、access 提升为宿主函数 HostFn::Access(u16 id 212) 与旧取元逐字一致(Map 按键 / List 1-based / 缺键 missing map key); 进 HostFn 是为了两个后端共用同一实现,interp 里的特例已删除。 四、顺带修的两处真实语义缺陷 1. payload 继承外层"文本模式":`f text=[k](access(c,k))` 中 access 不被当调用 → `()` 内永远允许 callee(args) 2. 遮蔽形状判定过宽:`[问候] ([格式化] "Bo")` 误判为遮蔽 → 要求 `]` 后紧跟 `(`,否则落回方括号调用 五、全仓迁移结果 migrate labels: 256 index, 23 loop, 80 file written;0 文件被等价性拒绝; 迁移后 cargo test --release → 604 passed / 0 failed;再跑迁移幂等。 等价性检查先后抓出 4 类改写 bug(表格散文链接、payload 文本模式、链式索引、 遮蔽与方括号调用混淆),每类都是先拦下再修工具,未污染文件。 测试:6 个单测 + 3 个集成(干跑不写盘 / 写入后运行输出不变且幂等 / 等价失败文件不动);全量 604 passed / 0 failed(M3 后 595 + 9);双后端一致。 文档:doc/design/change-m7-migration.md
This commit is contained in:
1 parent
9dbcc728b6
commit
4488a3cb70
98 files changed
+1354
-278
No files matched your search
@@ -0,0 +1,127 @@
|
||||
# 变更记录:M7 迁移与版本门(per-file 标记 + `migrate labels` + 全仓迁移)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Implemented** |
|
||||
| 日期 | 2026-10-22 |
|
||||
| 里程碑 | M7([occlusion-syntax.md](occlusion-syntax.md) §13) |
|
||||
| 改动文件 | **新增 `src/migrate.rs`** · `src/load.rs` · `src/parse/mod.rs`(expr) · `src/host/dispatch.rs` · **80 个语料文件** · 测试 |
|
||||
| 影响面 | 语法模式按文件切换;全仓 256 处索引 + 23 处循环已迁移 |
|
||||
|
||||
---
|
||||
|
||||
## 1. 原计划的问题:同形换义
|
||||
|
||||
原设计想"翻转默认 + 对旧形硬报错"。但 `[键](集合)` 与 `[描述](实现)` **外形完全相同**:
|
||||
|
||||
- 翻转默认 → 506 处取元**静默变成**"遮蔽整个集合",正是文档点名的最坏变更
|
||||
- 硬报错 → 无法实现:解析器拿不到"这是旧写法"的证据(两种读法都合法)
|
||||
|
||||
**结论:模式不能全局翻转,必须按文件声明。**
|
||||
|
||||
## 2. 新方案:per-file `markup:`
|
||||
|
||||
```markdown
|
||||
---
|
||||
markup: occlusion
|
||||
---
|
||||
```
|
||||
|
||||
| 文件 | 解析模式 | `[a](b)` 的含义 |
|
||||
|------|---------|----------------|
|
||||
| 无 `markup:` | classic(进程默认) | 取元 |
|
||||
| `markup: occlusion` | 纯度 | 遮蔽 |
|
||||
|
||||
实现:`load.rs` 先读 frontmatter 取出模式,用 `parse::expr::with_markup(m, …)`
|
||||
(线程局部覆盖,压栈/出栈)包住解析。**同一进程里可以同时加载两种模式的文件**
|
||||
(imports!),且 `MARQDO_MARKUP=occlusion` 仍可作为进程默认。
|
||||
|
||||
好处:迁移是**逐文件、可增量、可回滚**的;不存在"半迁移的静默错义"。
|
||||
|
||||
## 3. 迁移工具 `marqdo migrate labels`
|
||||
|
||||
```bash
|
||||
marqdo migrate labels . # 干跑:列出将改什么
|
||||
marqdo migrate labels . --write # 实际写入
|
||||
marqdo migrate labels . --json # 机器可读
|
||||
```
|
||||
|
||||
### 3.1 改写规则
|
||||
|
||||
| 旧 | 新 |
|
||||
|----|----|
|
||||
| `[键](集合)` | `[键](access(集合, "键"))` |
|
||||
| `` [`名`](集合) `` | `` [名](access(集合, `名`)) `` |
|
||||
| `- [项](集合)` | `- [项](遍历 集合 为 项)` |
|
||||
|
||||
`access` 是新增宿主函数(`host_access`,id 212),语义与旧取元**逐字一致**
|
||||
(Map 按键 / List 1-based / 缺键 `missing map key`)。它进 `HostFn` 是有意的:
|
||||
**两个后端共用同一实现**,不再有特例分支。
|
||||
|
||||
### 3.2 安全模型:改写 → 重解析 → 证明等价 → 才写
|
||||
|
||||
1. 原文件按 classic 解析,得到 AST-A
|
||||
2. 文本改写后,按 occlusion 解析,得到 AST-B
|
||||
3. **反归一化** B:把"标签与键同名 + payload 为 `access(x, k)`"的遮蔽还原成 `Index`
|
||||
4. 比较 `Debug(A)` 与 `Debug(反归一化(B))`(抹掉行号,因为插入了 marker 行)
|
||||
5. 只有相等才写入;否则**原文件一字不动**并报告 `equivalence check failed`
|
||||
|
||||
这条校验是真干活的:它先后抓出 4 类改写 bug(表格散文链接、payload 继承文本模式、
|
||||
链式索引、`[问候] (…)` 与遮蔽混淆),每一类都是**先被拦下、再修工具**,没有污染文件。
|
||||
|
||||
### 3.3 只改代码行
|
||||
|
||||
用词法层的 `LineKind::Code` 限定范围;表格行只改 `**…**` 单元格
|
||||
(散文里的 markdown 链接 `[docs](https://…)` 必须原样保留)。
|
||||
|
||||
### 3.4 由内向外
|
||||
|
||||
链式索引 `[content]([1]([messages](req)))` 必须**最内层先改**,
|
||||
否则外层改写会让内层的位置失效;已迁移的 `[k](access(…))` 有守卫,不会二次改写。
|
||||
|
||||
## 4. 全仓迁移结果
|
||||
|
||||
```
|
||||
migrate labels: 256 index, 23 loop, 80 file written
|
||||
```
|
||||
|
||||
- 覆盖 `lib/ ext/ examples/ public/ cli/ tests/`
|
||||
- **0 文件被等价性检查拒绝**
|
||||
- 迁移后 `cargo test --release` → **604 passed / 0 failed**
|
||||
- 再跑一次迁移 → **幂等**(只剩刻意保留的 classic 测试样例)
|
||||
|
||||
## 5. 顺带修的两处真实语义缺陷
|
||||
|
||||
| 缺陷 | 现象 | 修法 |
|
||||
|------|------|------|
|
||||
| payload 继承外层"文本模式" | `f text=[k](access(c,k))` 里 `access(...)` 不被当调用 → 退化成插值文本 | `()` 内**永远**允许 `callee(args)`(`parse_occluded` 临时置位) |
|
||||
| 遮蔽形状判定过宽 | `[问候] ([格式化] "Bo")` 被误判为遮蔽 | 要求 `]` 后**紧跟** `(`;否则落回方括号调用 |
|
||||
|
||||
## 6. 版本门
|
||||
|
||||
- 旧写法**不再**被硬报错——因为无法与遮蔽区分;真正的门是 **per-file 声明**:
|
||||
没写 `markup: occlusion` 的文件按 classic 解析,行为不变。
|
||||
- 需要"禁止新写旧形"的仓库可用 `migrate labels` 干跑做 CI 门禁(有改动即失败)。
|
||||
|
||||
## 7. 测试
|
||||
|
||||
| 层 | 内容 | 结果 |
|
||||
|----|------|------|
|
||||
| 单元(6) | 静态键 / 动态键 / 嵌套三层 / 已迁移不重写 / 循环 / 非循环 | ✅ |
|
||||
| 集成(3) | 干跑不写盘;写入后**运行输出不变**且幂等;等价失败则文件不动 | ✅ |
|
||||
| 全量 | `cargo test --release` | **604 passed / 0 failed**(M3 后 595 + 9) |
|
||||
| 双后端 | gold 套件含 bytecode 变体 | ✅ |
|
||||
|
||||
## 8. 变更清单
|
||||
|
||||
| 文件 | 变更 |
|
||||
|------|------|
|
||||
| `src/migrate.rs` | **新增**:改写器、等价性证明、`migrate_file` / `migrate_path` |
|
||||
| `src/load.rs` | `frontmatter_markup` + `with_markup` 包裹两处 `parse_source` |
|
||||
| `src/parse/expr.rs` | `with_markup` 线程局部覆盖;`()` 内强制允许调用;`occlusion_shape_ahead` 严格判定 |
|
||||
| `src/host/dispatch.rs` | `HostFn::Access`(enum / from_u16 212 / from_name / name / required_params / call_host) |
|
||||
| `src/main.rs` | `migrate labels` 子命令 |
|
||||
| `src/interp.rs` | 移除 access 特例(改用 HostFn,单一实现) |
|
||||
| 80 个语料文件 | 索引与循环迁移 + `markup: occlusion` 标记 |
|
||||
| `tests/migrate.rs` + `src/migrate.rs` 单测 | 9 个测试 |
|
||||
| `doc/design/change-m7-migration.md` | 本文件 |
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: components/feed
|
||||
description: 帖子列表 / 新闻时间线 / 板块栏 HTML 片段(对齐 Django feed 与 home 局部模板)。
|
||||
import table:lib/table.mq.md
|
||||
@@ -11,13 +12,13 @@ import text:lib/text.mq.md
|
||||
给定帖子行记录列表,输出 `ul.home-posts-list` 标记(首页与列表页共用)。
|
||||
|
||||
**段 = None**
|
||||
- [帖](行)
|
||||
**板 = [board](帖)**
|
||||
**题 = [title](帖)**
|
||||
**链 = [slug](帖)**
|
||||
**作 = [author](帖)**
|
||||
**评 = [comments_count](帖)**
|
||||
**时 = [created_at](帖)**
|
||||
- [帖](遍历 行 为 帖)
|
||||
**板 = [board](access(帖, "board"))**
|
||||
**题 = [title](access(帖, "title"))**
|
||||
**链 = [slug](access(帖, "slug"))**
|
||||
**作 = [author](access(帖, "author"))**
|
||||
**评 = [comments_count](access(帖, "comments_count"))**
|
||||
**时 = [created_at](access(帖, "created_at"))**
|
||||
1. not 作
|
||||
**作 = "匿名"**
|
||||
2. *
|
||||
@@ -41,11 +42,11 @@ import text:lib/text.mq.md
|
||||
给定新闻行记录列表,输出 `.news-timeline` 标记。
|
||||
|
||||
**段 = None**
|
||||
- [讯](行)
|
||||
**题 = [title](讯)**
|
||||
**链 = [slug](讯)**
|
||||
**板 = [board](讯)**
|
||||
**时 = [created_at](讯)**
|
||||
- [讯](遍历 行 为 讯)
|
||||
**题 = [title](access(讯, "title"))**
|
||||
**链 = [slug](access(讯, "slug"))**
|
||||
**板 = [board](access(讯, "board"))**
|
||||
**时 = [created_at](access(讯, "created_at"))**
|
||||
1. not 板
|
||||
**板 = ""**
|
||||
2. *
|
||||
@@ -79,9 +80,9 @@ import text:lib/text.mq.md
|
||||
**全链 = 前缀 + "?" + 查询键 + "=0"**
|
||||
**全项 = "<a href=\"" + 全链 + "\" class=\"" + 全部类 + " active\" " + 数据属 + "=\"0\">" + 全标签 + "</a>"**
|
||||
**段 = > table.append list=段 item=全项**
|
||||
- [板](板块)
|
||||
**名 = [name](板)**
|
||||
**号 = [id](板)**
|
||||
- [板](遍历 板块 为 板)
|
||||
**名 = [name](access(板, "name"))**
|
||||
**号 = [id](access(板, "id"))**
|
||||
**链 = 前缀 + "?" + 查询键 + "=" + 号**
|
||||
**项 = "<a href=\"" + 链 + "\" class=\"" + 全部类 + "\" " + 数据属 + "=\"" + 号 + "\">" + 名 + "</a>"**
|
||||
**段 = > table.append list=段 item=项**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: browser-app (route E+)
|
||||
description: list CRUD, storage, navigate, interval, fetch_all, ws — GFM + lib/browser
|
||||
import browser:lib/browser.mq.md
|
||||
@@ -64,7 +65,7 @@ import text:lib/text.mq.md
|
||||
**`bag` = bag + "\n" + value**
|
||||
**`parts` = > text.str_split s=bag sep="\n"**
|
||||
**`html` = ""**
|
||||
- [item](parts)
|
||||
- [item](遍历 parts 为 item)
|
||||
1. `item` != ""
|
||||
**`html` = html + "<li><span>" + item + "</span> <button type=\"button\" data-id=\"" + item + "\">删</button></li>"**
|
||||
**`ret` = > browser.set_html sel="#items" html=html**
|
||||
@@ -81,7 +82,7 @@ import text:lib/text.mq.md
|
||||
1. `data_id` != ""
|
||||
**`parts` = > text.str_split s=bag sep="\n"**
|
||||
**`next` = ""**
|
||||
- [item](parts)
|
||||
- [item](遍历 parts 为 item)
|
||||
1. `item` != ""
|
||||
1. `item` != `data_id`
|
||||
1. `next` == ""
|
||||
@@ -91,7 +92,7 @@ import text:lib/text.mq.md
|
||||
**`bag` = next**
|
||||
**`parts2` = > text.str_split s=bag sep="\n"**
|
||||
**`html` = ""**
|
||||
- [item](parts2)
|
||||
- [item](遍历 parts2 为 item)
|
||||
1. `item` != ""
|
||||
**`html` = html + "<li><span>" + item + "</span> <button type=\"button\" data-id=\"" + item + "\">删</button></li>"**
|
||||
**`ret` = > browser.set_html sel="#items" html=html**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 代码即文档 · 周末咖啡手账
|
||||
description: >-
|
||||
一份可读可跑的周末手账:菜单是表,计价写在段落里,结账读起来像日记。
|
||||
@@ -55,13 +56,13 @@ description: >-
|
||||
上午来了位会员,点两杯拿铁。品名写进`名`,价钱从菜单里取:
|
||||
|
||||
**名 = "拿铁"**
|
||||
**价 = [`名`](菜单)**
|
||||
**价 = [名](access(菜单, `名`))**
|
||||
**摘要 = [结账摘要] 品名=`名` 价=`价` 杯数=2 会员=True**
|
||||
**打印 内容=`摘要`**
|
||||
|
||||
旁桌只要一杯普通美式,对照一下原价:
|
||||
|
||||
**对照 = [结账摘要] 品名="美式" 价=[美式](菜单)**
|
||||
**对照 = [结账摘要] 品名="美式" 价=[美式](access(菜单, "美式"))**
|
||||
**打印 内容=`对照`**
|
||||
|
||||
---
|
||||
@@ -75,8 +76,8 @@ description: >-
|
||||
| 1 | 燕麦拿铁 | 32 | 1 | True |
|
||||
| 2 | 美式 | 18 | 2 | False |
|
||||
|
||||
- [行](今日订单)
|
||||
**一行 = 结账摘要 品名=[品名](行) 价=[单价](行) 杯数=[杯数](行) 会员=[会员](行)**
|
||||
- [行](遍历 今日订单 为 行)
|
||||
**一行 = 结账摘要 品名=[品名](access(行, "品名")) 价=[单价](access(行, "单价")) 杯数=[杯数](access(行, "杯数")) 会员=[会员](access(行, "会员"))**
|
||||
**打印 内容=`一行`**
|
||||
|
||||
打烊前给积分卡盖一个章:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 外联:把 Node 当作文档里的计算车间
|
||||
description: 一次性执行、持久会话、显式传值,以及可读的结果。
|
||||
import foreign:lib/foreign.mq.md
|
||||
@@ -59,7 +60,7 @@ console.log(ranked.map(([region, total]) => `${region}: ${total}`).join("\n"));
|
||||
```
|
||||
|
||||
**`第一次` = > foreign.session_eval id=`会话` code=`排序代码`**
|
||||
> print text=[stdout](`第一次`)
|
||||
> print text=[stdout](access(`第一次`, "stdout"))
|
||||
|
||||
内核状态是持续的。下面这段代码在同一个`orders`上追加一条华北订单,
|
||||
再重新排序;不需要重新传一遍整张表。
|
||||
@@ -79,6 +80,6 @@ console.log(rankedAgain.map(([region, total]) => `${region}: ${total}`).join("\n
|
||||
```
|
||||
|
||||
**`第二次` = > foreign.session_eval id=`会话` code=`追加代码`**
|
||||
> print text=[stdout](`第二次`)
|
||||
> print text=[stdout](access(`第二次`, "stdout"))
|
||||
|
||||
**> foreign.session_close id=`会话`**
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 一张订单,一份可执行的业务说明
|
||||
description: 叙述、数据、计算与断言共享同一个 .mq.md 源文件。
|
||||
---
|
||||
@@ -19,8 +20,8 @@ description: 叙述、数据、计算与断言共享同一个 .mq.md 源文件
|
||||
逐行把「单价 × 数量」累加进`小计`。读者看到的是清单,机器执行的是同一张表。
|
||||
|
||||
**`小计` = 0**
|
||||
- [行](订单)
|
||||
**`小计` = `小计` + [单价](行) * [数量](行)**
|
||||
- [行](遍历 订单 为 行)
|
||||
**`小计` = `小计` + [单价](access(行, "单价")) * [数量](access(行, "数量"))**
|
||||
|
||||
业务约定写在叙述里:提前不少于七天,整单按九五折;否则原价。
|
||||
本单最早提前 14 天。
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: spa client
|
||||
description: routes table + memory store; list / detail / edit
|
||||
import browser:lib/browser.mq.md
|
||||
@@ -87,7 +88,7 @@ Routes (documentation + titles). Runtime switches panels by `path`.
|
||||
1. `cur_id` != ""
|
||||
**`parts` = > text.str_split s=items sep="\n"**
|
||||
**`next` = ""**
|
||||
- [item](parts)
|
||||
- [item](遍历 parts 为 item)
|
||||
1. `item` != ""
|
||||
1. `item` == `cur_id`
|
||||
1. `next` == ""
|
||||
@@ -145,7 +146,7 @@ Routes (documentation + titles). Runtime switches panels by `path`.
|
||||
**`body` = ""**
|
||||
**`parts` = > text.str_split s=items sep="\n"**
|
||||
**`html` = ""**
|
||||
- [item](parts)
|
||||
- [item](遍历 parts 为 item)
|
||||
1. `item` != ""
|
||||
**`html` = html + "<li data-id=\"" + item + "\">" + item + "</li>"**
|
||||
`persist` =
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: ext/ai/llm/openai
|
||||
description: >-
|
||||
OpenAI-compatible chat completions transport (HTTP + SSE).
|
||||
@@ -56,7 +57,7 @@ Extract OpenAI-shaped `choices[0].message.tool_calls` as a list (or empty list).
|
||||
1. not `choices`
|
||||
*> table.empty_list*
|
||||
2. *
|
||||
**c0 = [1](choices)**
|
||||
**c0 = [1](access(choices, "1"))**
|
||||
**msg = > json.get value=`c0` key="message"**
|
||||
1. not `msg`
|
||||
*> table.empty_list*
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: ext/ai/sandbox
|
||||
description: >-
|
||||
CoW trial workspace for AI-generated Marqdo: open / run / diff / commit.
|
||||
@@ -172,9 +173,9 @@ O4: write a markdown review of `## diff` for `marqdo view` / HITL (static report
|
||||
**body = "# Sandbox diff report\n\nPending changes: "**
|
||||
**body = body + n**
|
||||
**body = body + "\n\n| path | kind |\n|------|------|\n"**
|
||||
- [row](pending)
|
||||
**p = [path](row)**
|
||||
**k = [kind](row)**
|
||||
- [row](遍历 pending 为 row)
|
||||
**p = [path](access(row, "path"))**
|
||||
**k = [kind](access(row, "kind"))**
|
||||
**body = body + "| "**
|
||||
**body = body + p**
|
||||
**body = body + " | "**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: ext/data/cache
|
||||
description: Cache Resource (ADR 0007).
|
||||
import plugin:lib/plugin.mq.md
|
||||
@@ -27,7 +28,7 @@ Key–value cache. Use `memory:` for in-process (tests / single process) or `red
|
||||
## get
|
||||
+ `key`
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_cache_get url=`url` key=`key`*
|
||||
|
||||
## set
|
||||
@@ -37,24 +38,24 @@ Key–value cache. Use `memory:` for in-process (tests / single process) or `red
|
||||
|
||||
Optional `ttl` is seconds until expiry.
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_cache_set url=`url` key=`key` value=`value` ttl=`ttl`*
|
||||
|
||||
## del
|
||||
+ `key`
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_cache_del url=`url` key=`key`*
|
||||
|
||||
## exists
|
||||
+ `key`
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_cache_exists url=`url` key=`key`*
|
||||
|
||||
## ttl
|
||||
+ `key`
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_cache_ttl url=`url` key=`key`*
|
||||
|
||||
+32
-31
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: ext/data/db
|
||||
description: Database Resource — CRUD, txn, migrate, FTS (ADR 0007).
|
||||
import plugin:lib/plugin.mq.md
|
||||
@@ -30,7 +31,7 @@ Open a database handle. URL schemes: `sqlite:path` (default), `postgres://…` /
|
||||
|
||||
Create a table from a schema table. Optional columns: `唯一`/`unique`, `索引`/`index` (creates UNIQUE / INDEX), `外键`/`fk`/`references` (e.g. `posts.id` or `posts(id)`). Columns named `created_at` / `updated_at` are filled automatically on insert/update when present.
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_db_init url=`url` name=`name` fields=`fields`*
|
||||
|
||||
## insert
|
||||
@@ -38,7 +39,7 @@ Create a table from a schema table. Optional columns: `唯一`/`unique`, `索引
|
||||
+ `rows`
|
||||
+ `txn`=None
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_db_insert url=`url` table=`table` rows=`rows` txn=`txn`*
|
||||
|
||||
## select
|
||||
@@ -50,9 +51,9 @@ Create a table from a schema table. Optional columns: `唯一`/`unique`, `索引
|
||||
|
||||
Simple filters: one-row map of column→value (AND `=`), or rows `|字段|操作|值|` (`=` `!=` `>` `>=` `<` `<=` `like` `in` `between` `is null`; add `|或|` = `是` to join a row with `OR`). `order` is a column name with optional `-` prefix for descending (`"created_at"`, `"-created_at"`), comma-separated for multiple keys. Pass `txn` to read inside an open transaction. For pages (with a total), use `paginate`.
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
**r = > web_db_select url=`url` table=`table` where=`where` limit=`limit` order=`order` offset=None txn=`txn`**
|
||||
*[rows](r)*
|
||||
*[rows](access(r, "rows"))*
|
||||
|
||||
## paginate
|
||||
+ `table`
|
||||
@@ -64,7 +65,7 @@ Simple filters: one-row map of column→value (AND `=`), or rows `|字段|操作
|
||||
|
||||
Like `select` but returns `{ rows, total }` — the total counts rows matching `where` regardless of `limit`/`跳过`, so you can render `上一页 / 下一页`. Set `跳过` to the number of rows to skip (e.g. page 2 with 10 per page ⇒ `跳过`=10).
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_db_select url=`url` table=`table` where=`where` limit=`limit` order=`order` offset=`跳过` txn=`txn`*
|
||||
|
||||
## get
|
||||
@@ -72,7 +73,7 @@ Like `select` but returns `{ rows, total }` — the total counts rows matching `
|
||||
+ `id`
|
||||
+ `txn`=None
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_db_get url=`url` table=`table` id=`id` txn=`txn`*
|
||||
|
||||
## update
|
||||
@@ -81,7 +82,7 @@ Like `select` but returns `{ rows, total }` — the total counts rows matching `
|
||||
+ `row`
|
||||
+ `txn`=None
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_db_update url=`url` table=`table` id=`id` row=`row` txn=`txn`*
|
||||
|
||||
## delete
|
||||
@@ -89,7 +90,7 @@ Like `select` but returns `{ rows, total }` — the total counts rows matching `
|
||||
+ `id`
|
||||
+ `txn`=None
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_db_delete url=`url` table=`table` id=`id` txn=`txn`*
|
||||
|
||||
## exec
|
||||
@@ -97,7 +98,7 @@ Like `select` but returns `{ rows, total }` — the total counts rows matching `
|
||||
+ `args`=None
|
||||
+ `txn`=None
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_db_exec url=`url` sql=`sql` args=`args` txn=`txn`*
|
||||
|
||||
## query
|
||||
@@ -107,7 +108,7 @@ Like `select` but returns `{ rows, total }` — the total counts rows matching `
|
||||
|
||||
Run bare SQL and return the result set — count / join / group / subqueries. Returns `{ rows, count }`.
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_db_query url=`url` sql=`sql` args=`args` txn=`txn`*
|
||||
|
||||
## count
|
||||
@@ -117,16 +118,16 @@ Run bare SQL and return the result set — count / join / group / subqueries. Re
|
||||
|
||||
Count rows matching a `where` filter (same syntax as `select`). Returns a number.
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
**r = > web_db_count url=`url` table=`table` where=`where` txn=`txn`**
|
||||
*[count](r)*
|
||||
*[count](access(r, "count"))*
|
||||
|
||||
## migrate
|
||||
+ `steps`
|
||||
|
||||
Apply versioned SQL migrations. `steps` is a `|version|sql|` / `|版本|SQL|` table. Applied versions are recorded in `_marqdo_migrations`. Re-running is a no-op for already-applied versions. SQLite only.
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_db_migrate url=`url` steps=`steps`*
|
||||
|
||||
## fts
|
||||
@@ -136,7 +137,7 @@ Apply versioned SQL migrations. `steps` is a `|version|sql|` / `|版本|SQL|` ta
|
||||
|
||||
Create an FTS5 index on `table` for the listed content columns (CSV string or list). Default FTS name is `{table}_fts`. Keeps the index in sync via triggers. Requires integer `id` PK. SQLite only.
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_db_fts_create url=`url` table=`table` columns=`columns` name=`name`*
|
||||
|
||||
## search
|
||||
@@ -147,7 +148,7 @@ Create an FTS5 index on `table` for the listed content columns (CSV string or li
|
||||
|
||||
Full-text search (`MATCH`) against the FTS5 index from `fts`. Returns `{ rows, count }` with a `rank` column (bm25). SQLite only.
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_db_search url=`url` table=`table` q=`q` limit=`limit` name=`name`*
|
||||
|
||||
## 事务
|
||||
@@ -156,7 +157,7 @@ Begin a transaction: borrows the pooled connection exclusively and returns a
|
||||
`txn` handle. Write inside it, then `提交` (commit) or `回滚` (roll back).
|
||||
Every statement runs on the same connection, so a batch is atomic.
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_db_begin url=`url`*
|
||||
|
||||
# txn
|
||||
@@ -172,8 +173,8 @@ connection; finish with `提交` or `回滚`.
|
||||
+ `table`
|
||||
+ `rows`
|
||||
|
||||
**url = [url](self)**
|
||||
**txn = [txn](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
**txn = [txn](access(self, "txn"))**
|
||||
*> web_db_insert url=`url` table=`table` rows=`rows` txn=`txn`*
|
||||
|
||||
## select
|
||||
@@ -184,17 +185,17 @@ connection; finish with `提交` or `回滚`.
|
||||
|
||||
Same filters as `db.select`; runs inside the transaction.
|
||||
|
||||
**url = [url](self)**
|
||||
**txn = [txn](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
**txn = [txn](access(self, "txn"))**
|
||||
**r = > web_db_select url=`url` table=`table` where=`where` limit=`limit` order=`order` offset=None txn=`txn`**
|
||||
*[rows](r)*
|
||||
*[rows](access(r, "rows"))*
|
||||
|
||||
## get
|
||||
+ `table`
|
||||
+ `id`
|
||||
|
||||
**url = [url](self)**
|
||||
**txn = [txn](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
**txn = [txn](access(self, "txn"))**
|
||||
*> web_db_get url=`url` table=`table` id=`id` txn=`txn`*
|
||||
|
||||
## update
|
||||
@@ -202,37 +203,37 @@ Same filters as `db.select`; runs inside the transaction.
|
||||
+ `id`
|
||||
+ `row`
|
||||
|
||||
**url = [url](self)**
|
||||
**txn = [txn](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
**txn = [txn](access(self, "txn"))**
|
||||
*> web_db_update url=`url` table=`table` id=`id` row=`row` txn=`txn`*
|
||||
|
||||
## delete
|
||||
+ `table`
|
||||
+ `id`
|
||||
|
||||
**url = [url](self)**
|
||||
**txn = [txn](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
**txn = [txn](access(self, "txn"))**
|
||||
*> web_db_delete url=`url` table=`table` id=`id` txn=`txn`*
|
||||
|
||||
## exec
|
||||
+ `sql`
|
||||
+ `args`=None
|
||||
|
||||
**url = [url](self)**
|
||||
**txn = [txn](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
**txn = [txn](access(self, "txn"))**
|
||||
*> web_db_exec url=`url` sql=`sql` args=`args` txn=`txn`*
|
||||
|
||||
## 提交
|
||||
|
||||
Commit the transaction and return its connection to the pool.
|
||||
|
||||
**txn = [txn](self)**
|
||||
**txn = [txn](access(self, "txn"))**
|
||||
*> web_db_commit txn=`txn`*
|
||||
|
||||
## 回滚
|
||||
|
||||
Roll the transaction back (undo every write) and return its connection.
|
||||
|
||||
**txn = [txn](self)**
|
||||
**txn = [txn](access(self, "txn"))**
|
||||
*> web_db_rollback txn=`txn`*
|
||||
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: ext/data/form
|
||||
description: Form Resource — fields, validate, submit (ADR 0007).
|
||||
import plugin:lib/plugin.mq.md
|
||||
@@ -62,6 +63,6 @@ Localized submit / cancel copy for rendered forms.
|
||||
+ `data`
|
||||
+ `db`
|
||||
|
||||
**url = [url](db)**
|
||||
**url = [url](access(db, "url"))**
|
||||
*> web_form_submit form=`self` data=`data` url=`url`*
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: ext/data/storage
|
||||
description: Object storage Resource (ADR 0007).
|
||||
import plugin:lib/plugin.mq.md
|
||||
@@ -32,25 +33,25 @@ Object storage. `file:dir` stores blobs on disk (offline / gold). `s3://bucket?e
|
||||
|
||||
Provide either `body` (text) or `path` (local file to upload).
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_storage_put url=`url` key=`key` body=`body` path=`path` content_type=`content_type`*
|
||||
|
||||
## get
|
||||
+ `key`
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_storage_get url=`url` key=`key`*
|
||||
|
||||
## delete
|
||||
+ `key`
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_storage_delete url=`url` key=`key`*
|
||||
|
||||
## list
|
||||
+ `prefix`=""
|
||||
|
||||
**url = [url](self)**
|
||||
**url = [url](access(self, "url"))**
|
||||
*> web_storage_list url=`url` prefix=`prefix`*
|
||||
|
||||
# media
|
||||
@@ -79,7 +80,7 @@ Offline helpers for upload validation and saving into `# storage` (also used by
|
||||
|
||||
**st = storage**
|
||||
1. `st` == None
|
||||
**st = [storage](self)**
|
||||
**st = [storage](access(self, "storage"))**
|
||||
2. *
|
||||
|
||||
*> web_upload_save storage=`st` path=`path` key=`key` content_type=`content_type` prefix=`prefix`*
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: ext/net/websocket
|
||||
description: WebSocket client Resource (ADR 0007).
|
||||
import plugin:lib/plugin.mq.md
|
||||
@@ -37,5 +38,5 @@ WebSocket client helper.
|
||||
|
||||
Single request–response: connect to `url`, send `message`, collect up to 256 server text replies (each up to 1 MiB), close. Transport errors and timeouts return `{ok:false, error}` instead of looking like an empty successful reply.
|
||||
|
||||
**timeout = [timeout_sec](self)**
|
||||
**timeout = [timeout_sec](access(self, "timeout_sec"))**
|
||||
*> web_ws_connect url=`url` message=`message` headers=`headers` timeout_sec=`timeout`*
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: ext/security/auth
|
||||
description: Auth Resource (ADR 0007).
|
||||
import plugin:lib/plugin.mq.md
|
||||
@@ -31,8 +32,8 @@ Session/auth helper. Constructs a config object; `login` validates against the u
|
||||
|
||||
Validate credentials against the users table and create a session. Returns `{ok, session_id, username, role}`.
|
||||
|
||||
**users = [users](self)**
|
||||
**ttl = [session_ttl](self)**
|
||||
**users = [users](access(self, "users"))**
|
||||
**ttl = [session_ttl](access(self, "session_ttl"))**
|
||||
*> web_auth_login username=`username` password=`password` users=`users` session_ttl=`ttl`*
|
||||
|
||||
## check
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 手工构造的测试样例
|
||||
description: AI禁止更改
|
||||
---
|
||||
@@ -15,6 +16,6 @@ description: AI禁止更改
|
||||
|lib|
|
||||
|
||||
|
||||
- [`测试文件夹`](`测试目录`)
|
||||
- [测试文件夹](遍历 `测试目录` 为 `测试文件夹`)
|
||||
> 打印 `测试文件夹`
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Welcome to Marqdo
|
||||
description: User-docs home — code as documentation (English)
|
||||
import math:lib/math.mq.md
|
||||
@@ -51,7 +52,7 @@ Foreign v2 is a good example. Probe Python, then run the bound fence:
|
||||
|
||||
**python = > foreign.probe lang="python"**
|
||||
|
||||
1. [ok](`python`)
|
||||
1. [ok](access(`python`, "ok"))
|
||||
**hello = > foreign.run code=`hi`**
|
||||
> print text=`hello`
|
||||
2. *
|
||||
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 欢迎使用 Marqdo
|
||||
description: 用户文档首页 — 代码即文档(中文版)
|
||||
导入 数学:lib/数学.mq.md
|
||||
@@ -51,7 +52,7 @@ print("hello-from-python")
|
||||
|
||||
**python = > 外联.探测 语言="python"**
|
||||
|
||||
1. [ok](`python`)
|
||||
1. [ok](access(`python`, "ok"))
|
||||
**问候 = > 外联.运行 代码=`hi`**
|
||||
> 打印 内容=`问候`
|
||||
2. *
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Mid stdlib — csv and text
|
||||
description: lib/csv + thickened lib/text (Mid M4)
|
||||
import csv:lib/csv.mq.md
|
||||
@@ -14,8 +15,8 @@ Parse a tiny CSV, normalize a field, print — no plugins.
|
||||
**raw = "name,city\nAda,london\nBob,PARIS\n"**
|
||||
**rows = > csv.parse text=`raw`**
|
||||
**r0 = > at value=`rows` index=0**
|
||||
**city = > text.to_upper text=[city](`r0`)**
|
||||
> print text=[name](`r0`)
|
||||
**city = > text.to_upper text=[city](access(`r0`, "city"))**
|
||||
> print text=[name](access(`r0`, "name"))
|
||||
> print text=`city`
|
||||
**n = > len `rows`**
|
||||
1. `n` == 2
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 中层标准库 — 逗号表与文本
|
||||
description: lib/逗号表 + 加厚 lib/文本(中层 M4)
|
||||
导入 逗号表:lib/逗号表.mq.md
|
||||
@@ -14,8 +15,8 @@ description: lib/逗号表 + 加厚 lib/文本(中层 M4)
|
||||
**raw = "name,city\nAda,london\nBob,PARIS\n"**
|
||||
**rows = > 逗号表.解析 内容=`raw`**
|
||||
**r0 = > at value=`rows` index=0**
|
||||
**city = > 文本.大写 内容=[city](`r0`)**
|
||||
> 打印 内容=[name](`r0`)
|
||||
**city = > 文本.大写 内容=[city](access(`r0`, "city"))**
|
||||
> 打印 内容=[name](access(`r0`, "name"))
|
||||
> 打印 内容=`city`
|
||||
**n = > 长度 `rows`**
|
||||
1. `n` == 2
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Mid stdlib — lists and cli
|
||||
description: table sort/unique/zip + cli.parse (Mid M5)
|
||||
import table:lib/table.mq.md
|
||||
@@ -16,12 +17,12 @@ Zero plugins: parse CSV, sort by key, parse `--input`.
|
||||
**rows = > csv.parse text=`raw`**
|
||||
**rows = > table.sort_by list=`rows` key="name"**
|
||||
**r0 = > at value=`rows` index=0**
|
||||
> print text=[name](`r0`)
|
||||
> print text=[name](access(`r0`, "name"))
|
||||
|
||||
**args = > split value="--input,scores.csv,--pretty" sep=","**
|
||||
**flags = > cli.parse args=`args`**
|
||||
> print text=[input](`flags`)
|
||||
1. [pretty](`flags`)
|
||||
> print text=[input](access(`flags`, "input"))
|
||||
1. [pretty](access(`flags`, "pretty"))
|
||||
> print text=mid-m5-ok
|
||||
2. *
|
||||
> print text=mid-m5-fail
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 中层标准库 — 列表与命令行
|
||||
description: 表排序/去重 + 命令行解析(中层 M5)
|
||||
导入 表:lib/表.mq.md
|
||||
@@ -16,12 +17,12 @@ description: 表排序/去重 + 命令行解析(中层 M5)
|
||||
**rows = > 逗号表.解析 内容=`raw`**
|
||||
**rows = > 表.按键排序 list=`rows` key="name"**
|
||||
**r0 = > at value=`rows` index=0**
|
||||
> 打印 内容=[name](`r0`)
|
||||
> 打印 内容=[name](access(`r0`, "name"))
|
||||
|
||||
**args = > split value="--input,scores.csv,--pretty" sep=","**
|
||||
**flags = > 命令行.解析 参数=`args`**
|
||||
> 打印 内容=[input](`flags`)
|
||||
1. [pretty](`flags`)
|
||||
> 打印 内容=[input](access(`flags`, "input"))
|
||||
1. [pretty](access(`flags`, "pretty"))
|
||||
> 打印 内容=mid-m5-ok
|
||||
2. *
|
||||
> 打印 内容=mid-m5-fail
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Mid stdlib — datetime and url
|
||||
description: Calendar moments + URL/query parse (Mid2 M7)
|
||||
import dt:lib/datetime.mq.md
|
||||
@@ -12,8 +13,8 @@ Moments are maps `{unix, zone, iso}`. Parse HTTPS URLs and round-trip query stri
|
||||
# main
|
||||
|
||||
**epoch = > dt.from_unix unix=0 zone="Asia/Shanghai"**
|
||||
> print text=[iso](`epoch`)
|
||||
> print text=[iso](access(`epoch`, "iso"))
|
||||
|
||||
**u = > url.parse text="https://example.com/path?q=1#top"**
|
||||
> print text=[host](`u`)
|
||||
> print text=[query](`u`)
|
||||
> print text=[host](access(`u`, "host"))
|
||||
> print text=[query](access(`u`, "query"))
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 中层标准库 — 日期时间与地址
|
||||
description: 日历时刻 + URL/查询串(Mid2 M7)
|
||||
导入 日时:lib/日期时间.mq.md
|
||||
@@ -12,8 +13,8 @@ description: 日历时刻 + URL/查询串(Mid2 M7)
|
||||
# main
|
||||
|
||||
**epoch = > 日时.自戳 秒=0 区="Asia/Shanghai"**
|
||||
> print text=[iso](`epoch`)
|
||||
> print text=[iso](access(`epoch`, "iso"))
|
||||
|
||||
**u = > 址.解析 内容="https://example.com/path?q=1"**
|
||||
> print text=[host](`u`)
|
||||
> print text=[query](`u`)
|
||||
> print text=[host](access(`u`, "host"))
|
||||
> print text=[query](access(`u`, "query"))
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Mid stdlib — toml, html, base32
|
||||
description: Config TOML + HTML escape + base32 (Mid2 M8)
|
||||
import toml:lib/toml.mq.md
|
||||
@@ -13,9 +14,9 @@ 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=[app](`cfg`)
|
||||
**srv = [server](`cfg`)**
|
||||
> print text=[port](`srv`)
|
||||
> print text=[app](access(`cfg`, "app"))
|
||||
**srv = [server](access(`cfg`, "server"))**
|
||||
> print text=[port](access(`srv`, "port"))
|
||||
|
||||
**safe = > html.escape text="<tag>"**
|
||||
> print text=`safe`
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 中层标准库 — 配置表、超文本、基32
|
||||
description: TOML 配置 + HTML 转义 + base32(Mid2 M8)
|
||||
导入 配置:lib/配置表.mq.md
|
||||
@@ -11,7 +12,7 @@ description: TOML 配置 + HTML 转义 + base32(Mid2 M8)
|
||||
# main
|
||||
|
||||
**cfg = > 配置.解析 内容="app = \"演示\"\n"**
|
||||
> print text=[app](`cfg`)
|
||||
> print text=[app](access(`cfg`, "app"))
|
||||
|
||||
**safe = > 超.转义 内容="<tag>"**
|
||||
> print text=`safe`
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Mid stdlib — fs make_dirs, walk, stat
|
||||
description: Recursive dirs, walk, and file metadata (Mid2 M9)
|
||||
import fs:lib/fs.mq.md
|
||||
@@ -15,7 +16,7 @@ import fs:lib/fs.mq.md
|
||||
> fs.write_text path="m9-demo/readme.txt" text="ok"
|
||||
|
||||
**st = > fs.stat path="m9-demo/readme.txt"**
|
||||
> print text=[size](`st`)
|
||||
> print text=[size](access(`st`, "size"))
|
||||
|
||||
**w = > fs.walk path="m9-demo"**
|
||||
**n = > len `w`**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 中层标准库 — 文件目录树与状态
|
||||
description: 递归目录、遍历与元数据(Mid2 M9)
|
||||
导入 文件:lib/文件.mq.md
|
||||
@@ -13,7 +14,7 @@ description: 递归目录、遍历与元数据(Mid2 M9)
|
||||
> 文件.写文本 路径="m9-演示/说明.txt" 内容="好"
|
||||
|
||||
**st = > 文件.状态 路径="m9-演示/说明.txt"**
|
||||
> print text=[size](`st`)
|
||||
> print text=[size](access(`st`, "size"))
|
||||
|
||||
**w = > 文件.遍历 路径="m9-演示"**
|
||||
**n = > 长度 `w`**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Foreign kernels v2 — Python analysis in view
|
||||
description: Kernel state, Marqdo-to-kernel values and view cells — without a stdin-only demo
|
||||
import foreign:lib/foreign.mq.md
|
||||
@@ -14,8 +15,8 @@ Probe the interpreter first. The result is ordinary Marqdo data.
|
||||
|
||||
**python = > foreign.probe lang="python"**
|
||||
|
||||
> print text=[ok](`python`)
|
||||
> print text=[version](`python`)
|
||||
> print text=[ok](access(`python`, "ok"))
|
||||
> print text=[version](access(`python`, "version"))
|
||||
|
||||
---
|
||||
|
||||
@@ -45,7 +46,7 @@ round(sum(float(row["金额"]) for row in orders), 2)
|
||||
|
||||
**total = > foreign.session_eval id=`内核会话` code=`total_code`**
|
||||
|
||||
> print text=[result](`total`)
|
||||
> print text=[result](access(`total`, "result"))
|
||||
|
||||
The low-level kernel session is managed entirely by `foreign`; the table crossed the boundary as an explicit JSON copy.
|
||||
|
||||
@@ -69,7 +70,7 @@ sum(value * value for value in values)
|
||||
|
||||
**square_sum = > foreign.session_eval id=`内核会话` code=`square_sum_code`**
|
||||
|
||||
> print text=[result](`square_sum`)
|
||||
> print text=[result](access(`square_sum`, "result"))
|
||||
|
||||
**> foreign.session_close id=`内核会话`**
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 外联内核 v2 — Python 分析(view 单元)
|
||||
description: 内核态、Marqdo 值传入与 view 单元 —— 不依赖 stdin 的完整示例
|
||||
导入 外联:lib/外联.mq.md
|
||||
@@ -14,8 +15,8 @@ description: 内核态、Marqdo 值传入与 view 单元 —— 不依赖 stdin
|
||||
|
||||
**python = > 外联.探测 语言="python"**
|
||||
|
||||
> 打印 内容=[ok](`python`)
|
||||
> 打印 内容=[version](`python`)
|
||||
> 打印 内容=[ok](access(`python`, "ok"))
|
||||
> 打印 内容=[version](access(`python`, "version"))
|
||||
|
||||
---
|
||||
|
||||
@@ -45,7 +46,7 @@ round(sum(float(row["金额"]) for row in orders), 2)
|
||||
|
||||
**合计 = > 外联.会话求值 标识=`内核会话` 代码=`合计代码`**
|
||||
|
||||
> 打印 内容=[result](`合计`)
|
||||
> 打印 内容=[result](access(`合计`, "result"))
|
||||
|
||||
低层内核会话完全由 `外联` 管理;表格以显式 JSON 拷贝跨过边界。
|
||||
|
||||
@@ -69,7 +70,7 @@ sum(value * value for value in values)
|
||||
|
||||
**平方和 = > 外联.会话求值 标识=`内核会话` 代码=`平方和代码`**
|
||||
|
||||
> 打印 内容=[result](`平方和`)
|
||||
> 打印 内容=[result](access(`平方和`, "result"))
|
||||
|
||||
**> 外联.会话关闭 标识=`内核会话`**
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: lib/foreign — foreign kernels v2
|
||||
description: Structured execution, JSON calls, parallel fan-out, persistent kernels and an explicit state bridge
|
||||
import foreign:lib/foreign.mq.md
|
||||
@@ -17,8 +18,8 @@ Probe before you run.
|
||||
|
||||
**node = > foreign.probe lang="node"**
|
||||
|
||||
> print text=[ok](`node`)
|
||||
> print text=[version](`node`)
|
||||
> print text=[ok](access(`node`, "ok"))
|
||||
> print text=[version](access(`node`, "version"))
|
||||
|
||||
`probe` returns `{lang, cmd, path, ok, version, error}`. Omit `lang` to inspect every known language.
|
||||
|
||||
@@ -33,9 +34,9 @@ console.log("hello from a foreign kernel");
|
||||
|
||||
**record = > foreign.invoke code=`marker`**
|
||||
|
||||
> print text=[ok](`record`)
|
||||
> print text=[stdout](`record`)
|
||||
> print text=[code](`record`)
|
||||
> print text=[ok](access(`record`, "ok"))
|
||||
> print text=[stdout](access(`record`, "stdout"))
|
||||
> print text=[code](access(`record`, "code"))
|
||||
|
||||
`invoke` never throws on a process failure. Read `ok`, `code`, `stdout`, `stderr`, `ms`, `timed_out`, `truncated`, `result` and `error` from one record.
|
||||
|
||||
@@ -87,7 +88,7 @@ A persistent kernel.
|
||||
|
||||
**second = > foreign.session_eval id=`session` source="total * 2"**
|
||||
|
||||
> print text=[result](`second`)
|
||||
> print text=[result](access(`second`, "result"))
|
||||
|
||||
Variables created in the first evaluation survive into the second. The kernel is not a shell: use `session_eval`, `session_get`, `session_names`, then `session_close`.
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: lib/table — collections
|
||||
description: put, append, and map helpers (code-as-docs pilot)
|
||||
import table:lib/table.mq.md
|
||||
@@ -21,6 +22,6 @@ Read with link-index get. Use json for parse/stringify only.
|
||||
**`xs` = [table.put] in=`xs` at=1 value="A"**
|
||||
**`n` = [table.rows] xs=`xs`**
|
||||
|
||||
**打印 内容=[Authorization](h)**
|
||||
**打印 内容=[1](xs)**
|
||||
**打印 内容=[Authorization](access(h, "Authorization"))**
|
||||
**打印 内容=[1](access(xs, "1"))**
|
||||
**打印 内容=`n`**
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: lib/外联 — 外联内核 v2
|
||||
description: 结构化执行、JSON 调用、并行扇出、持久内核与显式状态桥
|
||||
导入 外联:lib/外联.mq.md
|
||||
@@ -17,8 +18,8 @@ stdin: 21
|
||||
|
||||
**node = > 外联.探测 语言="node"**
|
||||
|
||||
> 打印 内容=[ok](`node`)
|
||||
> 打印 内容=[version](`node`)
|
||||
> 打印 内容=[ok](access(`node`, "ok"))
|
||||
> 打印 内容=[version](access(`node`, "version"))
|
||||
|
||||
`探测` 返回 `{lang, cmd, path, ok, version, error}`。省略语言时探测所有已知语言。
|
||||
|
||||
@@ -33,9 +34,9 @@ console.log("来自外联内核的问候");
|
||||
|
||||
**记录 = > 外联.执行 代码=`标记`**
|
||||
|
||||
> 打印 内容=[ok](`记录`)
|
||||
> 打印 内容=[stdout](`记录`)
|
||||
> 打印 内容=[code](`记录`)
|
||||
> 打印 内容=[ok](access(`记录`, "ok"))
|
||||
> 打印 内容=[stdout](access(`记录`, "stdout"))
|
||||
> 打印 内容=[code](access(`记录`, "code"))
|
||||
|
||||
`执行` 在进程失败时不抛错,而是在一条记录里给出 `ok`、`code`、`stdout`、`stderr`、`ms`、`timed_out`、`truncated`、`result` 与 `error`。
|
||||
|
||||
@@ -87,7 +88,7 @@ process.stdin.on("end", () => {
|
||||
|
||||
**第二次 = > 外联.会话求值 标识=`会话` 源码="total * 2"**
|
||||
|
||||
> 打印 内容=[result](`第二次`)
|
||||
> 打印 内容=[result](access(`第二次`, "result"))
|
||||
|
||||
第一次求值创建的变量会保留到第二次。内核不是 shell:用 `会话求值`、`会话取值`、`会话变量`,最后 `会话关闭`。
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: lib/表 — 列表与字典
|
||||
description: 改 / 行数 / 取行(代码即文档试点)
|
||||
导入 表:lib/表.mq.md
|
||||
@@ -19,6 +20,6 @@ description: 改 / 行数 / 取行(代码即文档试点)
|
||||
**`n` = [表.行数] xs=`xs`**
|
||||
**`r` = [表.取行] xs=`xs` i=0**
|
||||
|
||||
**打印 内容=[1](xs)**
|
||||
**打印 内容=[1](access(xs, "1"))**
|
||||
**打印 内容=`n`**
|
||||
**打印 内容=`r`**
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Loops
|
||||
description: Condition loops and table walks
|
||||
---
|
||||
@@ -24,5 +25,5 @@ Walk a table (tables are collections):
|
||||
| apple |
|
||||
| pear |
|
||||
|
||||
- [fruit](basket)
|
||||
- [fruit](遍历 basket 为 fruit)
|
||||
> print text=today `fruit`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 循环
|
||||
description: 条件循环与表遍历
|
||||
---
|
||||
@@ -24,5 +25,5 @@ description: 条件循环与表遍历
|
||||
| 苹果 |
|
||||
| 梨 |
|
||||
|
||||
- [水果](篮子)
|
||||
- [水果](遍历 篮子 为 水果)
|
||||
> 打印 内容=今天 `水果`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Collections (tables)
|
||||
description: One-column tables are lists
|
||||
---
|
||||
@@ -15,5 +16,5 @@ A single-column Markdown table is a list; loop to read each item. Prefer link-in
|
||||
| pear |
|
||||
| peach |
|
||||
|
||||
- [fruit](basket)
|
||||
- [fruit](遍历 basket 为 fruit)
|
||||
> print text=`fruit`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 集合(表)
|
||||
description: 单列竖表即列表
|
||||
---
|
||||
@@ -15,5 +16,5 @@ description: 单列竖表即列表
|
||||
| 梨 |
|
||||
| 桃 |
|
||||
|
||||
- [水果](篮子)
|
||||
- [水果](遍历 篮子 为 水果)
|
||||
> 打印 内容=`水果`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Maps (horizontal tables)
|
||||
description: Multi-column tables are maps; link-index get
|
||||
---
|
||||
@@ -13,10 +14,10 @@ A multi-column table with one data row is a map. Read values with `[key](map)`.
|
||||
|-------|----------|
|
||||
| fruit | vegetable |
|
||||
|
||||
**`k` = [apple](kinds)**
|
||||
**`k` = [apple](access(kinds, "apple"))**
|
||||
|
||||
> print text=`k`
|
||||
|
||||
**`k` = [cucumber](kinds)**
|
||||
**`k` = [cucumber](access(kinds, "cucumber"))**
|
||||
|
||||
> print text=`k`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 字典(横表)
|
||||
description: 多列表是字典;链接取元
|
||||
---
|
||||
@@ -13,10 +14,10 @@ description: 多列表是字典;链接取元
|
||||
|------|------|
|
||||
| 水果 | 蔬菜 |
|
||||
|
||||
**`种` = [苹果](分类)**
|
||||
**`种` = [苹果](access(分类, "苹果"))**
|
||||
|
||||
> 打印 内容=`种`
|
||||
|
||||
**`种` = [黄瓜](分类)**
|
||||
**`种` = [黄瓜](access(分类, "黄瓜"))**
|
||||
|
||||
> 打印 内容=`种`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Row records
|
||||
description: First header @ / row makes a list of maps
|
||||
---
|
||||
@@ -14,10 +15,10 @@ When the first header is `@` or `row`, each data row is a map (marker column is
|
||||
| 1 | apple | 2 |
|
||||
| 2 | pear | 3 |
|
||||
|
||||
**`n` = [name]([1](orders))**
|
||||
**`n` = [name](access([1](access(orders, "1")), "name"))**
|
||||
|
||||
> print text=`n`
|
||||
|
||||
**`q` = [qty]([2](orders))**
|
||||
**`q` = [qty](access([2](access(orders, "2")), "qty"))**
|
||||
|
||||
> print text=`q`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 行向记录表
|
||||
description: 首列表头「行」→ 每行一个字典
|
||||
---
|
||||
@@ -14,10 +15,10 @@ description: 首列表头「行」→ 每行一个字典
|
||||
| 1 | 苹果 | 2 |
|
||||
| 2 | 梨 | 3 |
|
||||
|
||||
**`名` = [品名]([1](订单))**
|
||||
**`名` = [品名](access([1](access(订单, "1")), "品名"))**
|
||||
|
||||
> 打印 内容=`名`
|
||||
|
||||
**`量` = [数量]([2](订单))**
|
||||
**`量` = [数量](access([2](access(订单, "2")), "数量"))**
|
||||
|
||||
> 打印 内容=`量`
|
||||
@@ -218,6 +218,8 @@ pub enum HostFn {
|
||||
ForeignSessionClose = 209,
|
||||
ForeignSessionList = 210,
|
||||
ForeignSessionInterrupt = 211,
|
||||
/// `<TAB>` M7: `access(集合, 键)` — polymorphic collection access (legacy index).
|
||||
Access,
|
||||
}
|
||||
|
||||
|
||||
@@ -426,6 +428,7 @@ impl HostFn {
|
||||
209 => Self::ForeignSessionClose,
|
||||
210 => Self::ForeignSessionList,
|
||||
211 => Self::ForeignSessionInterrupt,
|
||||
212 => Self::Access,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -525,6 +528,7 @@ impl HostFn {
|
||||
"host_plugin_load" | "plugin_load" => Self::PluginLoad,
|
||||
"host_plugin_unload" | "plugin_unload" => Self::PluginUnload,
|
||||
"host_plugin_list" | "plugin_list" => Self::PluginList,
|
||||
"host_access" | "access" | "取" | "取值" => Self::Access,
|
||||
"host_ext_native_path" | "ext_native_path" => Self::ExtNativePath,
|
||||
"host_map_set" | "map_set" => Self::MapSet,
|
||||
"host_list_append" | "list_append" => Self::ListAppend,
|
||||
@@ -647,6 +651,7 @@ impl HostFn {
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Access => "host_access",
|
||||
Self::ReadText => "host_read_text",
|
||||
Self::WriteText => "host_write_text",
|
||||
Self::AppendText => "host_append_text",
|
||||
@@ -854,6 +859,7 @@ impl HostFn {
|
||||
|
||||
pub fn required_params(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::Access => &["value", "key"],
|
||||
Self::ReadText | Self::Exists | Self::ListDir | Self::MakeDir | Self::Remove => {
|
||||
&["path"]
|
||||
}
|
||||
@@ -1098,6 +1104,15 @@ pub fn call_host(
|
||||
bound: &HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
match fn_id {
|
||||
HostFn::Access => {
|
||||
let base = require(bound, "value")?;
|
||||
let key = match require(bound, "key")? {
|
||||
Value::Text(t) => t.clone(),
|
||||
Value::Int(i) => i.to_string(),
|
||||
other => crate::builtin::builtin_str(other).as_display(),
|
||||
};
|
||||
crate::builtin::builtin_footnote_get(base, &key)
|
||||
}
|
||||
HostFn::ReadText => fs::read_text(ctx, require(bound, "path")?),
|
||||
HostFn::WriteText => {
|
||||
fs::write_text(ctx, require(bound, "path")?, require(bound, "text")?)
|
||||
|
||||
@@ -1185,28 +1185,6 @@ impl Interpreter {
|
||||
}
|
||||
|
||||
match call.callee.as_str() {
|
||||
// `<TAB>` M3: `access(集合, 键)` — the exact polymorphism of the
|
||||
// legacy `[键](集合)` index (map key / 1-based list index, error on
|
||||
// missing). Migration rewrites legacy indexes to this call, so the
|
||||
// two must stay semantically identical.
|
||||
"access" | "取" | "取值" => {
|
||||
let bound = bind_args(&["value".into(), "key".into()], &ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let base = bound
|
||||
.get("value")
|
||||
.cloned()
|
||||
.ok_or_else(|| self.err("access requires value (collection)"))?;
|
||||
let key = bound
|
||||
.get("key")
|
||||
.map(|v| match v {
|
||||
Value::Text(t) => t.clone(),
|
||||
Value::Int(i) => i.to_string(),
|
||||
other => other.as_display(),
|
||||
})
|
||||
.ok_or_else(|| self.err("access requires key"))?;
|
||||
return crate::builtin::builtin_footnote_get(&base, &key)
|
||||
.map_err(|m| self.err(m));
|
||||
}
|
||||
"print" => {
|
||||
let bound = bind_args(&["text".into()], &ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
pub mod aliases;
|
||||
pub mod artifact;
|
||||
pub mod label;
|
||||
pub mod migrate;
|
||||
pub mod ast;
|
||||
pub mod binding;
|
||||
pub mod browser_session;
|
||||
|
||||
+37
-2
@@ -38,7 +38,9 @@ fn load_module_inner(
|
||||
let result = (|| {
|
||||
let source = read_module_source(path)
|
||||
.with_context(|| format!("failed to read {}", path.display()))?;
|
||||
let mut module = parse_source(&source).map_err(|e| attach_path(path, e))?;
|
||||
let markup = frontmatter_markup(&source);
|
||||
let mut module = crate::parse::expr::with_markup(markup, || parse_source(&source))
|
||||
.map_err(|e| attach_path(path, e))?;
|
||||
|
||||
// Resolve Artifact Metadata bindings (entry and imports share the same ctx).
|
||||
let file_ctx = BindingContext {
|
||||
@@ -285,6 +287,37 @@ fn label_error(label: &str, e: anyhow::Error) -> anyhow::Error {
|
||||
}
|
||||
}
|
||||
|
||||
/// Effective markup mode declared by the file itself. `<TAB>` M7
|
||||
///
|
||||
/// Looks for `markup: occlusion` (or `标记: 遮蔽`) inside the leading frontmatter
|
||||
/// block. Files that say nothing keep the process default (classic today), so a
|
||||
/// repository can migrate file by file without any silent shape change.
|
||||
fn frontmatter_markup(source: &str) -> crate::parse::expr::Markup {
|
||||
use crate::parse::expr::Markup;
|
||||
let mut lines = source.lines();
|
||||
if lines.next().map(|l| l.trim_end()) != Some("---") {
|
||||
return crate::parse::expr::markup_default();
|
||||
}
|
||||
for line in lines {
|
||||
let t = line.trim();
|
||||
if t == "---" {
|
||||
break;
|
||||
}
|
||||
let lower = t.to_ascii_lowercase();
|
||||
for key in ["markup:", "标记:"] {
|
||||
if let Some(rest) = lower.strip_prefix(key) {
|
||||
let val = rest.trim();
|
||||
return if matches!(val, "occlusion" | "purity" | "遮蔽" | "纯度") {
|
||||
Markup::Occlusion
|
||||
} else {
|
||||
Markup::Classic
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::parse::expr::markup_default()
|
||||
}
|
||||
|
||||
fn load_module_from_source_inner(
|
||||
source: &str,
|
||||
label: &str,
|
||||
@@ -297,7 +330,9 @@ fn load_module_from_source_inner(
|
||||
}
|
||||
|
||||
let result = (|| {
|
||||
let mut module = parse_source(source).map_err(|e| label_error(label, e))?;
|
||||
let markup = frontmatter_markup(source);
|
||||
let mut module = crate::parse::expr::with_markup(markup, || parse_source(source))
|
||||
.map_err(|e| label_error(label, e))?;
|
||||
module.metadata = resolve_metadata(&module.metadata_raw, ctx, Span::new(1, 1))
|
||||
.map_err(|e| label_error(label, e))?;
|
||||
let imports = module.imports.clone();
|
||||
|
||||
+77
@@ -41,6 +41,22 @@ impl From<BackendCli> for Backend {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum MigrateAction {
|
||||
/// `[键](集合)` → `access(集合, 键)`;`- [项](集合)` → `- [项](遍历 集合 为 项)`
|
||||
Labels {
|
||||
#[arg(value_name = "PATH", default_value = ".")]
|
||||
path: PathBuf,
|
||||
/// Actually rewrite files (default: dry run)
|
||||
#[arg(long)]
|
||||
write: bool,
|
||||
/// One JSON object on stdout
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum Commands {
|
||||
/// Execute a Marqdo source file (defaults to ./index.mq.md)
|
||||
@@ -127,6 +143,11 @@ enum Commands {
|
||||
#[arg(long)]
|
||||
count: bool,
|
||||
},
|
||||
/// Migrate legacy syntax to the purity forms (`<TAB>` M7)
|
||||
Migrate {
|
||||
#[command(subcommand)]
|
||||
action: MigrateAction,
|
||||
},
|
||||
/// MLSP for AI: line-delimited JSON on stdio (locate / syntax / validate / repair_targets / schema)
|
||||
Mlsp,
|
||||
/// Browse `.mq.md` structure + execution (live server or static output)
|
||||
@@ -642,6 +663,62 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
Commands::Migrate { action } => match action {
|
||||
MigrateAction::Labels { path, write, json } => {
|
||||
let reports = marqdo::migrate::migrate_path(&path, write)?;
|
||||
let (mut idx, mut loops, mut applied) = (0usize, 0usize, 0usize);
|
||||
for r in &reports {
|
||||
idx += r.indexes;
|
||||
loops += r.loops;
|
||||
applied += usize::from(r.applied);
|
||||
}
|
||||
if json {
|
||||
let arr: Vec<serde_json::Value> = reports
|
||||
.iter()
|
||||
.filter(|r| r.indexes > 0 || r.loops > 0 || r.note.is_some())
|
||||
.map(|r| {
|
||||
serde_json::json!({
|
||||
"file": r.file.display().to_string(),
|
||||
"indexes": r.indexes,
|
||||
"loops": r.loops,
|
||||
"applied": r.applied,
|
||||
"note": r.note,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
println!("{}", serde_json::Value::Array(arr));
|
||||
} else {
|
||||
for r in &reports {
|
||||
if r.indexes == 0 && r.loops == 0 {
|
||||
continue;
|
||||
}
|
||||
let state = if r.applied {
|
||||
"written"
|
||||
} else if r.note.is_some() {
|
||||
"skipped"
|
||||
} else {
|
||||
"would change"
|
||||
};
|
||||
println!(
|
||||
"{} indexes={} loops={} {}{}",
|
||||
r.file.display(),
|
||||
r.indexes,
|
||||
r.loops,
|
||||
state,
|
||||
r.note
|
||||
.as_ref()
|
||||
.map(|n| format!(" ({n})"))
|
||||
.unwrap_or_default()
|
||||
);
|
||||
}
|
||||
println!(
|
||||
"migrate labels: {idx} index, {loops} loop, {applied} file written{}",
|
||||
if write { "" } else { " (dry run; pass --write)" }
|
||||
);
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
},
|
||||
Commands::Mlsp => {
|
||||
use std::io::{BufRead, Write};
|
||||
let stdin = std::io::stdin();
|
||||
|
||||
+621
@@ -0,0 +1,621 @@
|
||||
//! `<TAB>` M7: migrate legacy `[键](集合)` indexes and `- [项](集合)` loops to the
|
||||
//! purity forms (`access(集合, 键)` and `- [描述](遍历 集合 为 项)`), then mark
|
||||
//! the file `markup: occlusion`.
|
||||
//!
|
||||
//! Safety model: **transform, re-parse, prove equivalence, then write.**
|
||||
//! The transformed file is parsed in occlusion mode and *denormalized* back to
|
||||
//! the legacy AST shape; if the denormalized AST is not byte-identical (Debug)
|
||||
//! to the original, the file is left untouched and reported.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::ast::{Arg, BranchArm, Expr, Function, IndexKey, Module, Stmt};
|
||||
|
||||
/// Outcome of migrating one file.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FileReport {
|
||||
pub file: PathBuf,
|
||||
pub indexes: usize,
|
||||
pub loops: usize,
|
||||
pub applied: bool,
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
fn has_marker(source: &str) -> bool {
|
||||
let mut lines = source.lines();
|
||||
if lines.next().map(|l| l.trim_end()) != Some("---") {
|
||||
return false;
|
||||
}
|
||||
for line in lines {
|
||||
let t = line.trim();
|
||||
if t == "---" {
|
||||
break;
|
||||
}
|
||||
let lower = t.to_ascii_lowercase();
|
||||
if lower.starts_with("markup:") || t.starts_with("标记:") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn add_marker(source: &str) -> String {
|
||||
if has_marker(source) {
|
||||
return source.to_string();
|
||||
}
|
||||
if let Some(rest) = source.strip_prefix("---\n") {
|
||||
format!("---\nmarkup: occlusion\n{rest}")
|
||||
} else {
|
||||
format!("---\nmarkup: occlusion\n---\n\n{source}")
|
||||
}
|
||||
}
|
||||
|
||||
/// Quote a static index key as a text argument.
|
||||
fn quote_key(key: &str) -> String {
|
||||
let escaped = key.replace('\\', "\\\\").replace('"', "\\\"");
|
||||
format!("\"{escaped}\"")
|
||||
}
|
||||
|
||||
/// Rewrite every link-shaped index in one code line. Returns `(new_line, count)`.
|
||||
///
|
||||
/// Works **innermost first**: chained indexes (`[content]([1]([messages](req)))`)
|
||||
/// must be rewritten from the inside out, otherwise outer rewrites invalidate the
|
||||
/// inner spans.
|
||||
fn rewrite_indexes(line: &str) -> (String, usize) {
|
||||
let mut cur = line.to_string();
|
||||
let mut total = 0usize;
|
||||
for _ in 0..256 {
|
||||
match rewrite_one_innermost(&cur) {
|
||||
Some(next) => {
|
||||
cur = next;
|
||||
total += 1;
|
||||
}
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
(cur, total)
|
||||
}
|
||||
|
||||
/// Rewrite the first index whose key contains no nested `[`, returning the new line.
|
||||
fn rewrite_one_innermost(line: &str) -> Option<String> {
|
||||
let chars: Vec<char> = line.chars().collect();
|
||||
let mut i = 0usize;
|
||||
let mut in_bt = false;
|
||||
let mut in_str = false;
|
||||
while i < chars.len() {
|
||||
let c = chars[i];
|
||||
if in_str {
|
||||
if c == '\\' {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if c == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if in_bt {
|
||||
if c == '`' {
|
||||
in_bt = false;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'`' => {
|
||||
in_bt = true;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
'"' => {
|
||||
in_str = true;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if c == '[' && chars.get(i + 1) != Some(&'^') {
|
||||
if let Some(close) = match_close(&chars, i, '[', ']') {
|
||||
let key: String = chars[i + 1..close].iter().collect();
|
||||
let nested = key.contains('[');
|
||||
if !nested && chars.get(close + 1) == Some(&'(') {
|
||||
if let Some(paren) = match_close(&chars, close + 1, '(', ')') {
|
||||
let coll: String = chars[close + 2..paren].iter().collect();
|
||||
// Already migrated (`[k](access(…))`) — never rewrite twice.
|
||||
if coll.trim_start().starts_with("access(") {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let k = key.trim();
|
||||
let backticked = k.starts_with('`') && k.ends_with('`') && k.len() >= 2;
|
||||
let label = if backticked { &k[1..k.len() - 1] } else { k };
|
||||
let key_arg = if backticked {
|
||||
k.to_string()
|
||||
} else {
|
||||
quote_key(k)
|
||||
};
|
||||
let replaced = format!(
|
||||
"[{label}](access({}, {key_arg}))",
|
||||
coll.trim()
|
||||
);
|
||||
let mut out = String::new();
|
||||
out.extend(chars[..i].iter());
|
||||
out.push_str(&replaced);
|
||||
out.extend(chars[paren + 1..].iter());
|
||||
return Some(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Rewrite only the **code** parts of a line.
|
||||
///
|
||||
/// Table rows are the important case: a cell is code only when it starts with
|
||||
/// `**…**`; everything else is prose (markdown links live there and must not be
|
||||
/// rewritten). Non-table code lines are rewritten whole.
|
||||
fn rewrite_code_segments(line: &str) -> (String, usize) {
|
||||
let trimmed = line.trim_start();
|
||||
if !trimmed.starts_with('|') {
|
||||
return rewrite_indexes(line);
|
||||
}
|
||||
let mut out = String::with_capacity(line.len());
|
||||
let mut total = 0usize;
|
||||
let mut rest = line;
|
||||
while let Some(pos) = rest.find('|') {
|
||||
let (cell, tail) = rest.split_at(pos);
|
||||
out.push_str(cell);
|
||||
out.push('|');
|
||||
rest = &tail[1..];
|
||||
}
|
||||
// Trailing part without a separator.
|
||||
out.push_str(rest);
|
||||
// Second pass: rewrite only `**…**` runs inside the rebuilt line.
|
||||
let mut result = String::with_capacity(out.len());
|
||||
let mut s = out.as_str();
|
||||
while let Some(open) = s.find("**") {
|
||||
result.push_str(&s[..open + 2]);
|
||||
let after = &s[open + 2..];
|
||||
let Some(close) = after.find("**") else {
|
||||
result.push_str(after);
|
||||
return (result, total);
|
||||
};
|
||||
let (inner, tail) = after.split_at(close);
|
||||
let (rewritten, n) = rewrite_indexes(inner);
|
||||
total += n;
|
||||
result.push_str(&rewritten);
|
||||
result.push_str("**");
|
||||
s = &tail[2..];
|
||||
}
|
||||
result.push_str(s);
|
||||
(result, total)
|
||||
}
|
||||
|
||||
/// Matching closer index for `open` at `start`, honouring nesting of the pair.
|
||||
fn match_close(bytes: &[char], start: usize, open: char, close: char) -> Option<usize> {
|
||||
let mut depth = 0i32;
|
||||
let mut i = start;
|
||||
let mut in_bt = false;
|
||||
let mut in_str = false;
|
||||
while i < bytes.len() {
|
||||
let c = bytes[i];
|
||||
if in_str {
|
||||
if c == '\\' {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if c == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if in_bt {
|
||||
if c == '`' {
|
||||
in_bt = false;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'`' => in_bt = true,
|
||||
'"' => in_str = true,
|
||||
c if c == open => depth += 1,
|
||||
c if c == close => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Rewrite a legacy loop line `- [x](c)` → `- [x](遍历 c 为 x)`.
|
||||
fn rewrite_loop(line: &str) -> Option<String> {
|
||||
let trimmed = line.trim_start();
|
||||
let rest = trimmed.strip_prefix('-')?.trim_start();
|
||||
if !rest.starts_with('[') {
|
||||
return None;
|
||||
}
|
||||
let end = rest.find(']')?;
|
||||
let item = rest[1..end].trim();
|
||||
let after = rest[end + 1..].trim();
|
||||
if !after.starts_with('(') || !after.ends_with(')') {
|
||||
return None;
|
||||
}
|
||||
let coll = after[1..after.len() - 1].trim();
|
||||
if item.is_empty() || coll.is_empty() || says_foreach(coll) {
|
||||
return None;
|
||||
}
|
||||
let indent = &line[..line.len() - trimmed.len()];
|
||||
let shown = item.trim_matches('`').to_string();
|
||||
Some(format!(
|
||||
"{indent}- [{shown}](遍历 {coll} 为 {item})"
|
||||
))
|
||||
}
|
||||
|
||||
fn says_foreach(s: &str) -> bool {
|
||||
s.starts_with("遍历") || s.starts_with("for ")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Equivalence proof: denormalize the migrated AST back to the legacy shape.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn denorm_expr(expr: &Expr) -> Expr {
|
||||
match expr {
|
||||
Expr::Occluded { label, payload } => match payload.as_deref() {
|
||||
Some(Expr::Call(call))
|
||||
if (call.callee == "access" || call.callee == "取" || call.callee == "取值")
|
||||
&& call.args.len() == 2 =>
|
||||
{
|
||||
let mut it = call.args.iter();
|
||||
let (base, key) = match (it.next(), it.next()) {
|
||||
(Some(Arg::Positional(b)), Some(Arg::Positional(k))) => (b, k),
|
||||
_ => return expr.clone(),
|
||||
};
|
||||
let key_label = match key {
|
||||
Expr::Literal(crate::ast::Literal::Text(t)) if t == label => Some(IndexKey::Lit(t.clone())),
|
||||
Expr::Var(v) if v == label => Some(IndexKey::Var(v.clone())),
|
||||
_ => None,
|
||||
};
|
||||
match key_label {
|
||||
Some(k) => Expr::Index {
|
||||
base: Box::new(denorm_expr(base)),
|
||||
label: k,
|
||||
},
|
||||
None => expr.clone(),
|
||||
}
|
||||
}
|
||||
Some(inner) => Expr::Occluded {
|
||||
label: label.clone(),
|
||||
payload: Some(Box::new(denorm_expr(inner))),
|
||||
},
|
||||
None => expr.clone(),
|
||||
},
|
||||
Expr::Unary { op, expr } => Expr::Unary {
|
||||
op: *op,
|
||||
expr: Box::new(denorm_expr(expr)),
|
||||
},
|
||||
Expr::Binary { op, left, right } => Expr::Binary {
|
||||
op: *op,
|
||||
left: Box::new(denorm_expr(left)),
|
||||
right: Box::new(denorm_expr(right)),
|
||||
},
|
||||
Expr::Call(call) => {
|
||||
let mut c = call.clone();
|
||||
c.args = c
|
||||
.args
|
||||
.into_iter()
|
||||
.map(|a| match a {
|
||||
Arg::Positional(e) => Arg::Positional(denorm_expr(&e)),
|
||||
Arg::Named { name, value } => Arg::Named {
|
||||
name,
|
||||
value: denorm_expr(&value),
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
Expr::Call(c)
|
||||
}
|
||||
Expr::List(items) => Expr::List(items.iter().map(denorm_expr).collect()),
|
||||
Expr::Map(pairs) => Expr::Map(
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), denorm_expr(v)))
|
||||
.collect(),
|
||||
),
|
||||
Expr::Index { base, label } => Expr::Index {
|
||||
base: Box::new(denorm_expr(base)),
|
||||
label: label.clone(),
|
||||
},
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn denorm_stmt(stmt: &Stmt) -> Stmt {
|
||||
match stmt {
|
||||
Stmt::Assign {
|
||||
name,
|
||||
value,
|
||||
span,
|
||||
end_line,
|
||||
} => Stmt::Assign {
|
||||
name: name.clone(),
|
||||
value: denorm_expr(value),
|
||||
span: *span,
|
||||
end_line: *end_line,
|
||||
},
|
||||
Stmt::Return { value, span } => Stmt::Return {
|
||||
value: denorm_expr(value),
|
||||
span: *span,
|
||||
},
|
||||
Stmt::Expr { value, span } => Stmt::Expr {
|
||||
value: denorm_expr(value),
|
||||
span: *span,
|
||||
},
|
||||
Stmt::Call { call, span } => {
|
||||
let mut c = call.clone();
|
||||
c.args = c
|
||||
.args
|
||||
.into_iter()
|
||||
.map(|a| match a {
|
||||
Arg::Positional(e) => Arg::Positional(denorm_expr(&e)),
|
||||
Arg::Named { name, value } => Arg::Named {
|
||||
name,
|
||||
value: denorm_expr(&value),
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
Stmt::Call { call: c, span: *span }
|
||||
}
|
||||
Stmt::Branch { arms, span } => Stmt::Branch {
|
||||
arms: arms
|
||||
.iter()
|
||||
.map(|a| BranchArm {
|
||||
condition: a.condition.as_ref().map(denorm_expr),
|
||||
body: a.body.iter().map(denorm_stmt).collect(),
|
||||
})
|
||||
.collect(),
|
||||
span: *span,
|
||||
},
|
||||
Stmt::While {
|
||||
condition,
|
||||
body,
|
||||
span,
|
||||
} => Stmt::While {
|
||||
condition: denorm_expr(condition),
|
||||
body: body.iter().map(denorm_stmt).collect(),
|
||||
span: *span,
|
||||
},
|
||||
Stmt::ForEach {
|
||||
item,
|
||||
collection,
|
||||
label: _,
|
||||
body,
|
||||
span,
|
||||
} => Stmt::ForEach {
|
||||
item: item.clone(),
|
||||
collection: collection.clone(),
|
||||
label: None,
|
||||
body: body.iter().map(denorm_stmt).collect(),
|
||||
span: *span,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn denorm_fun(fun: &Function) -> Function {
|
||||
let mut f = fun.clone();
|
||||
f.body = fun.body.iter().map(denorm_stmt).collect();
|
||||
f.children = fun.children.iter().map(denorm_fun).collect();
|
||||
f
|
||||
}
|
||||
|
||||
/// Replace every `line: <n>` with `line: #` so that inserting the frontmatter
|
||||
/// marker (which shifts every line by one) does not defeat the comparison.
|
||||
fn strip_line_numbers(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut rest = s;
|
||||
while let Some(i) = rest.find("line: ") {
|
||||
out.push_str(&rest[..i + 6]);
|
||||
let tail = &rest[i + 6..];
|
||||
let end = tail
|
||||
.find(|c: char| !c.is_ascii_digit())
|
||||
.unwrap_or(tail.len());
|
||||
out.push('#');
|
||||
rest = &tail[end..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
fn shape(module: &Module) -> String {
|
||||
let raw = format!(
|
||||
"{:?}",
|
||||
module.functions.iter().map(denorm_fun).collect::<Vec<_>>()
|
||||
);
|
||||
strip_line_numbers(&raw)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Entry point
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Migrate one file. `write=false` performs a dry run (still fully verified).
|
||||
pub fn migrate_file(path: &Path, write: bool) -> anyhow::Result<FileReport> {
|
||||
let source = std::fs::read_to_string(path)?;
|
||||
let mut report = FileReport {
|
||||
file: path.to_path_buf(),
|
||||
indexes: 0,
|
||||
loops: 0,
|
||||
applied: false,
|
||||
note: None,
|
||||
};
|
||||
if has_marker(&source) {
|
||||
report.note = Some("already marked `markup: occlusion`".into());
|
||||
return Ok(report);
|
||||
}
|
||||
|
||||
// The original must be readable in classic mode (that is what it means today).
|
||||
let original = crate::parse::expr::with_markup(crate::parse::expr::Markup::Classic, || {
|
||||
crate::load::load_module(path)
|
||||
})?;
|
||||
|
||||
let classified = crate::lex::classify_source(&source);
|
||||
let mut lines: Vec<String> = source.lines().map(|l| l.to_string()).collect();
|
||||
for cl in &classified {
|
||||
if cl.kind != crate::lex::LineKind::Code {
|
||||
continue;
|
||||
}
|
||||
let idx = (cl.line_no as usize).saturating_sub(1);
|
||||
let Some(line) = lines.get(idx).cloned() else {
|
||||
continue;
|
||||
};
|
||||
if let Some(new_loop) = rewrite_loop(&line) {
|
||||
report.loops += 1;
|
||||
lines[idx] = new_loop;
|
||||
continue;
|
||||
}
|
||||
let (new_line, n) = rewrite_code_segments(&line);
|
||||
if n > 0 {
|
||||
report.indexes += n;
|
||||
lines[idx] = new_line;
|
||||
}
|
||||
}
|
||||
if report.indexes == 0 && report.loops == 0 {
|
||||
report.note = Some("no legacy index or loop".into());
|
||||
return Ok(report);
|
||||
}
|
||||
|
||||
let mut body = lines.join("\n");
|
||||
if source.ends_with('\n') {
|
||||
body.push('\n');
|
||||
}
|
||||
let migrated = add_marker(&body);
|
||||
|
||||
// Prove equivalence: the migrated file, parsed in occlusion mode and
|
||||
// denormalized, must be structurally identical to the original.
|
||||
let reparsed = crate::parse::expr::with_markup(crate::parse::expr::Markup::Occlusion, || {
|
||||
crate::load::load_module_from_source(&migrated)
|
||||
})?;
|
||||
if std::env::var("MARQDO_MIGRATE_DEBUG").is_ok() {
|
||||
eprintln!("ORIG: {}", shape(&original));
|
||||
eprintln!("MIGR: {}", shape(&reparsed));
|
||||
}
|
||||
if shape(&original) != shape(&reparsed) {
|
||||
report.note = Some("equivalence check failed — file left untouched".into());
|
||||
return Ok(report);
|
||||
}
|
||||
|
||||
if write {
|
||||
std::fs::write(path, &migrated)?;
|
||||
report.applied = true;
|
||||
}
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Recursively migrate every `*.mq.md` under `path`.
|
||||
pub fn migrate_path(path: &Path, write: bool) -> anyhow::Result<Vec<FileReport>> {
|
||||
let files = crate::migrate::collect_files(path);
|
||||
let mut out = Vec::new();
|
||||
for f in files {
|
||||
match migrate_file(&f, write) {
|
||||
Ok(r) => out.push(r),
|
||||
Err(e) => out.push(FileReport {
|
||||
file: f,
|
||||
indexes: 0,
|
||||
loops: 0,
|
||||
applied: false,
|
||||
note: Some(format!("load failed: {e:#}")),
|
||||
}),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Collect `*.mq.md` under `path` (file → itself).
|
||||
pub fn collect_files(path: &Path) -> Vec<PathBuf> {
|
||||
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(rd) = std::fs::read_dir(dir) else { return };
|
||||
for e in rd.flatten() {
|
||||
let p = e.path();
|
||||
let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
|
||||
if p.is_dir() {
|
||||
if matches!(name, "target" | "dist" | "node_modules" | ".git" | ".marqdo") {
|
||||
continue;
|
||||
}
|
||||
walk(&p, out);
|
||||
} else if name.ends_with(".mq.md") {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
if path.is_file() {
|
||||
return vec![path.to_path_buf()];
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(path, &mut out);
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{rewrite_indexes, rewrite_loop};
|
||||
|
||||
#[test]
|
||||
fn rewrites_static_key() {
|
||||
let (out, n) = rewrite_indexes("**v = [键](`表`)**");
|
||||
assert_eq!(n, 1);
|
||||
assert_eq!(out, "**v = [键](access(`表`, \"键\"))**");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_dynamic_key_without_backticks_in_label() {
|
||||
let (out, n) = rewrite_indexes("**v = [`名`](`表`)**");
|
||||
assert_eq!(n, 1);
|
||||
assert_eq!(out, "**v = [名](access(`表`, `名`))**");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_nested_indexes_inside_out() {
|
||||
let (out, n) = rewrite_indexes("**v = [content]([1]([messages](`req`)))**");
|
||||
assert_eq!(n, 3);
|
||||
assert_eq!(
|
||||
out,
|
||||
"**v = [content](access([1](access([messages](access(`req`, \"messages\")), \"1\")), \"content\"))**"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_rewrites_already_migrated() {
|
||||
let (out, n) = rewrite_indexes("**v = [键](access(`表`, \"键\"))**");
|
||||
assert_eq!(n, 0);
|
||||
assert_eq!(out, "**v = [键](access(`表`, \"键\"))**");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_prose_links_alone() {
|
||||
let (out, n) = rewrite_indexes("see [docs](https://example.com) for more");
|
||||
assert_eq!(n, 1, "plain code lines are rewritten…");
|
||||
// …but the table-cell path only touches `**…**` runs, which is what the
|
||||
// real corpus needs (see rewrite_code_segments).
|
||||
let _ = out;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_loop() {
|
||||
let got = rewrite_loop("- [果](`列`)").unwrap();
|
||||
assert_eq!(got, "- [果](遍历 `列` 为 果)");
|
||||
// Already migrated / narrative loops stay untouched.
|
||||
assert!(rewrite_loop("- [果](遍历 `列` 为 果)").is_none());
|
||||
assert!(rewrite_loop("not a loop").is_none());
|
||||
}
|
||||
}
|
||||
+61
-5
@@ -33,7 +33,26 @@ pub fn set_markup_default(m: Markup) {
|
||||
);
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Per-module override (`markup:` in frontmatter) — wins over the process default.
|
||||
static MARKUP_OVERRIDE: std::cell::Cell<Option<Markup>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// Run `f` with `markup` as the effective mode for everything parsed inside.
|
||||
///
|
||||
/// Frontmatter `markup: occlusion` uses this so that one process can load files
|
||||
/// in different modes (imports!). `<TAB>` M7
|
||||
pub fn with_markup<T>(markup: Markup, f: impl FnOnce() -> T) -> T {
|
||||
let saved = MARKUP_OVERRIDE.with(|c| c.replace(Some(markup)));
|
||||
let out = f();
|
||||
MARKUP_OVERRIDE.with(|c| c.set(saved));
|
||||
out
|
||||
}
|
||||
|
||||
pub fn markup_default() -> Markup {
|
||||
if let Some(m) = MARKUP_OVERRIDE.with(|c| c.get()) {
|
||||
return m;
|
||||
}
|
||||
match MARKUP.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
1 => Markup::Occlusion,
|
||||
_ => Markup::Classic,
|
||||
@@ -517,7 +536,7 @@ impl<'a> Parser<'a> {
|
||||
// Link-shaped index `[key](collection)` vs bracket-marked call `[callee] …`
|
||||
// vs JSON-ish `[…]` (arg text fallback when expr parse fails).
|
||||
if self.starts_with("[") && !self.starts_with("[^") {
|
||||
if self.markup == Markup::Occlusion {
|
||||
if self.markup == Markup::Occlusion && occlusion_shape_ahead(self.rest()) {
|
||||
return self.parse_occluded();
|
||||
}
|
||||
if link_index_shape_ahead(self.rest()) {
|
||||
@@ -722,7 +741,13 @@ impl<'a> Parser<'a> {
|
||||
payload: None,
|
||||
});
|
||||
}
|
||||
let inner = self.parse_or()?;
|
||||
// `()` is machine code: the payload always allows `callee(args)` even
|
||||
// when the occlusion sits inside a text-like argument value. `<TAB>` M7
|
||||
let saved_allow = self.allow_paren_call;
|
||||
self.allow_paren_call = true;
|
||||
let inner = self.parse_or();
|
||||
self.allow_paren_call = saved_allow;
|
||||
let inner = inner?;
|
||||
self.skip_ws();
|
||||
if !self.eat(")") {
|
||||
bail!("expected ')' to close occlusion payload");
|
||||
@@ -1432,6 +1457,33 @@ fn split_first_token(s: &str, paren_mode: bool) -> (&str, &str) {
|
||||
}
|
||||
|
||||
/// `[key](…)` with no whitespace between `]` and `(`.
|
||||
/// True when `[…]` is immediately followed by `(` — i.e. an occlusion shape.
|
||||
/// `[问候] "Ada"` (bracket-marked call) has no `(`, so it keeps its meaning. `<TAB>` M7
|
||||
fn occlusion_shape_ahead(s: &str) -> bool {
|
||||
let mut chars = s.char_indices();
|
||||
let Some((_, '[')) = chars.next() else {
|
||||
return false;
|
||||
};
|
||||
let mut escaped = false;
|
||||
for (i, c) in chars {
|
||||
if escaped {
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'\\' => escaped = true,
|
||||
']' => {
|
||||
// Strict: `(` must follow immediately. `[问候] ([…])` is a
|
||||
// bracket-marked call with a parenthesised argument, not an occlusion.
|
||||
return s[i + 1..].starts_with('(');
|
||||
}
|
||||
'\n' => return false,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn link_index_shape_ahead(s: &str) -> bool {
|
||||
let s = s.trim_start();
|
||||
if !s.starts_with('[') || s.starts_with("[^") {
|
||||
@@ -2124,9 +2176,13 @@ mod bracket_call_tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn occlusion_requires_paren() {
|
||||
let err = parse_expr_markup("[只有描述]", false, Markup::Occlusion).unwrap_err();
|
||||
assert!(err.to_string().contains("followed by"), "{err}");
|
||||
fn occlusion_requires_immediate_paren() {
|
||||
// No `(` after `]` → falls back to the bracket-marked call form.
|
||||
let e = parse_expr_markup("[只有描述]", false, Markup::Occlusion).unwrap();
|
||||
assert!(matches!(e, Expr::Call(_)), "got {e:?}");
|
||||
// A space before `(` also means "not an occlusion".
|
||||
let e = parse_expr_markup("[问候] (1)", false, Markup::Occlusion).unwrap();
|
||||
assert!(matches!(e, Expr::Call(_)), "got {e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: promote requires sandbox proof (O2)
|
||||
description: >
|
||||
Good workbook promotes; broken workbook is rejected (sandbox_proof_failed).
|
||||
@@ -25,11 +26,11 @@ import sys:lib/sys.mq.md
|
||||
**_ = 0**
|
||||
|
||||
**prom = agent_kb_promote kb_dir=`kb` goal="sandbox promote good" workbook="sandbox-fixtures/promote-good.mq.md"**
|
||||
**ok = [promoted](prom)**
|
||||
**ok = [promoted](access(prom, "promoted"))**
|
||||
> print text=`ok`
|
||||
|
||||
**rej = agent_kb_promote kb_dir=`kb` goal="sandbox promote bad" workbook="sandbox-fixtures/promote-bad.mq.md"**
|
||||
**rej_ok = [promoted](rej)**
|
||||
**reason = [reason](rej)**
|
||||
**rej_ok = [promoted](access(rej, "promoted"))**
|
||||
**reason = [reason](access(rej, "reason"))**
|
||||
> print text=`rej_ok`
|
||||
> print text=`reason`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: O5 quarantine skill status
|
||||
description: Promote good skill then quarantine — status becomes quarantine.
|
||||
import plugin:lib/plugin.mq.md
|
||||
@@ -23,12 +24,12 @@ import sys:lib/sys.mq.md
|
||||
**_ = 0**
|
||||
|
||||
**prom = agent_kb_promote kb_dir=`kb` goal="quarantine demo" workbook="sandbox-fixtures/promote-good.mq.md"**
|
||||
**ok = [promoted](prom)**
|
||||
**slug = [slug](prom)**
|
||||
**ok = [promoted](access(prom, "promoted"))**
|
||||
**slug = [slug](access(prom, "slug"))**
|
||||
> print text=`ok`
|
||||
|
||||
**q = agent_kb_quarantine kb_dir=`kb` slug=`slug` reason="fixture_regression"**
|
||||
**qok = [ok](q)**
|
||||
**st = [status](q)**
|
||||
**qok = [ok](access(q, "ok"))**
|
||||
**st = [status](access(q, "status"))**
|
||||
> print text=`qok`
|
||||
> print text=`st`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: table sort_by + cli
|
||||
import table:lib/table.mq.md
|
||||
import csv:lib/csv.mq.md
|
||||
@@ -11,12 +12,12 @@ import cli:lib/cli.mq.md
|
||||
**rows = > csv.parse text=`raw`**
|
||||
**rows = > table.sort_by list=`rows` key="name"**
|
||||
**r0 = > at value=`rows` index=0**
|
||||
> print text=[name](`r0`)
|
||||
> print text=[name](access(`r0`, "name"))
|
||||
|
||||
**args = > split value="--input,data.csv,rest,--verbose" sep=","**
|
||||
**flags = > cli.parse args=`args`**
|
||||
> print text=[input](`flags`)
|
||||
> print text=[verbose](`flags`)
|
||||
**pos = [_](`flags`)**
|
||||
> print text=[input](access(`flags`, "input"))
|
||||
> print text=[verbose](access(`flags`, "verbose"))
|
||||
**pos = [_](access(`flags`, "_"))**
|
||||
**p0 = > at value=`pos` index=0**
|
||||
> print text=`p0`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: lib/csv smoke
|
||||
import csv:lib/csv.mq.md
|
||||
---
|
||||
@@ -12,8 +13,8 @@ import csv:lib/csv.mq.md
|
||||
> print text=`n`
|
||||
|
||||
**r0 = > at value=`rows` index=0**
|
||||
> print text=[name](`r0`)
|
||||
> print text=[note](`r0`)
|
||||
> print text=[name](access(`r0`, "name"))
|
||||
> print text=[note](access(`r0`, "note"))
|
||||
|
||||
**out = > csv.stringify rows=`rows`**
|
||||
**rows2 = > csv.parse text=`out`**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: lib/datetime smoke
|
||||
import dt:lib/datetime.mq.md
|
||||
---
|
||||
@@ -6,10 +7,10 @@ import dt:lib/datetime.mq.md
|
||||
# main
|
||||
|
||||
**m = > dt.from_unix unix=0**
|
||||
> print text=[iso](`m`)
|
||||
> print text=[iso](access(`m`, "iso"))
|
||||
|
||||
**sh = > dt.in_zone dt=`m` zone="Asia/Shanghai"**
|
||||
> print text=[iso](`sh`)
|
||||
> print text=[iso](access(`sh`, "iso"))
|
||||
|
||||
**p = > dt.parse text="2020-01-02T03:04:05+08:00"**
|
||||
**u = > dt.to_unix dt=`p`**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: foreign config load
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
@@ -9,4 +10,4 @@ import foreign:lib/foreign.mq.md
|
||||
> print text=`载入`
|
||||
|
||||
**运行 = > foreign.invoke lang="tinycfg" source="console.log('cfg')"**
|
||||
> print text=[stdout](`运行`)
|
||||
> print text=[stdout](access(`运行`, "stdout"))
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: foreign env cwd timeout
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
@@ -17,7 +18,7 @@ console.log(process.env.MODE + "|" + process.env.MARQDO_FOREIGN_LANG);
|
||||
```
|
||||
|
||||
**检查 = > foreign.invoke code=`环境检查` env=`环境`**
|
||||
**检查输出 = > trim [stdout](`检查`)**
|
||||
**检查输出 = > trim [stdout](access(`检查`, "stdout"))**
|
||||
|
||||
> print text=`检查输出`
|
||||
|
||||
@@ -28,5 +29,5 @@ setTimeout(() => console.log("late"), 5000);
|
||||
|
||||
**超时 = > foreign.invoke code=`慢` timeout=0.5**
|
||||
|
||||
> print text=[ok](`超时`)
|
||||
> print text=[timed_out](`超时`)
|
||||
> print text=[ok](access(`超时`, "ok"))
|
||||
> print text=[timed_out](access(`超时`, "timed_out"))
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: foreign invoke record
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
@@ -13,7 +14,7 @@ process.exit(3);
|
||||
|
||||
**记录 = > foreign.invoke code=`失败`**
|
||||
|
||||
> print text=[ok](`记录`)
|
||||
> print text=[code](`记录`)
|
||||
> print text=[stderr](`记录`)
|
||||
> print text=[truncated](`记录`)
|
||||
> print text=[ok](access(`记录`, "ok"))
|
||||
> print text=[code](access(`记录`, "code"))
|
||||
> print text=[stderr](access(`记录`, "stderr"))
|
||||
> print text=[truncated](access(`记录`, "truncated"))
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: foreign invoke JSON input
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
@@ -25,8 +26,8 @@ process.stdin.on("end", () => {
|
||||
```
|
||||
|
||||
**记录 = > foreign.invoke code=`统计` input=`数值表` output="json"**
|
||||
**统计结果 = [result](`记录`)**
|
||||
**统计结果 = [result](access(`记录`, "result"))**
|
||||
|
||||
> print text=[ok](`记录`)
|
||||
> print text=[n](`统计结果`)
|
||||
> print text=[sum](`统计结果`)
|
||||
> print text=[ok](access(`记录`, "ok"))
|
||||
> print text=[n](access(`统计结果`, "n"))
|
||||
> print text=[sum](access(`统计结果`, "sum"))
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: foreign probe and register
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
@@ -6,8 +7,8 @@ import foreign:lib/foreign.mq.md
|
||||
# main
|
||||
|
||||
**探测 = > foreign.probe lang="node"**
|
||||
> print text=[ok](`探测`)
|
||||
> print text=[lang](`探测`)
|
||||
> print text=[ok](access(`探测`, "ok"))
|
||||
> print text=[lang](access(`探测`, "lang"))
|
||||
|
||||
`模板` =
|
||||
|
||||
@@ -19,6 +20,6 @@ import foreign:lib/foreign.mq.md
|
||||
|
||||
**> foreign.register lang="tiny" template=`模板`**
|
||||
**运行 = > foreign.invoke lang="tiny" source="console.log('tiny')"**
|
||||
**运行输出 = > trim [stdout](`运行`)**
|
||||
**运行输出 = > trim [stdout](access(`运行`, "stdout"))**
|
||||
> print text=`运行输出`
|
||||
**> foreign.unset lang="tiny"**
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: foreign python session
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
@@ -9,7 +10,7 @@ import foreign:lib/foreign.mq.md
|
||||
**设值 = > foreign.session_eval id=`会话` source="x = 41"**
|
||||
**求值 = > foreign.session_eval id=`会话` source="x + 1"**
|
||||
|
||||
> print text=[result](`求值`)
|
||||
> print text=[result](access(`求值`, "result"))
|
||||
|
||||
**> foreign.session_set id=`会话` name="y" value=5**
|
||||
**取值 = > foreign.session_get id=`会话` name="y"**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: foreign session timeout
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
@@ -8,6 +9,6 @@ import foreign:lib/foreign.mq.md
|
||||
**会话 = > foreign.session_open lang="node"**
|
||||
**慢 = > foreign.session_eval id=`会话` source="(async () => { await new Promise(r => setTimeout(r, 5000)); return 1; })()" timeout=0.3**
|
||||
|
||||
> print text=[ok](`慢`)
|
||||
> print text=[timed_out](`慢`)
|
||||
> print text=[alive](`慢`)
|
||||
> print text=[ok](access(`慢`, "ok"))
|
||||
> print text=[timed_out](access(`慢`, "timed_out"))
|
||||
> print text=[alive](access(`慢`, "alive"))
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: foreign persistent session
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
@@ -9,7 +10,7 @@ import foreign:lib/foreign.mq.md
|
||||
**设值 = > foreign.session_eval id=`会话` source="let x = 41"**
|
||||
**求值 = > foreign.session_eval id=`会话` source="x + 1"**
|
||||
|
||||
> print text=[result](`求值`)
|
||||
> print text=[result](access(`求值`, "result"))
|
||||
|
||||
**取x = > foreign.session_get id=`会话` name="x"**
|
||||
> print text=`取x`
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: fs mid2 M9 smoke
|
||||
import fs:lib/fs.mq.md
|
||||
---
|
||||
@@ -12,9 +13,9 @@ import fs:lib/fs.mq.md
|
||||
> fs.write_text path="m9-tree/nested/b.txt" text="B"
|
||||
|
||||
**st = > fs.stat path="m9-tree/a.txt"**
|
||||
> print text=[size](`st`)
|
||||
> print text=[is_file](`st`)
|
||||
> print text=[is_dir](`st`)
|
||||
> print text=[size](access(`st`, "size"))
|
||||
> print text=[is_file](access(`st`, "is_file"))
|
||||
> print text=[is_dir](access(`st`, "is_dir"))
|
||||
|
||||
**w = > fs.walk path="m9-tree"**
|
||||
**n = > len `w`**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: net cookie_parse
|
||||
import net:lib/net.mq.md
|
||||
---
|
||||
@@ -9,9 +10,9 @@ import net:lib/net.mq.md
|
||||
|
||||
**resp = > net.cookie_parse text="id=42; Path=/; HttpOnly; Secure; SameSite=Lax, theme=light; Max-Age=3600" is_response=True**
|
||||
|
||||
> print text=[name]([1](`req`))
|
||||
> print text=[value]([1](`req`))
|
||||
> print text=[http_only]([1](`resp`))
|
||||
> print text=[secure]([1](`resp`))
|
||||
> print text=[same_site]([1](`resp`))
|
||||
> print text=[max_age]([2](`resp`))
|
||||
> print text=[name](access([1](access(`req`, "1")), "name"))
|
||||
> print text=[value](access([1](access(`req`, "1")), "value"))
|
||||
> print text=[http_only](access([1](access(`resp`, "1")), "http_only"))
|
||||
> print text=[secure](access([1](access(`resp`, "1")), "secure"))
|
||||
> print text=[same_site](access([1](access(`resp`, "1")), "same_site"))
|
||||
> print text=[max_age](access([2](access(`resp`, "2")), "max_age"))
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: net multipart_parse
|
||||
import net:lib/net.mq.md
|
||||
---
|
||||
@@ -11,9 +12,9 @@ import net:lib/net.mq.md
|
||||
|
||||
**parts = > net.multipart_parse body=`body` boundary=`boundary`**
|
||||
|
||||
> print text=[name]([1](`parts`))
|
||||
> print text=[value]([1](`parts`))
|
||||
> print text=[name]([2](`parts`))
|
||||
> print text=[filename]([2](`parts`))
|
||||
> print text=[content_type]([2](`parts`))
|
||||
> print text=[value]([2](`parts`))
|
||||
> print text=[name](access([1](access(`parts`, "1")), "name"))
|
||||
> print text=[value](access([1](access(`parts`, "1")), "value"))
|
||||
> print text=[name](access([2](access(`parts`, "2")), "name"))
|
||||
> print text=[filename](access([2](access(`parts`, "2")), "filename"))
|
||||
> print text=[content_type](access([2](access(`parts`, "2")), "content_type"))
|
||||
> print text=[value](access([2](access(`parts`, "2")), "value"))
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: openai SSE parse offline
|
||||
import net:lib/net.mq.md
|
||||
import json:lib/json.mq.md
|
||||
@@ -10,7 +11,7 @@ import json:lib/json.mq.md
|
||||
|
||||
**events = > net.openai_sse_parse text=`fixture`**
|
||||
|
||||
- [`ev`](`events`)
|
||||
- [ev](遍历 `events` 为 `ev`)
|
||||
**t = > json.get value=`ev` key="type"**
|
||||
1. `t` == "delta"
|
||||
**chunk = > json.get value=`ev` key="text"**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: sys.exec capture=True returns stdout map
|
||||
description: GAP-09 optional capture.
|
||||
import sys:lib/sys.mq.md
|
||||
@@ -15,8 +16,8 @@ import json:lib/json.mq.md
|
||||
|
||||
**args = > json.parse text=["-c","printf hi-capture"]**
|
||||
**out = > sys.exec cmd="sh" args=args capture=True**
|
||||
**c = [code](out)**
|
||||
**s = [stdout](out)**
|
||||
**c = [code](access(out, "code"))**
|
||||
**s = [stdout](access(out, "stdout"))**
|
||||
1. `c` == 0
|
||||
> print text=capture-code-ok
|
||||
2. *
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: table collections
|
||||
description: put + list/map helpers
|
||||
import table:lib/table.mq.md
|
||||
@@ -7,7 +8,7 @@ import table:lib/table.mq.md
|
||||
# main
|
||||
|
||||
**h = > table.put in=None at="Authorization" value="Bearer-x"**
|
||||
> print text=[Authorization](`h`)
|
||||
> print text=[Authorization](access(`h`, "Authorization"))
|
||||
|
||||
`xs` =
|
||||
|
||||
@@ -17,8 +18,8 @@ import table:lib/table.mq.md
|
||||
| b |
|
||||
|
||||
**xs = > table.put in=`xs` at=1 value="A"**
|
||||
> print text=[1](`xs`)
|
||||
> print text=[2](`xs`)
|
||||
> print text=[1](access(`xs`, "1"))
|
||||
> print text=[2](access(`xs`, "2"))
|
||||
|
||||
`req` =
|
||||
|
||||
@@ -31,8 +32,8 @@ import table:lib/table.mq.md
|
||||
**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=[content]([1]([messages](`req`)))
|
||||
> print text=[stream](`req`)
|
||||
> print text=[content](access([1](access([messages](access(`req`, "messages")), "1")), "content"))
|
||||
> print text=[stream](access(`req`, "stream"))
|
||||
|
||||
**xs = > table.append list=`xs` item="c"**
|
||||
**n = > table.len xs=`xs`**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: lib/toml html encoding M8 smoke
|
||||
import toml:lib/toml.mq.md
|
||||
import html:lib/html.mq.md
|
||||
@@ -8,10 +9,10 @@ import enc:lib/encoding.mq.md
|
||||
# main
|
||||
|
||||
**cfg = > toml.parse text="name = \"marqdo\"\ncount = 2\n[pkg]\nver = \"1\"\n"**
|
||||
> print text=[name](`cfg`)
|
||||
> print text=[count](`cfg`)
|
||||
**pkg = [pkg](`cfg`)**
|
||||
> print text=[ver](`pkg`)
|
||||
> print text=[name](access(`cfg`, "name"))
|
||||
> print text=[count](access(`cfg`, "count"))
|
||||
**pkg = [pkg](access(`cfg`, "pkg"))**
|
||||
> print text=[ver](access(`pkg`, "ver"))
|
||||
|
||||
**e = > html.escape text="a<b>&\"c'"**
|
||||
> print text=`e`
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: lib/url smoke
|
||||
import url:lib/url.mq.md
|
||||
---
|
||||
@@ -6,16 +7,16 @@ import url:lib/url.mq.md
|
||||
# main
|
||||
|
||||
**u = > url.parse text="https://example.com:8443/a/b?x=1&y=2#frag"**
|
||||
> print text=[scheme](`u`)
|
||||
> print text=[host](`u`)
|
||||
> print text=[port](`u`)
|
||||
> print text=[path](`u`)
|
||||
> print text=[query](`u`)
|
||||
> print text=[fragment](`u`)
|
||||
> print text=[scheme](access(`u`, "scheme"))
|
||||
> print text=[host](access(`u`, "host"))
|
||||
> print text=[port](access(`u`, "port"))
|
||||
> print text=[path](access(`u`, "path"))
|
||||
> print text=[query](access(`u`, "query"))
|
||||
> print text=[fragment](access(`u`, "fragment"))
|
||||
|
||||
**q = > url.query_parse text="a=1&b=hi%20x&a=2"**
|
||||
> print text=[b](`q`)
|
||||
**as = [a](`q`)**
|
||||
> print text=[b](access(`q`, "b"))
|
||||
**as = [a](access(`q`, "a"))**
|
||||
**a0 = > at value=`as` index=0**
|
||||
**a1 = > at value=`as` index=1**
|
||||
> print text=`a0`
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: lib/地址 烟测
|
||||
导入 址:lib/地址.mq.md
|
||||
---
|
||||
@@ -6,7 +7,7 @@ title: lib/地址 烟测
|
||||
# main
|
||||
|
||||
**u = > 址.解析 内容="https://example.com/a?x=1"**
|
||||
> print text=[scheme](`u`)
|
||||
> print text=[host](`u`)
|
||||
> print text=[path](`u`)
|
||||
> print text=[query](`u`)
|
||||
> print text=[scheme](access(`u`, "scheme"))
|
||||
> print text=[host](access(`u`, "host"))
|
||||
> print text=[path](access(`u`, "path"))
|
||||
> print text=[query](access(`u`, "query"))
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 文件 Mid2 M9 烟测
|
||||
导入 文件:lib/文件.mq.md
|
||||
---
|
||||
@@ -10,7 +11,7 @@ title: 文件 Mid2 M9 烟测
|
||||
> 文件.写文本 路径="m9-zh/a.txt" 内容="A"
|
||||
|
||||
**st = > 文件.状态 路径="m9-zh/a.txt"**
|
||||
> print text=[is_file](`st`)
|
||||
> print text=[is_file](access(`st`, "is_file"))
|
||||
|
||||
**w = > 文件.遍历 路径="m9-zh"**
|
||||
**n = > 长度 `w`**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: lib/日期时间 烟测
|
||||
导入 日时:lib/日期时间.mq.md
|
||||
---
|
||||
@@ -6,10 +7,10 @@ title: lib/日期时间 烟测
|
||||
# main
|
||||
|
||||
**m = > 日时.自戳 秒=0**
|
||||
> print text=[iso](`m`)
|
||||
> print text=[iso](access(`m`, "iso"))
|
||||
|
||||
**sh = > 日时.时区 时刻=`m` 区="Asia/Shanghai"**
|
||||
> print text=[iso](`sh`)
|
||||
> print text=[iso](access(`sh`, "iso"))
|
||||
|
||||
**p = > 日时.解析 内容="2020-01-02T03:04:05+08:00"**
|
||||
**u = > 日时.成戳 时刻=`p`**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 表与命令行 烟测
|
||||
导入 表:lib/表.mq.md
|
||||
导入 命令行:lib/命令行.mq.md
|
||||
@@ -13,5 +14,5 @@ title: 表与命令行 烟测
|
||||
|
||||
**args = > split value="--x,1,--flag" sep=","**
|
||||
**flags = > 命令行.解析 参数=`args`**
|
||||
> 打印 内容=[x](`flags`)
|
||||
> 打印 内容=[flag](`flags`)
|
||||
> 打印 内容=[x](access(`flags`, "x"))
|
||||
> 打印 内容=[flag](access(`flags`, "flag"))
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 表集合
|
||||
description: 改 + 列表字典
|
||||
导入 表:lib/表.mq.md
|
||||
@@ -7,7 +8,7 @@ description: 改 + 列表字典
|
||||
# main
|
||||
|
||||
**h = > 表.改 入=None 于="Authorization" 值="Bearer-x"**
|
||||
> 打印 内容=[Authorization](`h`)
|
||||
> 打印 内容=[Authorization](access(`h`, "Authorization"))
|
||||
|
||||
`xs` =
|
||||
|
||||
@@ -17,7 +18,7 @@ description: 改 + 列表字典
|
||||
| b |
|
||||
|
||||
**xs = > 表.改 入=`xs` 于=1 值="A"**
|
||||
> 打印 内容=[1](`xs`)
|
||||
> 打印 内容=[1](access(`xs`, "1"))
|
||||
|
||||
**xs = > 表.追加 list=`xs` item="c"**
|
||||
**n = > 表.长度 xs=`xs`**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: lib/逗号表 烟测
|
||||
导入 逗号表:lib/逗号表.mq.md
|
||||
---
|
||||
@@ -12,4 +13,4 @@ title: lib/逗号表 烟测
|
||||
> 打印 内容=`n`
|
||||
|
||||
**r0 = > at value=`rows` index=0**
|
||||
> 打印 内容=[a](`r0`)
|
||||
> 打印 内容=[a](access(`r0`, "a"))
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: lib/配置表 超文本 编码 烟测
|
||||
导入 配置:lib/配置表.mq.md
|
||||
导入 超:lib/超文本.mq.md
|
||||
@@ -8,8 +9,8 @@ title: lib/配置表 超文本 编码 烟测
|
||||
# main
|
||||
|
||||
**cfg = > 配置.解析 内容="name = \"中文\"\nok = true\n"**
|
||||
> print text=[name](`cfg`)
|
||||
> print text=[ok](`cfg`)
|
||||
> print text=[name](access(`cfg`, "name"))
|
||||
> print text=[ok](access(`cfg`, "ok"))
|
||||
|
||||
**e = > 超.转义 内容="a<b>"**
|
||||
> print text=`e`
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: v0.3 推荐循环头嵌套
|
||||
description: `- [o](外层)` 内再 `- [i](内层)`
|
||||
---
|
||||
@@ -18,8 +19,8 @@ description: `- [o](外层)` 内再 `- [i](内层)`
|
||||
|---|
|
||||
| 1 |
|
||||
|
||||
- [o](外层)
|
||||
- [i](内层)
|
||||
- [o](遍历 外层 为 o)
|
||||
- [i](遍历 内层 为 i)
|
||||
**print text=`o`**
|
||||
|
||||
*None*
|
||||
@@ -0,0 +1,77 @@
|
||||
//! `<TAB>` M7: `marqdo migrate labels` — dry run, write, idempotence, runtime parity.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
fn run_in(dir: &std::path::Path, args: &[&str], markup: Option<&str>) -> (i32, String, String) {
|
||||
let mut cmd = Command::new(env!("CARGO_BIN_EXE_marqdo"));
|
||||
cmd.args(args);
|
||||
if let Some(m) = markup {
|
||||
cmd.env("MARQDO_MARKUP", m);
|
||||
}
|
||||
let out = cmd.output().expect("run marqdo");
|
||||
let _ = dir;
|
||||
(
|
||||
out.status.code().unwrap_or(1),
|
||||
String::from_utf8_lossy(&out.stdout).into_owned(),
|
||||
String::from_utf8_lossy(&out.stderr).into_owned(),
|
||||
)
|
||||
}
|
||||
|
||||
fn fixture() -> (std::path::PathBuf, String) {
|
||||
let dir = std::env::temp_dir().join(format!("marqdo-migrate-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("demo.mq.md");
|
||||
let src = "---\nimport json:lib/json.mq.md\n---\n\n# main\n\n`表` = > json.parse text={\"键\":\"值\"}\n**a = [键](`表`)**\n> print text=\"a=\" + `a`\n";
|
||||
std::fs::write(&path, src).unwrap();
|
||||
(path, src.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dry_run_does_not_write() {
|
||||
let (path, before) = fixture();
|
||||
let (code, stdout, _) = run_in(path.parent().unwrap(), &["migrate", "labels", path.to_str().unwrap()], None);
|
||||
assert_eq!(code, 0);
|
||||
assert!(stdout.contains("would change"), "{stdout}");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_migrates_and_keeps_runtime_behaviour() {
|
||||
let (path, _) = fixture();
|
||||
let parent = path.parent().unwrap().to_path_buf();
|
||||
// Baseline output (classic index).
|
||||
let (c0, out0, e0) = run_in(&parent, &["run", path.to_str().unwrap()], None);
|
||||
assert_eq!(c0, 0, "stderr={e0}");
|
||||
|
||||
let (code, _, err) = run_in(&parent, &["migrate", "labels", path.to_str().unwrap(), "--write"], None);
|
||||
assert_eq!(code, 0, "stderr={err}");
|
||||
|
||||
let migrated = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(migrated.contains("markup: occlusion"), "{migrated}");
|
||||
assert!(migrated.contains("access("), "{migrated}");
|
||||
|
||||
// Same output, now via the purity form.
|
||||
let (c1, out1, e1) = run_in(&parent, &["run", path.to_str().unwrap()], None);
|
||||
assert_eq!(c1, 0, "stderr={e1}");
|
||||
assert_eq!(out0, out1);
|
||||
|
||||
// Idempotent: a second pass finds nothing to do.
|
||||
let (_, again, _) = run_in(&parent, &["migrate", "labels", path.to_str().unwrap()], None);
|
||||
assert!(again.contains("0 index"), "{again}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equivalence_failure_leaves_file_untouched() {
|
||||
// A hand-written occlusion has no `(access(…))` payload, so rewriting the
|
||||
// shape again would change the AST — the tool must refuse.
|
||||
let dir = std::env::temp_dir().join(format!("marqdo-migrate-bad-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("bad.mq.md");
|
||||
let src = "---\nmarkup: occlusion\n---\n\n# main\n\n**a = [一加一](1 + 1)**\n> print text=`a`\n";
|
||||
std::fs::write(&path, src).unwrap();
|
||||
let (code, stdout, _) = run_in(&dir, &["migrate", "labels", path.to_str().unwrap()], None);
|
||||
assert_eq!(code, 0);
|
||||
// Already marked → reported as such, never rewritten.
|
||||
assert!(stdout.contains("already marked") || stdout.contains("0 index"), "{stdout}");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), src);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: access + occlusion loop
|
||||
import json:lib/json.mq.md
|
||||
---
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: clean occlusion
|
||||
---
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: empty label
|
||||
---
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: empty payload
|
||||
---
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: implicit occlusion consistent
|
||||
---
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: implicit occlusion stale
|
||||
---
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: label search fixture
|
||||
---
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: dangling label ref
|
||||
---
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: resolvable label refs
|
||||
---
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: occlusion value passthrough
|
||||
---
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 方括号标记调用与前置修饰语
|
||||
description: 礼貌 [问候] …;嵌套 ([…]);与 [键](集合) 取元消歧
|
||||
---
|
||||
@@ -15,7 +16,7 @@ description: 礼貌 [问候] …;嵌套 ([…]);与 [键](集合) 取元消
|
||||
|------|------|
|
||||
| 18 | 28 |
|
||||
|
||||
**价 = [拿铁](菜单)**
|
||||
**价 = [拿铁](access(菜单, "拿铁"))**
|
||||
**打印 内容=`价`**
|
||||
|
||||
## 问候
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: table cell expressions
|
||||
description: Data cells evaluate like call-arg values (`var`, paths, hyphen prose).
|
||||
---
|
||||
@@ -14,9 +15,9 @@ description: Data cells evaluate like call-arg values (`var`, paths, hyphen pros
|
||||
|---------|-------|------|
|
||||
| `secret` | `name` | https://api.openai.com/v1 |
|
||||
|
||||
> print text=[api_key](`cfg`)
|
||||
> print text=[model](`cfg`)
|
||||
> print text=[base](`cfg`)
|
||||
> print text=[api_key](access(`cfg`, "api_key"))
|
||||
> print text=[model](access(`cfg`, "model"))
|
||||
> print text=[base](access(`cfg`, "base"))
|
||||
|
||||
`paths` =
|
||||
|
||||
@@ -24,7 +25,7 @@ description: Data cells evaluate like call-arg values (`var`, paths, hyphen pros
|
||||
|---|
|
||||
| /chat/completions |
|
||||
|
||||
> print text=[1](`paths`)
|
||||
> print text=[1](access(`paths`, "1"))
|
||||
|
||||
`rec` =
|
||||
|
||||
@@ -32,7 +33,7 @@ description: Data cells evaluate like call-arg values (`var`, paths, hyphen pros
|
||||
|---|------|---------|
|
||||
| 1 | user | `secret` |
|
||||
|
||||
> print text=[content]([1](`rec`))
|
||||
> print text=[content](access([1](access(`rec`, "1")), "content"))
|
||||
|
||||
`ratios` =
|
||||
|
||||
@@ -41,5 +42,5 @@ description: Data cells evaluate like call-arg values (`var`, paths, hyphen pros
|
||||
| "1/5" |
|
||||
| "16/9" |
|
||||
|
||||
> print text=[1](`ratios`)
|
||||
> print text=[2](`ratios`)
|
||||
> print text=[1](access(`ratios`, "1"))
|
||||
> print text=[2](access(`ratios`, "2"))
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 横表多行 → 字典套列表
|
||||
---
|
||||
|
||||
@@ -11,14 +12,14 @@ title: 横表多行 → 字典套列表
|
||||
| 红富士 | 青瓜 |
|
||||
| 嘎啦 | 黄瓜条 |
|
||||
|
||||
**第一种苹果 = [1]([苹果](货架))**
|
||||
**第一种苹果 = [1](access([苹果](access(货架, "苹果")), "1"))**
|
||||
|
||||
> print text=`第一种苹果`
|
||||
|
||||
**列 = [苹果](货架)**
|
||||
**列 = [苹果](access(货架, "苹果"))**
|
||||
|
||||
> print text=`列`
|
||||
|
||||
**第二种黄瓜 = [2]([黄瓜](货架))**
|
||||
**第二种黄瓜 = [2](access([黄瓜](access(货架, "黄瓜")), "2"))**
|
||||
|
||||
> print text=`第二种黄瓜`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 横表单行 → 字典
|
||||
---
|
||||
|
||||
@@ -10,17 +11,17 @@ title: 横表单行 → 字典
|
||||
|------|------|------|
|
||||
| 水果 | 蔬菜 | 数码用品 |
|
||||
|
||||
**种 = [苹果](分类)**
|
||||
**种 = [苹果](access(分类, "苹果"))**
|
||||
|
||||
> print text=`种`
|
||||
|
||||
**种 = [黄瓜](分类)**
|
||||
**种 = [黄瓜](access(分类, "黄瓜"))**
|
||||
|
||||
> print text=`种`
|
||||
|
||||
**种 = [鼠标](分类)**
|
||||
**种 = [鼠标](access(分类, "鼠标"))**
|
||||
|
||||
> print text=`种`
|
||||
|
||||
- [键](分类)
|
||||
- [键](遍历 分类 为 键)
|
||||
> print text=`键`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: row records with @ marker
|
||||
---
|
||||
|
||||
@@ -11,10 +12,10 @@ title: row records with @ marker
|
||||
| 1 | apple | 2 |
|
||||
| 2 | pear | 3 |
|
||||
|
||||
**n = [name]([1](orders))**
|
||||
**n = [name](access([1](access(orders, "1")), "name"))**
|
||||
|
||||
> print text=`n`
|
||||
|
||||
**q = [qty]([2](orders))**
|
||||
**q = [qty](access([2](access(orders, "2")), "qty"))**
|
||||
|
||||
> print text=`q`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 行向记录表(首列 行 / @)
|
||||
---
|
||||
|
||||
@@ -11,17 +12,17 @@ title: 行向记录表(首列 行 / @)
|
||||
| 1 | 苹果 | 2 |
|
||||
| 2 | 梨 | 3 |
|
||||
|
||||
**第一 = [1](订单)**
|
||||
**第一 = [1](access(订单, "1"))**
|
||||
|
||||
> print text=`第一`
|
||||
|
||||
**名 = [品名]([1](订单))**
|
||||
**名 = [品名](access([1](access(订单, "1")), "品名"))**
|
||||
|
||||
> print text=`名`
|
||||
|
||||
**量 = [数量]([2](订单))**
|
||||
**量 = [数量](access([2](access(订单, "2")), "数量"))**
|
||||
|
||||
> print text=`量`
|
||||
|
||||
- [记录](订单)
|
||||
- [记录](遍历 订单 为 记录)
|
||||
> print text=`记录`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 集合(表格)示例
|
||||
---
|
||||
|
||||
@@ -12,5 +13,5 @@ title: 集合(表格)示例
|
||||
| 梨 |
|
||||
| 桃 |
|
||||
|
||||
- [果](篮子)
|
||||
- [果](遍历 篮子 为 果)
|
||||
> print text=`果`
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 链接形取元
|
||||
description: [键](集合) 为主语法;脚注取元仍兼容
|
||||
---
|
||||
@@ -19,9 +20,9 @@ description: [键](集合) 为主语法;脚注取元仍兼容
|
||||
| 杏 |
|
||||
|
||||
**名 = "拿铁"**
|
||||
**价 = [`名`](菜单)**
|
||||
**价 = [名](access(菜单, `名`))**
|
||||
**打印 内容=`价`**
|
||||
**静 = [美式](菜单)**
|
||||
**静 = [美式](access(菜单, "美式"))**
|
||||
**打印 内容=`静`**
|
||||
**第一 = [1](篮子)**
|
||||
**第一 = [1](access(篮子, "1"))**
|
||||
**打印 内容=`第一`**
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 循环示例
|
||||
---
|
||||
|
||||
@@ -21,5 +22,5 @@ title: 循环示例
|
||||
| 苹果 |
|
||||
| 梨 |
|
||||
|
||||
- [果](篮子)
|
||||
- [果](遍历 篮子 为 果)
|
||||
> print text=今天吃`果`
|
||||
Reference in new issue
Block a user