From a23fdedfa2fef10564df69526e068aebd700f237 Mon Sep 17 00:00:00 2001 From: cflmy Date: Mon, 10 Aug 2026 09:50:21 +0800 Subject: [PATCH] Implement table semantic T0-T4: map/records/footnote get MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 1-col table stays a List; >=2-col becomes a column-oriented Map (1 data row -> scalar values, >=2 -> Map of Lists). - First header @ / 行 / row opts into row-oriented List of Maps (marker column excluded); missing field cols is a diagnostic. - Footnote index: `xs`[^1] (1-based list), `m`[^key] (map key), chained. Errors for [^0], out-of-range, missing key, duplicate headers. - foreach walks list items or map keys; Map values now display as {k: v}. - Sync both tree and bytecode backends; new gold + error fixtures, docs (markdown-mapping, roadmap, skill, public), and public 07/08 pages. - Fix subtask-spawn fixture return value to child_ok (child-ok parses as subtraction). Co-authored-by: Cursor --- .cursor/skills/marqdo/SKILL.md | 2 +- .cursor/skills/marqdo/examples.md | 32 ++++ doc/README.md | 2 +- doc/design/markdown-mapping.md | 36 ++++- doc/roadmap/tables-maps-footnotes.md | 43 ++++-- lib/table.mq.md | 2 +- public/stdlib/table.mq.md | 2 +- public/structure/06-collection.mq.md | 4 +- public/structure/06-集合.mq.md | 4 +- public/structure/07-map.mq.md | 22 +++ public/structure/07-字典.mq.md | 22 +++ public/structure/08-records.mq.md | 23 +++ public/structure/08-记录表.mq.md | 23 +++ skills/marqdo/SKILL.md | 2 +- skills/marqdo/examples.md | 32 ++++ src/ast.rs | 8 +- src/builtin.rs | 54 +++++++ src/bytecode/compile.rs | 7 + src/bytecode/mod.rs | 4 + src/bytecode/vm.rs | 20 ++- src/interp.rs | 16 +- src/parse/expr.rs | 40 ++++- src/parse/mod.rs | 126 ++++++++++++--- src/value.rs | 12 +- src/view/render.rs | 4 + tests/errors/footnote-missing-key.mq.md | 15 ++ tests/errors/footnote-oob.mq.md | 15 ++ tests/errors/footnote-zero.mq.md | 15 ++ tests/errors/table-dup-header.mq.md | 13 ++ tests/errors/table-row-marker-only.mq.md | 13 ++ tests/gold.rs | 160 +++++++++++++++++++- tests/lib/subtask-spawn.mq.md | 2 +- tests/structure/collection-map-list.mq.md | 24 +++ tests/structure/collection-map.mq.md | 26 ++++ tests/structure/collection-records-at.mq.md | 20 +++ tests/structure/collection-records.mq.md | 27 ++++ tests/structure/footnote-index.mq.md | 25 +++ 37 files changed, 846 insertions(+), 51 deletions(-) create mode 100644 public/structure/07-map.mq.md create mode 100644 public/structure/07-字典.mq.md create mode 100644 public/structure/08-records.mq.md create mode 100644 public/structure/08-记录表.mq.md create mode 100644 tests/errors/footnote-missing-key.mq.md create mode 100644 tests/errors/footnote-oob.mq.md create mode 100644 tests/errors/footnote-zero.mq.md create mode 100644 tests/errors/table-dup-header.mq.md create mode 100644 tests/errors/table-row-marker-only.mq.md create mode 100644 tests/structure/collection-map-list.mq.md create mode 100644 tests/structure/collection-map.mq.md create mode 100644 tests/structure/collection-records-at.mq.md create mode 100644 tests/structure/collection-records.mq.md create mode 100644 tests/structure/footnote-index.mq.md diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index dbcc6f3..a1a6301 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -45,7 +45,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. | `**…**` | Return value | | `****` or `**` + spaces + `**` | Return `None` and end function body | | Lone `---` / `***` in function body | End function body (no value) | -| GFM table after empty RHS bind | Collection | +| GFM table after empty RHS bind | Collection (1-col list / ≥2-col map / `@`·`行`·`row` → list of maps); `` `x`[^1] `` / `` `m`[^key] `` | | `` ```lang `` | Foreign code block (via `lib/foreign`) | | `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped | | Unmarked prose | Comment | diff --git a/.cursor/skills/marqdo/examples.md b/.cursor/skills/marqdo/examples.md index 0db0205..d39f006 100644 --- a/.cursor/skills/marqdo/examples.md +++ b/.cursor/skills/marqdo/examples.md @@ -69,6 +69,7 @@ Greeting via a nested function: # main `篮子` = + | 果 | |----| | 苹果 | @@ -77,6 +78,37 @@ Greeting via a nested function: > print text=`果` ``` +## 6b. Map table + footnote get + +```markdown +# main + +`分类` = + +| 苹果 | 黄瓜 | +|------|------| +| 水果 | 蔬菜 | + +*`种` = `分类`[^苹果] * +> print text=`种` + +*`第一` = `篮子`[^1] * +``` + +One column → list; ≥2 columns + one data row → map; ≥2 columns + many rows → map of lists. Footnotes are 1-based on lists; map keys are header text. Foreach on a map walks **keys**. + +Row-oriented records (SQL-like): first header `@` / `行` / `row` → list of maps (marker column excluded): + +```markdown +`订单` = + +| 行 | 品名 | 数量 | +|----|------|------| +| 1 | 苹果 | 2 | + +*`名` = `订单`[^1][^品名] * +``` + ## 7. Import text stdlib ```markdown diff --git a/doc/README.md b/doc/README.md index 456767a..2dde29e 100644 --- a/doc/README.md +++ b/doc/README.md @@ -54,7 +54,7 @@ | [roadmap/okf-near-match.md](roadmap/okf-near-match.md) | **规划:OKF 相近任务命中**(精确 sig 之外的可选软复用) | | [roadmap/agent-streaming.md](roadmap/agent-streaming.md) | **规划:智能体 / LLM 流式输出**(事件模型 + step/plan 透传) | | [roadmap/object-inheritance.md](roadmap/object-inheritance.md) | **规划:对象继承**(`# 子类 = > 父类`) | -| [roadmap/tables-maps-footnotes.md](roadmap/tables-maps-footnotes.md) | **规划:表格语义**(竖表列表 / 横表字典 / 脚注取元) | +| [roadmap/tables-maps-footnotes.md](roadmap/tables-maps-footnotes.md) | **表格语义**(竖表 / 横表字典 / 脚注取元 / 行向记录;T0–T4 已落地) | | [roadmap/ext-web.md](roadmap/ext-web.md) | **规划:`ext/web` 动态网页**(env/DB init·迁移·样式脚手架·ABI) | | [roadmap/ext-quantum.md](roadmap/ext-quantum.md) | **规划:`ext/quantum` 量子模拟**(基础门·电路·ABI·`ext add`) | | [research/okf-and-marqdo.md](research/okf-and-marqdo.md) | OKF 调研 | diff --git a/doc/design/markdown-mapping.md b/doc/design/markdown-mapping.md index 584d3b8..1803c0b 100644 --- a/doc/design/markdown-mapping.md +++ b/doc/design/markdown-mapping.md @@ -242,9 +242,41 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 ## 9. 集合(表格) -同 v0。`` `篮子` = `` 后接 GFM 表;**当前落地:单列竖表 → 列表**。 +`` `名` = `` 后接 GFM 表;几何决定值类型(详见 [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md)): -横表字典、多行嵌套、脚注取元属未来规划,见 [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md)。 +| 形状 | 值 | +|------|-----| +| **1 列**(竖表) | `List`(表头 = foreach 元素名,不进入元素) | +| **≥2 列 + 1 行数据**(横表) | `Map`:键 = 表头,值 = 该列标量 | +| **≥2 列 + ≥2 行数据** | `Map`:键 = 表头,值 = 该列 `List`(列向) | +| **≥2 列 + 0 行数据** | `Map`:键存在,值为空列表 | +| **首列表头 `@` / `行` / `row`** | **行向** `List` of `Map`(标记列不进入字段;任意数据行数) | +| 重复表头 | 诊断错误 | + +行向示例: + +```markdown +`订单` = + +| 行 | 品名 | 数量 | +|----|------|------| +| 1 | 苹果 | 2 | +| 2 | 梨 | 3 | + +*`名` = `订单`[^1][^品名] * +``` + +**脚注取元**(表达式级,1-based 列表下标 / 字典键;可链式): + +```markdown +*`第一` = `篮子`[^1] * +*`种` = `分类`[^苹果] * +*`第一种苹果` = `货架`[^苹果][^1] * +``` + +- 文末 `[^1]: …` 定义块仍是注释,与取元无关。 +- `[^0]`、越界、缺键 → 报错。 +- foreach:`List` 遍历元素;`Map` 遍历**键**(值用脚注取)。 --- diff --git a/doc/roadmap/tables-maps-footnotes.md b/doc/roadmap/tables-maps-footnotes.md index 180660d..aa0f624 100644 --- a/doc/roadmap/tables-maps-footnotes.md +++ b/doc/roadmap/tables-maps-footnotes.md @@ -2,8 +2,8 @@ | | | |---|---| -| 状态 | **规划 / 未开工** | -| 日期 | 2026-08-09 | +| 状态 | **T0–T4 已落地** | +| 日期 | 2026-08-10 | | 相关 | [markdown-mapping.md](../design/markdown-mapping.md) §9 · [objects.md](../design/objects.md) · [stdlib.md](../design/stdlib.md)(`lib/table`) · [keywords.md](../design/keywords.md) | | 现状金样 | [tests/structure/collection.mq.md](../../tests/structure/collection.mq.md) | @@ -137,9 +137,33 @@ | ≥2 | ≥2 | `Map`(值均为 `List`) | | ≥2 | 0 | `Map`(键存在,值空列表或错误——开工时锁定为「空列表」) | -### 3.5 显式形态标记(可选,二期) +### 3.5 显式形态标记(行向记录)— **已落地** -若必须支持行向记录,可用表标题行或首列表头约定,例如首列表头为 `@` / `行` 时改行向——**仅当默认列向不够用再开**;v1 文档只教默认。 +首列表头为下列之一时,整表改为**行向**(不静默混用列向默认): + +| 标记 | 说明 | +|------|------| +| `@` | ASCII 短标记 | +| `行` | 中文 | +| `row` | 英文 | + +规则: + +1. 标记列**不进入**记录字段(数据格可写行号给人看)。 +2. 其余列 → 每行一个 `Map`;整体为 `List`。 +3. 须至少有一列字段(仅 `| 行 |` → 诊断)。 +4. 数据行数任意(含 0 → 空列表;1 行仍是 `List` of one `Map`,不是列向 `Map`)。 + +```markdown +`订单` = + +| 行 | 品名 | 数量 | +|----|------|------| +| 1 | 苹果 | 2 | +| 2 | 梨 | 3 | +``` + +→ `[{品名: 苹果, 数量: 2}, {品名: 梨, 数量: 3}]`。取元:`` `订单`[^1][^品名] ``。 --- @@ -228,11 +252,11 @@ ## 6. 推荐落地顺序 ```text -T0 横表单行 → Map;金样;竖表回归 -T1 横表多行 → Map of List(列向);嵌套金样 -T2 脚注取元:List [^n]、Map [^键]、链式 -T3 文档:markdown-mapping §9 重写;Skill / examples;table 库说明对齐 -T4 (可选)行向记录表显式标记 +T0 横表单行 → Map;金样;竖表回归 ✅ +T1 横表多行 → Map of List(列向);嵌套金样 ✅ +T2 脚注取元:List [^n]、Map [^键]、链式 ✅ +T3 文档:markdown-mapping §9;Skill / examples;table 库 ✅(本批) +T4 行向记录表:首列 `@` / `行` / `row` ✅ ``` 验收: @@ -251,6 +275,7 @@ T4 (可选)行向记录表显式标记 | 单列竖表 | 列表 | `` `a`[^1] `` | | 多列 + 一行 | 字典 | `` `m`[^键] `` | | 多列 + 多行 | 字典 → 列表 | `` `m`[^键][^1] `` | +| 首列 `@`/`行`/`row` | 记录列表 | `` `r`[^1][^字段] `` | 竖表表头是「元素名」;横表表头是「键名」——几何决定角色,减少「这张表到底是啥」的歧义。 diff --git a/lib/table.mq.md b/lib/table.mq.md index a24f3a0..05cca86 100644 --- a/lib/table.mq.md +++ b/lib/table.mq.md @@ -1,6 +1,6 @@ --- title: lib/table -description: English table helpers over len / at +description: English list helpers over len / at (prefer footnote index for one-shots) --- ## rows diff --git a/public/stdlib/table.mq.md b/public/stdlib/table.mq.md index 546c16e..7219064 100644 --- a/public/stdlib/table.mq.md +++ b/public/stdlib/table.mq.md @@ -6,7 +6,7 @@ description: Row count and index helpers # main -Import lib/table.mq.md. Functions: rows(xs), row_at(xs, i). Single-column Markdown tables are lists at runtime. +Import lib/table.mq.md. Functions: rows(xs), row_at(xs, i). Single-column tables are lists; multi-column tables are maps (see structure/07-map). Prefer `` `xs`[^1] `` for 1-based index; `row_at` stays 0-based. `xs` = diff --git a/public/structure/06-collection.mq.md b/public/structure/06-collection.mq.md index 39f32a0..be749b1 100644 --- a/public/structure/06-collection.mq.md +++ b/public/structure/06-collection.mq.md @@ -1,11 +1,11 @@ --- title: Collections (tables) -description: GFM tables are collections +description: One-column tables are lists --- # main -A Markdown table is a collection; loop to read each row. +A single-column Markdown table is a list; loop to read each item. Use `basket`[^1] for 1-based index. `basket` = diff --git a/public/structure/06-集合.mq.md b/public/structure/06-集合.mq.md index 07f9864..71c3aa6 100644 --- a/public/structure/06-集合.mq.md +++ b/public/structure/06-集合.mq.md @@ -1,11 +1,11 @@ --- title: 集合(表) -description: GFM 表格即集合 +description: 单列竖表即列表 --- # main -Markdown 表是集合;用循环读每一行。 +单列 Markdown 表是列表;用循环读每一项。按下标用 `` `篮子`[^1] ``(1-based)。 `篮子` = diff --git a/public/structure/07-map.mq.md b/public/structure/07-map.mq.md new file mode 100644 index 0000000..6fa4b61 --- /dev/null +++ b/public/structure/07-map.mq.md @@ -0,0 +1,22 @@ +--- +title: Maps (horizontal tables) +description: Multi-column tables are maps; footnote gets +--- + +# main + +A multi-column table with one data row is a map. Read values with footnote keys. + +`kinds` = + +| apple | cucumber | +|-------|----------| +| fruit | vegetable | + +*`k` = `kinds`[^apple] * + +> print text=`k` + +*`k` = `kinds`[^cucumber] * + +> print text=`k` diff --git a/public/structure/07-字典.mq.md b/public/structure/07-字典.mq.md new file mode 100644 index 0000000..ffc2a28 --- /dev/null +++ b/public/structure/07-字典.mq.md @@ -0,0 +1,22 @@ +--- +title: 字典(横表) +description: 多列表是字典;脚注按键取元 +--- + +# main + +多列且仅一行数据的表是字典。用脚注键取元。 + +`分类` = + +| 苹果 | 黄瓜 | +|------|------| +| 水果 | 蔬菜 | + +*`种` = `分类`[^苹果] * + +> 打印 内容=`种` + +*`种` = `分类`[^黄瓜] * + +> 打印 内容=`种` diff --git a/public/structure/08-records.mq.md b/public/structure/08-records.mq.md new file mode 100644 index 0000000..a2c76b7 --- /dev/null +++ b/public/structure/08-records.mq.md @@ -0,0 +1,23 @@ +--- +title: Row records +description: First header @ / row makes a list of maps +--- + +# main + +When the first header is `@` or `row`, each data row is a map (marker column is not a field). + +`orders` = + +| @ | name | qty | +|---|------|-----| +| 1 | apple | 2 | +| 2 | pear | 3 | + +*`n` = `orders`[^1][^name] * + +> print text=`n` + +*`q` = `orders`[^2][^qty] * + +> print text=`q` diff --git a/public/structure/08-记录表.mq.md b/public/structure/08-记录表.mq.md new file mode 100644 index 0000000..e0a53e4 --- /dev/null +++ b/public/structure/08-记录表.mq.md @@ -0,0 +1,23 @@ +--- +title: 行向记录表 +description: 首列表头「行」→ 每行一个字典 +--- + +# main + +首列表头为 `行`(或 `@` / `row`)时,每行数据是一个字典;标记列不进入字段。 + +`订单` = + +| 行 | 品名 | 数量 | +|----|------|------| +| 1 | 苹果 | 2 | +| 2 | 梨 | 3 | + +*`名` = `订单`[^1][^品名] * + +> 打印 内容=`名` + +*`量` = `订单`[^2][^数量] * + +> 打印 内容=`量` diff --git a/skills/marqdo/SKILL.md b/skills/marqdo/SKILL.md index e41b654..d3ca9d5 100644 --- a/skills/marqdo/SKILL.md +++ b/skills/marqdo/SKILL.md @@ -42,7 +42,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. | `**…**` | Return value | | `****` or `**` + spaces + `**` | Return `None` and end function body | | Lone `---` / `***` in function body | End function body (no value) | -| GFM table after empty RHS bind | Collection | +| GFM table after empty RHS bind | Collection (1-col list / ≥2-col map / `@`·`行`·`row` → list of maps); `` `x`[^1] `` / `` `m`[^key] `` | | `` ```lang `` | Foreign code block (via `lib/foreign`) | | `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped | | Unmarked prose | Comment | diff --git a/skills/marqdo/examples.md b/skills/marqdo/examples.md index 0db0205..d39f006 100644 --- a/skills/marqdo/examples.md +++ b/skills/marqdo/examples.md @@ -69,6 +69,7 @@ Greeting via a nested function: # main `篮子` = + | 果 | |----| | 苹果 | @@ -77,6 +78,37 @@ Greeting via a nested function: > print text=`果` ``` +## 6b. Map table + footnote get + +```markdown +# main + +`分类` = + +| 苹果 | 黄瓜 | +|------|------| +| 水果 | 蔬菜 | + +*`种` = `分类`[^苹果] * +> print text=`种` + +*`第一` = `篮子`[^1] * +``` + +One column → list; ≥2 columns + one data row → map; ≥2 columns + many rows → map of lists. Footnotes are 1-based on lists; map keys are header text. Foreach on a map walks **keys**. + +Row-oriented records (SQL-like): first header `@` / `行` / `row` → list of maps (marker column excluded): + +```markdown +`订单` = + +| 行 | 品名 | 数量 | +|----|------|------| +| 1 | 苹果 | 2 | + +*`名` = `订单`[^1][^品名] * +``` + ## 7. Import text stdlib ```markdown diff --git a/src/ast.rs b/src/ast.rs index be3d527..56433eb 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -139,8 +139,14 @@ pub enum Expr { }, Call(CallExpr), List(Vec), - /// Object literal / table row (`map` value). + /// Object literal / horizontal table (`map` value). Map(Vec<(String, Expr)>), + /// Footnote index: `` `xs`[^1] `` / `` `m`[^key] `` (see tables-maps-footnotes). + Index { + base: Box, + /// Label inside `[^…]` (digits → 1-based list index; else map key). + label: String, + }, /// Parsed `$$…$$` formula tree (from assignment RHS). Formula(FormulaExpr), /// Bound ```lang … ``` fence (`code` value). diff --git a/src/builtin.rs b/src/builtin.rs index 0ddf795..29a661d 100644 --- a/src/builtin.rs +++ b/src/builtin.rs @@ -113,3 +113,57 @@ pub fn builtin_at(value: &Value, index: &Value) -> Result { } Ok(xs[i as usize].clone()) } + +/// Foreach surface: list items unchanged; map → list of keys (insertion order). +pub fn builtin_iter_items(value: &Value) -> Result { + match value { + Value::List(xs) => Ok(Value::List(xs.clone())), + Value::Map(pairs) => Ok(Value::List( + pairs + .iter() + .map(|(k, _)| Value::Text(k.clone())) + .collect(), + )), + _ => Err("foreach needs a list or map".into()), + } +} + +/// Footnote get: `` `xs`[^1] `` (1-based list) or `` `m`[^key] `` (map key). +pub fn builtin_footnote_get(base: &Value, label: &str) -> Result { + let is_digits = !label.is_empty() && label.bytes().all(|b| b.is_ascii_digit()); + match base { + Value::List(xs) => { + if !is_digits { + return Err(format!( + "list footnote index must be digits (1-based), got `[^{label}]`" + )); + } + let n: i64 = label + .parse() + .map_err(|_| format!("invalid list index `[^{label}]`"))?; + if n == 0 { + return Err("`[^0]` is invalid; list indices are 1-based".into()); + } + if n < 1 || (n as usize) > xs.len() { + return Err(format!( + "list index {n} out of range (len {})", + xs.len() + )); + } + Ok(xs[(n as usize) - 1].clone()) + } + Value::Map(pairs) => { + if is_digits { + return Err( + "map footnote must be a key name, not pure digits (keys are text)".into(), + ); + } + pairs + .iter() + .find(|(k, _)| k == label) + .map(|(_, v)| v.clone()) + .ok_or_else(|| format!("missing map key `{label}`")) + } + _ => Err("footnote index needs list or map".into()), + } +} diff --git a/src/bytecode/compile.rs b/src/bytecode/compile.rs index f2afd77..5cdd4e1 100644 --- a/src/bytecode/compile.rs +++ b/src/bytecode/compile.rs @@ -373,6 +373,7 @@ impl<'a> FnCompiler<'a> { } => { self.stmt_span = *span; self.compile_expr(&Expr::Var(collection.clone()))?; + self.emit(Op::IterItems); let coll_slot = self.local_slot(&format!("__coll_{collection}")); self.emit(Op::SetLocal(coll_slot)); self.emit(Op::Pop); @@ -903,6 +904,12 @@ impl<'a> FnCompiler<'a> { } self.emit(Op::BuildMap(pairs.len() as u16)); } + Expr::Index { base, label } => { + self.compile_expr(base)?; + let li = self.add_const(Value::Text(label.clone())); + self.emit(Op::Constant(li)); + self.emit(Op::FootnoteGet); + } Expr::Formula(e) => { let i = self.add_const(Value::Formula(e.clone())); self.emit(Op::Constant(i)); diff --git a/src/bytecode/mod.rs b/src/bytecode/mod.rs index 9c0744d..5190d7a 100644 --- a/src/bytecode/mod.rs +++ b/src/bytecode/mod.rs @@ -54,6 +54,10 @@ pub enum Op { /// Pop sep, then list → push joined text. Join, GetIndex, + /// Pop list/map → push list of foreach items (list elements or map keys). + IterItems, + /// Pop footnote label text, then base → push indexed value (1-based list / map key). + FootnoteGet, /// Call function by index; argc values are on the stack (param order). Call(u16, u8), /// Pop function name text → call zero-arg top-level or lexically visible function. diff --git a/src/bytecode/vm.rs b/src/bytecode/vm.rs index 9cd33b8..5354203 100644 --- a/src/bytecode/vm.rs +++ b/src/bytecode/vm.rs @@ -5,7 +5,8 @@ use std::io::Write; use std::path::{Path, PathBuf}; use crate::builtin::{ - builtin_at, builtin_int, builtin_join, builtin_len, builtin_split, builtin_str, builtin_trim, + builtin_at, builtin_footnote_get, builtin_int, builtin_iter_items, builtin_join, + builtin_len, builtin_split, builtin_str, builtin_trim, builtin_type, }; use crate::host::{call_host, HostContext, HostFn}; @@ -310,6 +311,23 @@ impl Vm { let list = pop(&mut stack).map_err(|m| self.err_at(span, m))?; stack.push(builtin_at(&list, &idx).map_err(|m| self.err_at(span, m))?); } + Op::IterItems => { + let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; + stack.push(builtin_iter_items(&v).map_err(|m| self.err_at(span, m))?); + } + Op::FootnoteGet => { + let label = pop(&mut stack).map_err(|m| self.err_at(span, m))?; + let base = pop(&mut stack).map_err(|m| self.err_at(span, m))?; + let label = match label { + Value::Text(s) => s, + _ => { + return Err(self.err_at(span, "footnote label must be text")); + } + }; + stack.push( + builtin_footnote_get(&base, &label).map_err(|m| self.err_at(span, m))?, + ); + } Op::HostCall(id, argc) => { let hf = HostFn::from_u16(id) .ok_or_else(|| self.err_at(span, format!("unknown host id {id}")))?; diff --git a/src/interp.rs b/src/interp.rs index f023c4f..9a239a2 100644 --- a/src/interp.rs +++ b/src/interp.rs @@ -8,7 +8,8 @@ use crate::ast::{ Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Param, Stmt, UnaryOp, }; use crate::builtin::{ - builtin_at, builtin_int, builtin_join, builtin_len, builtin_split, builtin_str, builtin_trim, + builtin_at, builtin_footnote_get, builtin_int, builtin_iter_items, builtin_join, + builtin_len, builtin_split, builtin_str, builtin_trim, builtin_type, }; use crate::debug::{emit_trace, DebugController}; @@ -339,11 +340,10 @@ impl Interpreter { let coll = env.get(collection).cloned().ok_or_else(|| { self.err(format!("undefined collection `{collection}`")) })?; - let items = match coll { - Value::List(xs) => xs, - other => { - return Err(self.err(format!("foreach needs a list, got {other:?}"))); - } + let items = match builtin_iter_items(&coll) { + Ok(Value::List(xs)) => xs, + Ok(_) => unreachable!(), + Err(m) => return Err(self.err(m)), }; for val in items { env.set(item.clone(), val); @@ -433,6 +433,10 @@ impl Interpreter { } Ok(Value::Map(out)) } + Expr::Index { base, label } => { + let v = self.eval_expr(module, fun, env, base)?; + builtin_footnote_get(&v, label).map_err(|m| self.err(m)) + } Expr::Formula(e) => Ok(Value::Formula(e.clone())), Expr::Code(c) => Ok(Value::Code(c.clone())), } diff --git a/src/parse/expr.rs b/src/parse/expr.rs index 736a494..4586fb7 100644 --- a/src/parse/expr.rs +++ b/src/parse/expr.rs @@ -362,7 +362,20 @@ impl<'a> Parser<'a> { if !self.eat("`") { bail!("unterminated `name`"); } - return Ok(Expr::Var(name)); + let mut expr = Expr::Var(name); + // Postfix footnotes: `xs`[^1] / `m`[^key] / chained `m`[^k][^1] + loop { + self.skip_ws(); + if !self.starts_with("[^") { + break; + } + let label = self.parse_footnote_label()?; + expr = Expr::Index { + base: Box::new(expr), + label, + }; + } + return Ok(expr); } if self.eat(">") { // Inline call: `> name k=v` @@ -484,6 +497,31 @@ impl<'a> Parser<'a> { } Ok(Expr::Interp(parts)) } + + /// Parse `[^label]` after a value; label is text until `]`. + fn parse_footnote_label(&mut self) -> Result { + if !self.eat("[^") { + bail!("expected [^ footnote index"); + } + let start = self.i; + while let Some(c) = self.peek_char() { + if c == ']' { + break; + } + if c == '\n' || c == '\r' { + bail!("unterminated footnote index [^…]"); + } + self.bump_char(); + } + let label = self.src[start..self.i].trim().to_string(); + if !self.eat("]") { + bail!("unterminated footnote index [^…]"); + } + if label.is_empty() { + bail!("empty footnote index `[^]`"); + } + Ok(label) + } } fn is_word_end(s: &str, len: usize) -> bool { diff --git a/src/parse/mod.rs b/src/parse/mod.rs index 6801824..9a39c8c 100644 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -327,13 +327,13 @@ impl<'a> Cursor<'a> { return self.consume_code_fence(span); } let start_i = self.i; - let list = self.consume_table()?; + let table = self.consume_table()?; let end_line = if self.i > start_i { self.lines[self.i - 1].line_no } else { span.line }; - return Ok((Expr::List(list), end_line)); + return Ok((table, end_line)); } if let Some(expr) = try_parse_inline_formula(rhs)? { return Ok((expr, span.line)); @@ -456,10 +456,15 @@ impl<'a> Cursor<'a> { Ok((Expr::Formula(expr), end_line)) } - fn consume_table(&mut self) -> Result> { + /// GFM table after empty RHS: + /// - 1-col → List + /// - first header `@` / `行` / `row` → List of row Maps (marker col excluded) + /// - else ≥2-col → Map (column-oriented) + fn consume_table(&mut self) -> Result { self.skip_noise(); let mut header: Vec = Vec::new(); - let mut rows: Vec = Vec::new(); + let mut header_line: u32 = 1; + let mut data_rows: Vec> = Vec::new(); let mut header_done = false; let mut sep_done = false; while let Some(l) = self.peek() { @@ -470,10 +475,12 @@ impl<'a> Cursor<'a> { if !t.starts_with('|') { break; } + let line_no = l.line_no; self.bump(); let cells = split_table_row(t); if !header_done { header = cells; + header_line = line_no; header_done = true; continue; } @@ -486,23 +493,59 @@ impl<'a> Cursor<'a> { continue; } sep_done = true; - if header.len() <= 1 { - if let Some(cell) = cells.first() { - rows.push(Expr::Literal(cell_literal(cell))); - } - } else { - let mut pairs = Vec::new(); - for (i, key) in header.iter().enumerate() { - let raw = cells.get(i).map(|s| s.as_str()).unwrap_or(""); - pairs.push((key.clone(), Expr::Literal(cell_literal(raw)))); - } - rows.push(Expr::Map(pairs)); - } + data_rows.push(cells); } if !header_done { bail!("expected GFM table after empty assignment"); } - Ok(rows) + let row_oriented = header + .first() + .map(|h| is_row_table_marker(h)) + .unwrap_or(false); + if row_oriented { + return build_row_oriented_table(header, header_line, data_rows); + } + if header.len() <= 1 { + let mut rows = Vec::new(); + for cells in data_rows { + if let Some(cell) = cells.first() { + rows.push(Expr::Literal(cell_literal(cell))); + } + } + return Ok(Expr::List(rows)); + } + // Duplicate header keys are errors (column identity must be unique). + let mut seen = std::collections::HashSet::new(); + for key in &header { + if !seen.insert(key.clone()) { + return Err(Diagnostic::new( + None, + Span { + line: header_line, + col: 1, + }, + format!("duplicate table header `{key}`"), + ) + .into()); + } + } + let n_rows = data_rows.len(); + let mut pairs = Vec::with_capacity(header.len()); + for (col, key) in header.iter().enumerate() { + if n_rows == 1 { + let raw = data_rows[0].get(col).map(|s| s.as_str()).unwrap_or(""); + pairs.push((key.clone(), Expr::Literal(cell_literal(raw)))); + } else { + // 0 rows → empty lists; ≥2 rows → column lists. + let mut col_vals = Vec::with_capacity(n_rows); + for cells in &data_rows { + let raw = cells.get(col).map(|s| s.as_str()).unwrap_or(""); + col_vals.push(Expr::Literal(cell_literal(raw))); + } + pairs.push((key.clone(), Expr::List(col_vals))); + } + } + Ok(Expr::Map(pairs)) } fn parse_branch(&mut self) -> Result { @@ -899,6 +942,55 @@ fn cell_literal(raw: &str) -> Literal { Literal::Text(t.to_string()) } +/// First-column header that opts into row-oriented records (`List` of `Map`). +fn is_row_table_marker(header: &str) -> bool { + matches!(header.trim(), "@" | "行" | "row") +} + +fn build_row_oriented_table( + header: Vec, + header_line: u32, + data_rows: Vec>, +) -> Result { + if header.len() < 2 { + return Err(Diagnostic::new( + None, + Span { + line: header_line, + col: 1, + }, + "row-oriented table needs field columns after `@` / `行` / `row`", + ) + .into()); + } + let fields: Vec = header[1..].to_vec(); + let mut seen = std::collections::HashSet::new(); + for key in &fields { + if !seen.insert(key.clone()) { + return Err(Diagnostic::new( + None, + Span { + line: header_line, + col: 1, + }, + format!("duplicate table header `{key}`"), + ) + .into()); + } + } + let mut rows = Vec::with_capacity(data_rows.len()); + for cells in data_rows { + let mut pairs = Vec::with_capacity(fields.len()); + for (i, key) in fields.iter().enumerate() { + // Skip marker column (index 0); fields start at column 1. + let raw = cells.get(i + 1).map(|s| s.as_str()).unwrap_or(""); + pairs.push((key.clone(), Expr::Literal(cell_literal(raw)))); + } + rows.push(Expr::Map(pairs)); + } + Ok(Expr::List(rows)) +} + fn split_table_row(line: &str) -> Vec { let t = line.trim(); let t = t.strip_prefix('|').unwrap_or(t); diff --git a/src/value.rs b/src/value.rs index 2825d9c..7c2f03a 100644 --- a/src/value.rs +++ b/src/value.rs @@ -19,9 +19,9 @@ pub enum Value { /// Floating-point number (`type` → `num`). Num(f64), Text(String), - /// Single-column table rows, or list of row maps for multi-column tables. + /// Vertical (1-column) table rows, or nested list values in a column map. List(Vec), - /// JSON object / string-keyed map (insertion order). + /// String-keyed map (insertion order): JSON objects / horizontal tables. Map(Vec<(String, Value)>), /// Parsed symbolic expression (`type` → `formula`). Formula(FormulaExpr), @@ -56,7 +56,13 @@ impl Value { let parts: Vec = xs.iter().map(|v| v.as_display()).collect(); format!("[{}]", parts.join(", ")) } - Value::Map(_) => "".into(), + Value::Map(pairs) => { + let parts: Vec = pairs + .iter() + .map(|(k, v)| format!("{k}: {}", v.as_display())) + .collect(); + format!("{{{}}}", parts.join(", ")) + } Value::Formula(e) => e.as_display(), Value::Code(c) => format!("```{}\n{}\n```", c.lang, c.source), } diff --git a/src/view/render.rs b/src/view/render.rs index 868d022..ead7adf 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -127,6 +127,7 @@ fn collect_input_prompts_expr(expr: &Expr, out: &mut Vec) { collect_input_prompts_expr(e, out); } } + Expr::Index { base, .. } => collect_input_prompts_expr(base, out), Expr::Literal(_) | Expr::Var(_) | Expr::Interp(_) | Expr::Formula(_) | Expr::Code(_) => {} } } @@ -691,6 +692,9 @@ fn expr_prec(expr: &Expr, parent_prec: u8) -> String { .collect(); format!("{{{}}}", parts.join(", ")) } + Expr::Index { base, label } => { + format!("{}[^{}]", expr_prec(base, 8), label) + } Expr::Formula(e) => format!("$$ {} $$", e.as_display()), Expr::Code(c) => format!("```{} …```", c.lang), } diff --git a/tests/errors/footnote-missing-key.mq.md b/tests/errors/footnote-missing-key.mq.md new file mode 100644 index 0000000..05934d4 --- /dev/null +++ b/tests/errors/footnote-missing-key.mq.md @@ -0,0 +1,15 @@ +--- +title: footnote missing map key +--- + +# main + +`分类` = + +| 苹果 | 黄瓜 | +|------|------| +| 水果 | 蔬菜 | + +*`x` = `分类`[^香蕉] * + +> print text=`x` diff --git a/tests/errors/footnote-oob.mq.md b/tests/errors/footnote-oob.mq.md new file mode 100644 index 0000000..e9202e1 --- /dev/null +++ b/tests/errors/footnote-oob.mq.md @@ -0,0 +1,15 @@ +--- +title: footnote list out of range +--- + +# main + +`篮子` = + +| 果 | +|----| +| 苹果 | + +*`x` = `篮子`[^2] * + +> print text=`x` diff --git a/tests/errors/footnote-zero.mq.md b/tests/errors/footnote-zero.mq.md new file mode 100644 index 0000000..df01ace --- /dev/null +++ b/tests/errors/footnote-zero.mq.md @@ -0,0 +1,15 @@ +--- +title: footnote [^0] invalid +--- + +# main + +`篮子` = + +| 果 | +|----| +| 苹果 | + +*`x` = `篮子`[^0] * + +> print text=`x` diff --git a/tests/errors/table-dup-header.mq.md b/tests/errors/table-dup-header.mq.md new file mode 100644 index 0000000..0f5f963 --- /dev/null +++ b/tests/errors/table-dup-header.mq.md @@ -0,0 +1,13 @@ +--- +title: duplicate table header +--- + +# main + +`t` = + +| a | a | +|---|---| +| 1 | 2 | + +> print text=nope diff --git a/tests/errors/table-row-marker-only.mq.md b/tests/errors/table-row-marker-only.mq.md new file mode 100644 index 0000000..eb295ac --- /dev/null +++ b/tests/errors/table-row-marker-only.mq.md @@ -0,0 +1,13 @@ +--- +title: row marker without field columns +--- + +# main + +`t` = + +| 行 | +|----| +| 1 | + +> print text=nope diff --git a/tests/gold.rs b/tests/gold.rs index 5cf5e4d..005a1db 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -112,6 +112,60 @@ fn structure_collection() { 桃"); } +#[test] +fn structure_collection_map() { + assert_out( + "tests/structure/collection-map.mq.md", + "水果 +蔬菜 +数码用品 +苹果 +黄瓜 +鼠标", + ); +} + +#[test] +fn structure_collection_map_list() { + assert_out( + "tests/structure/collection-map-list.mq.md", + "红富士 +[红富士, 嘎啦] +黄瓜条", + ); +} + +#[test] +fn structure_footnote_index() { + assert_out( + "tests/structure/footnote-index.mq.md", + "苹果 +梨 +桃", + ); +} + +#[test] +fn structure_collection_records() { + assert_out( + "tests/structure/collection-records.mq.md", + "{品名: 苹果, 数量: 2} +苹果 +3 +{品名: 苹果, 数量: 2} +{品名: 梨, 数量: 3}", + ); +} + +#[test] +fn structure_collection_records_at() { + assert_out( + "tests/structure/collection-records-at.mq.md", + "apple +3", + ); +} + #[test] fn structure_import() { assert_out( @@ -358,6 +412,51 @@ fn error_div_zero() { assert_err("tests/errors/div-zero.mq.md", "7:1", "division by zero"); } +#[test] +fn error_footnote_zero() { + assert_err( + "tests/errors/footnote-zero.mq.md", + "13:1", + "`[^0]` is invalid", + ); +} + +#[test] +fn error_footnote_oob() { + assert_err( + "tests/errors/footnote-oob.mq.md", + "13:1", + "out of range", + ); +} + +#[test] +fn error_footnote_missing_key() { + assert_err( + "tests/errors/footnote-missing-key.mq.md", + "13:1", + "missing map key", + ); +} + +#[test] +fn error_table_dup_header() { + assert_err( + "tests/errors/table-dup-header.mq.md", + "9:1", + "duplicate table header", + ); +} + +#[test] +fn error_table_row_marker_only() { + assert_err( + "tests/errors/table-row-marker-only.mq.md", + "9:1", + "row-oriented table needs field columns", + ); +} + #[test] fn error_bad_int() { assert_err( @@ -493,6 +592,65 @@ fn bytecode_collection() { ); } +#[test] +fn bytecode_collection_map() { + assert_out_backend( + "tests/structure/collection-map.mq.md", + "bytecode", + "水果 +蔬菜 +数码用品 +苹果 +黄瓜 +鼠标", + ); +} + +#[test] +fn bytecode_collection_map_list() { + assert_out_backend( + "tests/structure/collection-map-list.mq.md", + "bytecode", + "红富士 +[红富士, 嘎啦] +黄瓜条", + ); +} + +#[test] +fn bytecode_footnote_index() { + assert_out_backend( + "tests/structure/footnote-index.mq.md", + "bytecode", + "苹果 +梨 +桃", + ); +} + +#[test] +fn bytecode_collection_records() { + assert_out_backend( + "tests/structure/collection-records.mq.md", + "bytecode", + "{品名: 苹果, 数量: 2} +苹果 +3 +{品名: 苹果, 数量: 2} +{品名: 梨, 数量: 3}", + ); +} + +#[test] +fn bytecode_collection_records_at() { + assert_out_backend( + "tests/structure/collection-records-at.mq.md", + "bytecode", + "apple +3", + ); +} + #[test] fn bytecode_print_keyword() { assert_out_backend( @@ -786,7 +944,7 @@ fn lib_writeback_get() { #[test] fn lib_subtask_spawn() { - assert_out("tests/lib/subtask-spawn.mq.md", "child-ok\ndone\nquiet-ok"); + assert_out("tests/lib/subtask-spawn.mq.md", "child_ok\ndone\nquiet-ok"); } #[test] diff --git a/tests/lib/subtask-spawn.mq.md b/tests/lib/subtask-spawn.mq.md index 910fd1f..72f341c 100644 --- a/tests/lib/subtask-spawn.mq.md +++ b/tests/lib/subtask-spawn.mq.md @@ -26,7 +26,7 @@ title: subtask spawn join *`val2` = > json.get value=`waited2` key=value * 1. `code2` == 0 - 1. `val2` == "child-ok" + 1. `val2` == "child_ok" > print text=quiet-ok 2. * > print text=quiet-bad-value diff --git a/tests/structure/collection-map-list.mq.md b/tests/structure/collection-map-list.mq.md new file mode 100644 index 0000000..97d3ae6 --- /dev/null +++ b/tests/structure/collection-map-list.mq.md @@ -0,0 +1,24 @@ +--- +title: 横表多行 → 字典套列表 +--- + +# main + +`货架` = + +| 苹果 | 黄瓜 | +|------|------| +| 红富士 | 青瓜 | +| 嘎啦 | 黄瓜条 | + +*`第一种苹果` = `货架`[^苹果][^1] * + +> print text=`第一种苹果` + +*`列` = `货架`[^苹果] * + +> print text=`列` + +*`第二种黄瓜` = `货架`[^黄瓜][^2] * + +> print text=`第二种黄瓜` diff --git a/tests/structure/collection-map.mq.md b/tests/structure/collection-map.mq.md new file mode 100644 index 0000000..81222ab --- /dev/null +++ b/tests/structure/collection-map.mq.md @@ -0,0 +1,26 @@ +--- +title: 横表单行 → 字典 +--- + +# main + +`分类` = + +| 苹果 | 黄瓜 | 鼠标 | +|------|------|------| +| 水果 | 蔬菜 | 数码用品 | + +*`种` = `分类`[^苹果] * + +> print text=`种` + +*`种` = `分类`[^黄瓜] * + +> print text=`种` + +*`种` = `分类`[^鼠标] * + +> print text=`种` + +- [`键`](`分类`) + > print text=`键` diff --git a/tests/structure/collection-records-at.mq.md b/tests/structure/collection-records-at.mq.md new file mode 100644 index 0000000..ec23282 --- /dev/null +++ b/tests/structure/collection-records-at.mq.md @@ -0,0 +1,20 @@ +--- +title: row records with @ marker +--- + +# main + +`orders` = + +| @ | name | qty | +|---|------|-----| +| 1 | apple | 2 | +| 2 | pear | 3 | + +*`n` = `orders`[^1][^name] * + +> print text=`n` + +*`q` = `orders`[^2][^qty] * + +> print text=`q` diff --git a/tests/structure/collection-records.mq.md b/tests/structure/collection-records.mq.md new file mode 100644 index 0000000..c691f1a --- /dev/null +++ b/tests/structure/collection-records.mq.md @@ -0,0 +1,27 @@ +--- +title: 行向记录表(首列 行 / @) +--- + +# main + +`订单` = + +| 行 | 品名 | 数量 | +|----|------|------| +| 1 | 苹果 | 2 | +| 2 | 梨 | 3 | + +*`第一` = `订单`[^1] * + +> print text=`第一` + +*`名` = `订单`[^1][^品名] * + +> print text=`名` + +*`量` = `订单`[^2][^数量] * + +> print text=`量` + +- [`记录`](`订单`) + > print text=`记录` diff --git a/tests/structure/footnote-index.mq.md b/tests/structure/footnote-index.mq.md new file mode 100644 index 0000000..94b65b8 --- /dev/null +++ b/tests/structure/footnote-index.mq.md @@ -0,0 +1,25 @@ +--- +title: 脚注取元(列表下标) +--- + +# main + +`篮子` = + +| 果 | +|----| +| 苹果 | +| 梨 | +| 桃 | + +*`第一` = `篮子`[^1] * + +> print text=`第一` + +*`第二` = `篮子`[^2] * + +> print text=`第二` + +*`第三` = `篮子`[^3] * + +> print text=`第三`