diff --git a/doc/design/change-m7-migration.md b/doc/design/change-m7-migration.md
new file mode 100644
index 0000000..61c37c1
--- /dev/null
+++ b/doc/design/change-m7-migration.md
@@ -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` | 本文件 |
diff --git a/examples/anlian-mq/components/feed.mq.md b/examples/anlian-mq/components/feed.mq.md
index b235928..ef67be0 100644
--- a/examples/anlian-mq/components/feed.mq.md
+++ b/examples/anlian-mq/components/feed.mq.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"**
**全项 = "" + 全标签 + ""**
**段 = > table.append list=段 item=全项**
-- [板](板块)
- **名 = [name](板)**
- **号 = [id](板)**
+- [板](遍历 板块 为 板)
+ **名 = [name](access(板, "name"))**
+ **号 = [id](access(板, "id"))**
**链 = 前缀 + "?" + 查询键 + "=" + 号**
**项 = "" + 名 + ""**
**段 = > table.append list=段 item=项**
diff --git a/examples/browser-app/app.mq.md b/examples/browser-app/app.mq.md
index b5bb108..ce7cd92 100644
--- a/examples/browser-app/app.mq.md
+++ b/examples/browser-app/app.mq.md
@@ -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 + "
" + item + " "**
**`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 + "" + item + " "**
**`ret` = > browser.set_html sel="#items" html=html**
diff --git a/examples/code-as-docs/index.mq.md b/examples/code-as-docs/index.mq.md
index 8acf980..816462d 100644
--- a/examples/code-as-docs/index.mq.md
+++ b/examples/code-as-docs/index.mq.md
@@ -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(行, "会员"))**
**打印 内容=`一行`**
打烊前给积分卡盖一个章:
diff --git a/examples/oa2026-showcase/foreign-node.mq.md b/examples/oa2026-showcase/foreign-node.mq.md
index 3c91d58..54b5765 100644
--- a/examples/oa2026-showcase/foreign-node.mq.md
+++ b/examples/oa2026-showcase/foreign-node.mq.md
@@ -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=`会话`**
diff --git a/examples/oa2026-showcase/invoice.mq.md b/examples/oa2026-showcase/invoice.mq.md
index 582d1dd..541d582 100644
--- a/examples/oa2026-showcase/invoice.mq.md
+++ b/examples/oa2026-showcase/invoice.mq.md
@@ -1,4 +1,5 @@
---
+markup: occlusion
title: 一张订单,一份可执行的业务说明
description: 叙述、数据、计算与断言共享同一个 .mq.md 源文件。
---
@@ -19,8 +20,8 @@ description: 叙述、数据、计算与断言共享同一个 .mq.md 源文件
逐行把「单价 × 数量」累加进`小计`。读者看到的是清单,机器执行的是同一张表。
**`小计` = 0**
-- [行](订单)
- **`小计` = `小计` + [单价](行) * [数量](行)**
+- [行](遍历 订单 为 行)
+ **`小计` = `小计` + [单价](access(行, "单价")) * [数量](access(行, "数量"))**
业务约定写在叙述里:提前不少于七天,整单按九五折;否则原价。
本单最早提前 14 天。
diff --git a/examples/web-spa-app/static/client.mq.md b/examples/web-spa-app/static/client.mq.md
index 4697f8f..9b82ccd 100644
--- a/examples/web-spa-app/static/client.mq.md
+++ b/examples/web-spa-app/static/client.mq.md
@@ -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 + "" + item + ""**
`persist` =
diff --git a/ext/ai/llm/openai.mq.md b/ext/ai/llm/openai.mq.md
index 8dad67c..2b9ca98 100644
--- a/ext/ai/llm/openai.mq.md
+++ b/ext/ai/llm/openai.mq.md
@@ -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*
diff --git a/ext/ai/sandbox.mq.md b/ext/ai/sandbox.mq.md
index 97727e0..310f9e8 100644
--- a/ext/ai/sandbox.mq.md
+++ b/ext/ai/sandbox.mq.md
@@ -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 + " | "**
diff --git a/ext/data/cache.mq.md b/ext/data/cache.mq.md
index 13bca6a..07418f0 100644
--- a/ext/data/cache.mq.md
+++ b/ext/data/cache.mq.md
@@ -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`*
diff --git a/ext/data/db.mq.md b/ext/data/db.mq.md
index f56ee01..5b31cb3 100644
--- a/ext/data/db.mq.md
+++ b/ext/data/db.mq.md
@@ -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`*
diff --git a/ext/data/form.mq.md b/ext/data/form.mq.md
index 7b49724..ade3f52 100644
--- a/ext/data/form.mq.md
+++ b/ext/data/form.mq.md
@@ -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`*
diff --git a/ext/data/storage.mq.md b/ext/data/storage.mq.md
index 02b9619..97bddc3 100644
--- a/ext/data/storage.mq.md
+++ b/ext/data/storage.mq.md
@@ -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`*
diff --git a/ext/net/websocket.mq.md b/ext/net/websocket.mq.md
index 4558fa1..cdd2d64 100644
--- a/ext/net/websocket.mq.md
+++ b/ext/net/websocket.mq.md
@@ -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`*
diff --git a/ext/security/auth.mq.md b/ext/security/auth.mq.md
index 7f2c14f..4bd2db4 100644
--- a/ext/security/auth.mq.md
+++ b/ext/security/auth.mq.md
@@ -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
diff --git a/man-test/index.mq.md b/man-test/index.mq.md
index be1bd54..0a42cdf 100644
--- a/man-test/index.mq.md
+++ b/man-test/index.mq.md
@@ -1,4 +1,5 @@
---
+markup: occlusion
title: 手工构造的测试样例
description: AI禁止更改
---
@@ -15,6 +16,6 @@ description: AI禁止更改
|lib|
-- [`测试文件夹`](`测试目录`)
+- [测试文件夹](遍历 `测试目录` 为 `测试文件夹`)
> 打印 `测试文件夹`
diff --git a/public/00-welcome.mq.md b/public/00-welcome.mq.md
index cda2179..10164d4 100644
--- a/public/00-welcome.mq.md
+++ b/public/00-welcome.mq.md
@@ -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. *
diff --git a/public/00-欢迎.mq.md b/public/00-欢迎.mq.md
index 762aac0..aaf3795 100644
--- a/public/00-欢迎.mq.md
+++ b/public/00-欢迎.mq.md
@@ -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. *
diff --git a/public/features/11-csv-text.mq.md b/public/features/11-csv-text.mq.md
index c6145e7..b76a3b8 100644
--- a/public/features/11-csv-text.mq.md
+++ b/public/features/11-csv-text.mq.md
@@ -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
diff --git a/public/features/11-逗号表文本.mq.md b/public/features/11-逗号表文本.mq.md
index 790200f..c7b9e86 100644
--- a/public/features/11-逗号表文本.mq.md
+++ b/public/features/11-逗号表文本.mq.md
@@ -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
diff --git a/public/features/12-list-cli.mq.md b/public/features/12-list-cli.mq.md
index 738c128..9273199 100644
--- a/public/features/12-list-cli.mq.md
+++ b/public/features/12-list-cli.mq.md
@@ -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
diff --git a/public/features/12-列表命令行.mq.md b/public/features/12-列表命令行.mq.md
index 0a8475e..7793f5a 100644
--- a/public/features/12-列表命令行.mq.md
+++ b/public/features/12-列表命令行.mq.md
@@ -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
diff --git a/public/features/14-datetime-url.mq.md b/public/features/14-datetime-url.mq.md
index f127cab..3d9fee0 100644
--- a/public/features/14-datetime-url.mq.md
+++ b/public/features/14-datetime-url.mq.md
@@ -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"))
diff --git a/public/features/14-日期时间地址.mq.md b/public/features/14-日期时间地址.mq.md
index 957d736..3b221c1 100644
--- a/public/features/14-日期时间地址.mq.md
+++ b/public/features/14-日期时间地址.mq.md
@@ -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"))
diff --git a/public/features/15-toml-html-encoding.mq.md b/public/features/15-toml-html-encoding.mq.md
index b70c367..bbc331e 100644
--- a/public/features/15-toml-html-encoding.mq.md
+++ b/public/features/15-toml-html-encoding.mq.md
@@ -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=""**
> print text=`safe`
diff --git a/public/features/15-配置表超文本编码.mq.md b/public/features/15-配置表超文本编码.mq.md
index c4fad58..8460d37 100644
--- a/public/features/15-配置表超文本编码.mq.md
+++ b/public/features/15-配置表超文本编码.mq.md
@@ -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 = > 超.转义 内容=""**
> print text=`safe`
diff --git a/public/features/16-fs-mid2.mq.md b/public/features/16-fs-mid2.mq.md
index 94b1f72..01bec4f 100644
--- a/public/features/16-fs-mid2.mq.md
+++ b/public/features/16-fs-mid2.mq.md
@@ -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`**
diff --git a/public/features/16-文件mid2.mq.md b/public/features/16-文件mid2.mq.md
index ce44d5a..63f637e 100644
--- a/public/features/16-文件mid2.mq.md
+++ b/public/features/16-文件mid2.mq.md
@@ -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`**
diff --git a/public/features/19-foreign-view-cells.mq.md b/public/features/19-foreign-view-cells.mq.md
index 5fcbfa4..349a974 100644
--- a/public/features/19-foreign-view-cells.mq.md
+++ b/public/features/19-foreign-view-cells.mq.md
@@ -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=`内核会话`**
diff --git a/public/features/19-外联视图单元.mq.md b/public/features/19-外联视图单元.mq.md
index d526a8b..75dcdce 100644
--- a/public/features/19-外联视图单元.mq.md
+++ b/public/features/19-外联视图单元.mq.md
@@ -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"))
**> 外联.会话关闭 标识=`内核会话`**
diff --git a/public/stdlib/foreign.mq.md b/public/stdlib/foreign.mq.md
index d82aef5..45b20c4 100644
--- a/public/stdlib/foreign.mq.md
+++ b/public/stdlib/foreign.mq.md
@@ -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`.
diff --git a/public/stdlib/table.mq.md b/public/stdlib/table.mq.md
index 6c5d0cf..778a67b 100644
--- a/public/stdlib/table.mq.md
+++ b/public/stdlib/table.mq.md
@@ -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`**
diff --git a/public/stdlib/外联.mq.md b/public/stdlib/外联.mq.md
index e30d33b..77b41b9 100644
--- a/public/stdlib/外联.mq.md
+++ b/public/stdlib/外联.mq.md
@@ -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:用 `会话求值`、`会话取值`、`会话变量`,最后 `会话关闭`。
diff --git a/public/stdlib/表.mq.md b/public/stdlib/表.mq.md
index 8547f2b..d503ae1 100644
--- a/public/stdlib/表.mq.md
+++ b/public/stdlib/表.mq.md
@@ -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`**
diff --git a/public/structure/05-loop.mq.md b/public/structure/05-loop.mq.md
index 2d9ea6d..2b6798e 100644
--- a/public/structure/05-loop.mq.md
+++ b/public/structure/05-loop.mq.md
@@ -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`
diff --git a/public/structure/05-循环.mq.md b/public/structure/05-循环.mq.md
index 0840dbb..a137227 100644
--- a/public/structure/05-循环.mq.md
+++ b/public/structure/05-循环.mq.md
@@ -1,4 +1,5 @@
---
+markup: occlusion
title: 循环
description: 条件循环与表遍历
---
@@ -24,5 +25,5 @@ description: 条件循环与表遍历
| 苹果 |
| 梨 |
-- [水果](篮子)
+- [水果](遍历 篮子 为 水果)
> 打印 内容=今天 `水果`
diff --git a/public/structure/06-collection.mq.md b/public/structure/06-collection.mq.md
index 2386ecd..a7d7788 100644
--- a/public/structure/06-collection.mq.md
+++ b/public/structure/06-collection.mq.md
@@ -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`
diff --git a/public/structure/06-集合.mq.md b/public/structure/06-集合.mq.md
index 7b858b0..961bad6 100644
--- a/public/structure/06-集合.mq.md
+++ b/public/structure/06-集合.mq.md
@@ -1,4 +1,5 @@
---
+markup: occlusion
title: 集合(表)
description: 单列竖表即列表
---
@@ -15,5 +16,5 @@ description: 单列竖表即列表
| 梨 |
| 桃 |
-- [水果](篮子)
+- [水果](遍历 篮子 为 水果)
> 打印 内容=`水果`
diff --git a/public/structure/07-map.mq.md b/public/structure/07-map.mq.md
index 7afdcb6..380ad0a 100644
--- a/public/structure/07-map.mq.md
+++ b/public/structure/07-map.mq.md
@@ -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`
diff --git a/public/structure/07-字典.mq.md b/public/structure/07-字典.mq.md
index bab186f..6f28c98 100644
--- a/public/structure/07-字典.mq.md
+++ b/public/structure/07-字典.mq.md
@@ -1,4 +1,5 @@
---
+markup: occlusion
title: 字典(横表)
description: 多列表是字典;链接取元
---
@@ -13,10 +14,10 @@ description: 多列表是字典;链接取元
|------|------|
| 水果 | 蔬菜 |
-**`种` = [苹果](分类)**
+**`种` = [苹果](access(分类, "苹果"))**
> 打印 内容=`种`
-**`种` = [黄瓜](分类)**
+**`种` = [黄瓜](access(分类, "黄瓜"))**
> 打印 内容=`种`
diff --git a/public/structure/08-records.mq.md b/public/structure/08-records.mq.md
index b677295..b69c229 100644
--- a/public/structure/08-records.mq.md
+++ b/public/structure/08-records.mq.md
@@ -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`
diff --git a/public/structure/08-记录表.mq.md b/public/structure/08-记录表.mq.md
index 7bcd33e..7945d36 100644
--- a/public/structure/08-记录表.mq.md
+++ b/public/structure/08-记录表.mq.md
@@ -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")), "数量"))**
> 打印 内容=`量`
diff --git a/src/host/dispatch.rs b/src/host/dispatch.rs
index abf7388..3b9c4e8 100644
--- a/src/host/dispatch.rs
+++ b/src/host/dispatch.rs
@@ -218,6 +218,8 @@ pub enum HostFn {
ForeignSessionClose = 209,
ForeignSessionList = 210,
ForeignSessionInterrupt = 211,
+ /// `` 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,
) -> Result {
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")?)
diff --git a/src/interp.rs b/src/interp.rs
index 2612b07..234ff75 100644
--- a/src/interp.rs
+++ b/src/interp.rs
@@ -1185,28 +1185,6 @@ impl Interpreter {
}
match call.callee.as_str() {
- // `` 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))?;
diff --git a/src/lib.rs b/src/lib.rs
index 1ec82b6..7b3c1d5 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -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;
diff --git a/src/load.rs b/src/load.rs
index 9f393ef..dc31360 100644
--- a/src/load.rs
+++ b/src/load.rs
@@ -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. `` 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();
diff --git a/src/main.rs b/src/main.rs
index 72864f8..0109d9d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -41,6 +41,22 @@ impl From 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 (`` 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 {
}
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 = 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();
diff --git a/src/migrate.rs b/src/migrate.rs
new file mode 100644
index 0000000..519cd50
--- /dev/null
+++ b/src/migrate.rs
@@ -0,0 +1,621 @@
+//! `` 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,
+}
+
+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 {
+ let chars: Vec = 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 {
+ 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 {
+ 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: ` 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::>()
+ );
+ 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 {
+ 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 = 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> {
+ 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 {
+ fn walk(dir: &Path, out: &mut Vec) {
+ 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());
+ }
+}
diff --git a/src/parse/expr.rs b/src/parse/expr.rs
index 2e998c5..c5ef1d1 100644
--- a/src/parse/expr.rs
+++ b/src/parse/expr.rs
@@ -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