From 4a1c9c48a2edc378ff07b11dad7c42aecd05d342 Mon Sep 17 00:00:00 2001 From: cflmy Date: Mon, 14 Sep 2026 10:44:18 +0800 Subject: [PATCH] feat(markup): prefer [key](collection) for map and list access Add GFM link-shaped index as the primary get surface, keep footnote index as transitional compatibility, and align the coffee example. Co-authored-by: Cursor --- .cursor/skills/marqdo/SKILL.md | 3 +- doc/design/collection-access-link.md | 58 ++++++++++++++ doc/design/markdown-mapping-v0.3.md | 3 + doc/roadmap/tables-maps-footnotes.md | 7 +- examples/code-as-docs/README.md | 11 +-- examples/code-as-docs/index.mq.md | 17 +++-- skills/marqdo/SKILL.md | 3 +- src/ast.rs | 11 +-- src/parse/expr.rs | 110 +++++++++++++++++++++++++++ src/view/render.rs | 3 +- tests/gold.rs | 5 ++ tests/structure/link-index.mq.md | 27 +++++++ 12 files changed, 235 insertions(+), 23 deletions(-) create mode 100644 doc/design/collection-access-link.md create mode 100644 tests/structure/link-index.mq.md diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index 0da9c13..8f822fd 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -54,7 +54,8 @@ Canonical design (repo): [`markdown-mapping-v0.3.md`](../../doc/design/markdown- | `*…*` | **Return value** — closing `*` touches last token; bare ids are variables | | `****` / whole-line `**` / `*None*` | Return `None` and end function body | | Lone `---` / `***` | Markdown thematic break (skip; not function end) | -| GFM table after empty RHS bind | Collection (1-col list / ≥2-col map / `@`·`行`·`row` → list of maps); `` `x`[^1] `` / `` `m`[^key] `` | +| GFM table after empty RHS bind | Collection; get with `[key](coll)` (preferred) or legacy `` `m`[^key] `` | +| `- [item](coll)` | Foreach (unchanged) | | `` ```lang `` | Foreign code block (via `lib/foreign`) | | `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped | | Unmarked prose | Comment | diff --git a/doc/design/collection-access-link.md b/doc/design/collection-access-link.md new file mode 100644 index 0000000..657455b --- /dev/null +++ b/doc/design/collection-access-link.md @@ -0,0 +1,58 @@ +# 集合取元:GFM 链接形 + +| | | +|---|---| +| 状态 | **Active(运行时)** | +| 日期 | 2026-09-14 | +| 相关 | [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md) · [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) | + +--- + +## 1. 决议 + +表达式取元的**主语法**为 Markdown 链接外形,与 foreach 同构: + +| 角色 | 写法 | +|------|------| +| **取元(表达式)** | `[键](集合)` | +| **遍历(语句)** | `- [项](集合)`(不变) | +| **脚注取元(过渡)** | `` 集合[^键] `` 仍解析,新代码勿写 | + +心智:**方括号 = 取出的名字,圆括号 = 从哪取。** + +```markdown +**价 = [拿铁](菜单)** +**价 = [`名`](菜单)** +**第一 = [1](篮子)** + +- [行](今日订单) + **名 = [品名](行)** +``` + +## 2. 细则 + +| 写法 | 语义 | +|------|------| +| `[拿铁](菜单)` | 静态键;`菜单` 为变量(粗体/斜体内) | +| `` [`名`](菜单) `` | 动态键(求值 `名` 再作键) | +| `[1](篮子)` | List **1-based** 下标(同脚注约定) | +| `[1]([苹果](货架))` | 嵌套链式 | + +与 `- [项](集合)` 消歧:仅 **表达式位置** 的 `[…](…)` 为取元;`-` 行头仍为 foreach。 + +## 3. 迁移 + +`` `菜单`[^拿铁] `` / `菜单[^拿铁]` → `[拿铁](菜单)`(**基与键左右对调**)。 + +脚注路径保留至另行决定移除之日;Skill / 教程 / 新示例只用链接形。 + +## 4. 非目标 + +- 点号 map 访问、`在`、箭头取元、`(键)[集合]` +- 循环语法糖(`←` / `in` / 自然语言) + +## 5. 修订历史 + +| 日期 | 说明 | +|------|------| +| 2026-09-14 | 初稿并落地主语法 | diff --git a/doc/design/markdown-mapping-v0.3.md b/doc/design/markdown-mapping-v0.3.md index 8629f9f..dd20c57 100644 --- a/doc/design/markdown-mapping-v0.3.md +++ b/doc/design/markdown-mapping-v0.3.md @@ -211,6 +211,8 @@ v0.3: | 体内 `-` | 循环 | | `N. *` | else 臂(此处 `*` 仍是「空条件」标记,**不是**返回值;见 §7.3) | | GFM 表格 | 集合(不变) | +| 表达式 `[键](集合)` | **取元**(与 foreach 同形;见 [collection-access-link.md](collection-access-link.md)) | +| `` 集合[^键] `` | **过渡**:旧脚注取元(仍可用) | | ` ```lang ` | 外联(不变) | | 单独一行 `---` / `***` | **叙述分隔**(跳过;模块顶与函数体内相同) | | 整行恰 `**` 或 `****` / `*None*` / `*无*` | **空返回**并结束本函数体(见 §7.2) | @@ -608,3 +610,4 @@ FnDef.params: | 2026-09-13 | 初稿:叙述统一、粗体代码、斜体返回、形参体推断;Proposed | | 2026-09-13 | 决议空返回(§7.2)与提及性反引号(§4.4);形参改为「升参」与绑定图分离(§8.2) | | 2026-09-14 | §7.2:`---` 不再收束;返回语句结束函数体解析;空返回首选 `*None*` | +| 2026-09-14 | 取元主语法改为 `[键](集合)`;脚注取元过渡保留 | diff --git a/doc/roadmap/tables-maps-footnotes.md b/doc/roadmap/tables-maps-footnotes.md index fe9170c..c779763 100644 --- a/doc/roadmap/tables-maps-footnotes.md +++ b/doc/roadmap/tables-maps-footnotes.md @@ -167,9 +167,12 @@ --- -## 4. 脚注取元(提案) +## 4. 脚注取元(历史 · 过渡保留) -### 4.1 为何用脚注外形 +> **主语法已切换为链接形** `[键](集合)`,见 [collection-access-link.md](../design/collection-access-link.md)。 +> 本节 `` 集合[^键] `` 仍由运行时接受;**新代码请写链接形**。 + +### 4.1 为何曾用脚注外形 - Markdown 已有 `[^…]` 引用形态,读者不陌生。 - 避免 `篮子[0]` 与链接 / 图片语法纠缠。 diff --git a/examples/code-as-docs/README.md b/examples/code-as-docs/README.md index 5ebe3cc..150a640 100644 --- a/examples/code-as-docs/README.md +++ b/examples/code-as-docs/README.md @@ -12,10 +12,11 @@ marqdo run examples/code-as-docs/index.mq.md |------|------| | 数据给人读 | GFM 表当菜单 / 订单 | | 步骤嵌在句子里 | `**总额 = 价 * 杯数**`、返回 `*总额*` | -| 装饰性强调 | `**说明**` 不执行(见设计 G2) | -| 段落分隔 | 顶层或体内的 `---` 只是分割线 | +| 装饰性强调 | `**说明**` 不执行 | +| 段落分隔 | `---` 只是分割线 | | 浮点 | `折扣`=0.85 | -| 动态键 | `` 菜单[^`名`] `` | -| 调用 | 粗体赋值右侧 **可省略 `>`**:`**摘要 = 结账摘要 …**`;输出可用 `**打印 内容=…**` | +| 取元 | `[拿铁](菜单)` / `` [`名`](菜单) ``(与循环同形;脚注 `[^…]` 仅过渡) | +| 循环 | `- [行](今日订单)` | +| 调用 | `**摘要 = 结账摘要 …**`(粗体 RHS 可省略 `>`) | -相关设计:[code-as-docs-gaps.md](../../doc/design/code-as-docs-gaps.md)、[markdown-mapping-v0.3.md](../../doc/design/markdown-mapping-v0.3.md) §6。 +设计:[collection-access-link.md](../../doc/design/collection-access-link.md)、[code-as-docs-gaps.md](../../doc/design/code-as-docs-gaps.md)。 diff --git a/examples/code-as-docs/index.mq.md b/examples/code-as-docs/index.mq.md index 39ae8a3..479c808 100644 --- a/examples/code-as-docs/index.mq.md +++ b/examples/code-as-docs/index.mq.md @@ -2,7 +2,7 @@ title: 代码即文档 · 周末咖啡手账 description: >- 一份可读可跑的周末手账:菜单是表,计价写在段落里,主流程像日记。 - 展示叙述统一写法、装饰性强调、分隔线、浮点折扣、动态脚注键,以及粗体内免 `>` 的调用。 + 展示叙述统一写法、链接形取元 [键](集合)、浮点折扣,以及粗体内免 `>` 的调用。 --- 本文件既是**说明**也是**程序**。人读得到段落与表格;机器执行嵌在叙述里的粗体步骤,并把斜体当作返回值。 @@ -53,20 +53,21 @@ description: >- --- -第一单:会员双杯拿铁。品名先记在变量里,再用动态键取价;粗体赋值右侧是调用时不必再写 `>`: +第一单:会员双杯拿铁。品名记在变量里,用链接形取元 `` [`名`](菜单) ``(与循环 `[项](集合)` 同形): **名 = "拿铁"** -**摘要 = 结账摘要 品名=`名` 价=菜单[^`名`] 杯数=2 会员=True** +**价 = [`名`](菜单)** +**摘要 = 结账摘要 品名=`名` 价=`价` 杯数=2 会员=True** **打印 内容=`摘要`** -对照一单非会员美式——品名已知,静态键即可: +对照一单非会员美式——静态键: -**对照 = 结账摘要 品名="美式" 价=菜单[^美式]** +**对照 = 结账摘要 品名="美式" 价=[美式](菜单)** **打印 内容=`对照`** --- -也可以把今日订单写成行表。循环里把行字段直接传给结账,少一层临时变量: +也可以把今日订单写成行表;循环头与取元同一套链接外形: `今日订单` = @@ -75,8 +76,8 @@ description: >- | 1 | 燕麦拿铁 | 32 | 1 | True | | 2 | 美式 | 18 | 2 | False | -- [`行`](`今日订单`) - **一行 = 结账摘要 品名=行[^品名] 价=行[^单价] 杯数=行[^杯数] 会员=行[^会员]** +- [行](今日订单) + **一行 = 结账摘要 品名=[品名](行) 价=[单价](行) 杯数=[杯数](行) 会员=[会员](行)** **打印 内容=`一行`** 最后用加一收个尾,确认叙述里的位置调用也通: diff --git a/skills/marqdo/SKILL.md b/skills/marqdo/SKILL.md index 1c44550..3214a63 100644 --- a/skills/marqdo/SKILL.md +++ b/skills/marqdo/SKILL.md @@ -54,7 +54,8 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. | `**…**` | Return value — closing `**` touches last token, **no trailing space**; bare ids are variables | | `****` or `**` + spaces + `**` | Return `None` and end function body | | Lone `---` / `***` | Markdown thematic break (skip; not function end) | -| GFM table after empty RHS bind | Collection (1-col list / ≥2-col map / `@`·`行`·`row` → list of maps); `` `x`[^1] `` / `` `m`[^key] `` | +| GFM table after empty RHS bind | Collection; get with `[key](coll)` (preferred) or legacy `` `m`[^key] `` | +| `- [item](coll)` | Foreach (unchanged) | | `` ```lang `` | Foreign code block (via `lib/foreign`) | | `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped | | Unmarked prose | Comment | diff --git a/src/ast.rs b/src/ast.rs index 5764dc7..c49875b 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -145,10 +145,11 @@ pub enum Expr { List(Vec), /// Object literal / horizontal table (`map` value). Map(Vec<(String, Expr)>), - /// Footnote index: `` `xs`[^1] `` / `` `m`[^key] `` / `` `m`[^`var`] `` (dynamic key). + /// Collection index: `` [拿铁](菜单) `` / `` [`名`](菜单) `` (preferred), or + /// legacy footnote `` `菜单`[^拿铁] `` / `` `菜单`[^`名`] ``. Index { base: Box, - /// Label inside `[^…]` (digits → 1-based list index, or map key; see [`IndexKey`]). + /// Key or 1-based list index; see [`IndexKey`]. label: IndexKey, }, /// Parsed `$$…$$` formula tree (from assignment RHS). @@ -166,12 +167,12 @@ pub enum InterpPart { Index { base: String, labels: Vec }, } -/// Footnote / map key after `[^…]`. +/// Map / list index key (`[key](coll)` or legacy `[^…]`). #[derive(Debug, Clone, PartialEq, Eq)] pub enum IndexKey { - /// Static text: `[^拿铁]` / `[^1]`. + /// Static text: `[拿铁](…)` / `[^拿铁]` / `[^1]`. Lit(String), - /// Dynamic: `` [^`品名`] `` — evaluate variable, then stringify as key. + /// Dynamic: `` [`品名`](…) `` / `` [^`品名`] `` — evaluate variable, then stringify as key. Var(String), } diff --git a/src/parse/expr.rs b/src/parse/expr.rs index 4e20449..9c0a50d 100644 --- a/src/parse/expr.rs +++ b/src/parse/expr.rs @@ -461,6 +461,11 @@ impl<'a> Parser<'a> { } return Ok(e); } + // Link-shaped index: `[key](collection)` / `` [`var`](collection) `` + // (same Markdown shape as foreach `- [item](coll)`; see collection-access-link.md). + if self.starts_with("[") && !self.starts_with("[^") { + return self.parse_link_index(); + } if self.eat("\"") { return self.parse_quoted_string('"'); } @@ -608,6 +613,69 @@ impl<'a> Parser<'a> { Ok(expr) } + /// `[key](collection)` — preferred collection get (GFM link shape). + fn parse_link_index(&mut self) -> Result { + if !self.eat("[") { + bail!("expected '[' for link index"); + } + self.skip_ws(); + let label = if self.eat("`") { + let start = self.i; + while let Some(c) = self.peek_char() { + if c == '`' { + break; + } + if c == '\n' || c == '\r' || c == ']' { + bail!("unterminated link-index var `[`…`](…)`"); + } + self.bump_char(); + } + let name = self.src[start..self.i].trim().to_string(); + if !self.eat("`") { + bail!("unterminated link-index var `[`…`](…)`"); + } + if name.is_empty() { + bail!("empty link-index var `[`](…)`"); + } + IndexKey::Var(name) + } else { + let start = self.i; + while let Some(c) = self.peek_char() { + if c == ']' { + break; + } + if c == '\n' || c == '\r' || c == '[' { + bail!("unterminated or nested link-index key `[…](…)`"); + } + self.bump_char(); + } + let key = self.src[start..self.i].trim().to_string(); + if key.is_empty() { + bail!("empty link-index key `[](…)`"); + } + IndexKey::Lit(key) + }; + self.skip_ws(); + if !self.eat("]") { + bail!("expected ']' after link-index key"); + } + self.skip_ws(); + if !self.eat("(") { + bail!("expected '(' collection after link-index `[key]`"); + } + let base = self.parse_or()?; + self.skip_ws(); + if !self.eat(")") { + bail!("expected ')' after link-index collection"); + } + let expr = Expr::Index { + base: Box::new(base), + label, + }; + // Legacy: allow trailing footnote chain on the result. + self.parse_index_chain(expr) + } + /// `"..."` or `'...'` with escapes and `` `var` `` interpolation. fn parse_quoted_string(&mut self, quote: char) -> Result { use crate::ast::InterpPart; @@ -1327,6 +1395,48 @@ mod tests { } if s == "拿铁" )); } + + #[test] + fn link_shaped_index() { + let e = parse_expr_prefer_var("[拿铁](菜单)").unwrap(); + match e { + Expr::Index { base, label } => { + assert!(matches!(base.as_ref(), Expr::Var(n) if n == "菜单")); + assert_eq!(label, IndexKey::Lit("拿铁".into())); + } + other => panic!("expected link Index, got {other:?}"), + } + let e = parse_expr_prefer_var("[`名`](菜单)").unwrap(); + match e { + Expr::Index { base, label } => { + assert!(matches!(base.as_ref(), Expr::Var(n) if n == "菜单")); + assert_eq!(label, IndexKey::Var("名".into())); + } + other => panic!("expected dynamic link Index, got {other:?}"), + } + let e = parse_expr_prefer_var("[1](篮子)").unwrap(); + assert!(matches!( + e, + Expr::Index { + label: IndexKey::Lit(ref s), + .. + } if s == "1" + )); + let e = parse_expr_prefer_var("[1]([苹果](货架))").unwrap(); + match e { + Expr::Index { base, label } => { + assert_eq!(label, IndexKey::Lit("1".into())); + assert!(matches!( + base.as_ref(), + Expr::Index { + label: IndexKey::Lit(ref k), + .. + } if k == "苹果" + )); + } + other => panic!("expected nested link Index, got {other:?}"), + } + } } diff --git a/src/view/render.rs b/src/view/render.rs index f7ab1d3..23c05eb 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -1345,7 +1345,8 @@ fn expr_prec(expr: &Expr, parent_prec: u8) -> String { crate::ast::IndexKey::Lit(s) => s.clone(), crate::ast::IndexKey::Var(n) => format!("`{n}`"), }; - format!("{}[^{}]", expr_prec(base, 8), key) + // Preferred surface: GFM link shape (legacy footnote still accepted by parser). + format!("[{}]({})", key, expr_prec(base, 0)) } Expr::Formula(e) => format!("$$ {} $$", e.as_display()), Expr::Code(c) => format!("```{} …```", c.lang), diff --git a/tests/gold.rs b/tests/gold.rs index 643148c..7b13231 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -279,6 +279,11 @@ fn structure_footnote_index() { ); } +#[test] +fn structure_link_index() { + assert_out("tests/structure/link-index.mq.md", "28\n18\n桃"); +} + #[test] fn structure_footnote_map_digits() { assert_out( diff --git a/tests/structure/link-index.mq.md b/tests/structure/link-index.mq.md new file mode 100644 index 0000000..6988c2e --- /dev/null +++ b/tests/structure/link-index.mq.md @@ -0,0 +1,27 @@ +--- +title: 链接形取元 +description: [键](集合) 为主语法;脚注取元仍兼容 +--- + +# main + +`菜单` = + +| 美式 | 拿铁 | +|------|------| +| 18 | 28 | + +`篮子` = + +| 果 | +|----| +| 桃 | +| 杏 | + +**名 = "拿铁"** +**价 = [`名`](菜单)** +**打印 内容=`价`** +**静 = [美式](菜单)** +**打印 内容=`静`** +**第一 = [1](篮子)** +**打印 内容=`第一`**