Implement table semantic T0-T4: map/records/footnote get

- 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 <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-10 09:50:21 +08:00
1 parent 3463628165
commit a23fdedfa2
37 files changed
+846 -51

No files matched your search

+1 -1
View File
@@ -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 |
+32
View File
@@ -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
+1 -1
View File
@@ -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 调研 |
+34 -2
View File
@@ -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` 遍历**键**(值用脚注取)。
---
+34 -9
View File
@@ -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][^字段] `` |
竖表表头是「元素名」;横表表头是「键名」——几何决定角色,减少「这张表到底是啥」的歧义。
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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` =
+2 -2
View File
@@ -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` =
+2 -2
View File
@@ -1,11 +1,11 @@
---
title: 集合(表)
description: GFM 表格即集合
description: 单列竖表即列表
---
# main
Markdown 表是集合;用循环读每一行。
单列 Markdown 表是列表;用循环读每一项。按下标用 `` `篮子`[^1] ``(1-based)。
`篮子` =
+22
View File
@@ -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`
+22
View File
@@ -0,0 +1,22 @@
---
title: 字典(横表)
description: 多列表是字典;脚注按键取元
---
# main
多列且仅一行数据的表是字典。用脚注键取元。
`分类` =
| 苹果 | 黄瓜 |
|------|------|
| 水果 | 蔬菜 |
*`种` = `分类`[^苹果] *
> 打印 内容=`种`
*`种` = `分类`[^黄瓜] *
> 打印 内容=`种`
+23
View File
@@ -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`
+23
View File
@@ -0,0 +1,23 @@
---
title: 行向记录表
description: 首列表头「行」→ 每行一个字典
---
# main
首列表头为 `行`(或 `@` / `row`)时,每行数据是一个字典;标记列不进入字段。
`订单` =
| 行 | 品名 | 数量 |
|----|------|------|
| 1 | 苹果 | 2 |
| 2 | 梨 | 3 |
*`名` = `订单`[^1][^品名] *
> 打印 内容=`名`
*`量` = `订单`[^2][^数量] *
> 打印 内容=`量`
+1 -1
View File
@@ -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 |
+32
View File
@@ -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
+7 -1
View File
@@ -139,8 +139,14 @@ pub enum Expr {
},
Call(CallExpr),
List(Vec<Expr>),
/// 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<Expr>,
/// 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).
+54
View File
@@ -113,3 +113,57 @@ pub fn builtin_at(value: &Value, index: &Value) -> Result<Value, String> {
}
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<Value, String> {
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<Value, String> {
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()),
}
}
+7
View File
@@ -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));
+4
View File
@@ -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.
+19 -1
View File
@@ -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}")))?;
+10 -6
View File
@@ -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())),
}
+39 -1
View File
@@ -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<String> {
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 {
+109 -17
View File
@@ -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<Vec<Expr>> {
/// 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<Expr> {
self.skip_noise();
let mut header: Vec<String> = Vec::new();
let mut rows: Vec<Expr> = Vec::new();
let mut header_line: u32 = 1;
let mut data_rows: Vec<Vec<String>> = 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<Stmt> {
@@ -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<String>,
header_line: u32,
data_rows: Vec<Vec<String>>,
) -> Result<Expr> {
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<String> = 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<String> {
let t = line.trim();
let t = t.strip_prefix('|').unwrap_or(t);
+9 -3
View File
@@ -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<Value>),
/// 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<String> = xs.iter().map(|v| v.as_display()).collect();
format!("[{}]", parts.join(", "))
}
Value::Map(_) => "<map>".into(),
Value::Map(pairs) => {
let parts: Vec<String> = 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),
}
+4
View File
@@ -127,6 +127,7 @@ fn collect_input_prompts_expr(expr: &Expr, out: &mut Vec<String>) {
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),
}
+15
View File
@@ -0,0 +1,15 @@
---
title: footnote missing map key
---
# main
`分类` =
| 苹果 | 黄瓜 |
|------|------|
| 水果 | 蔬菜 |
*`x` = `分类`[^香蕉] *
> print text=`x`
+15
View File
@@ -0,0 +1,15 @@
---
title: footnote list out of range
---
# main
`篮子` =
| 果 |
|----|
| 苹果 |
*`x` = `篮子`[^2] *
> print text=`x`
+15
View File
@@ -0,0 +1,15 @@
---
title: footnote [^0] invalid
---
# main
`篮子` =
| 果 |
|----|
| 苹果 |
*`x` = `篮子`[^0] *
> print text=`x`
+13
View File
@@ -0,0 +1,13 @@
---
title: duplicate table header
---
# main
`t` =
| a | a |
|---|---|
| 1 | 2 |
> print text=nope
+13
View File
@@ -0,0 +1,13 @@
---
title: row marker without field columns
---
# main
`t` =
| 行 |
|----|
| 1 |
> print text=nope
+159 -1
View File
@@ -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]
+1 -1
View File
@@ -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
+24
View File
@@ -0,0 +1,24 @@
---
title: 横表多行 → 字典套列表
---
# main
`货架` =
| 苹果 | 黄瓜 |
|------|------|
| 红富士 | 青瓜 |
| 嘎啦 | 黄瓜条 |
*`第一种苹果` = `货架`[^苹果][^1] *
> print text=`第一种苹果`
*`列` = `货架`[^苹果] *
> print text=`列`
*`第二种黄瓜` = `货架`[^黄瓜][^2] *
> print text=`第二种黄瓜`
+26
View File
@@ -0,0 +1,26 @@
---
title: 横表单行 → 字典
---
# main
`分类` =
| 苹果 | 黄瓜 | 鼠标 |
|------|------|------|
| 水果 | 蔬菜 | 数码用品 |
*`种` = `分类`[^苹果] *
> print text=`种`
*`种` = `分类`[^黄瓜] *
> print text=`种`
*`种` = `分类`[^鼠标] *
> print text=`种`
- [`键`](`分类`)
> print text=`键`
@@ -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`
+27
View File
@@ -0,0 +1,27 @@
---
title: 行向记录表(首列 行 / @)
---
# main
`订单` =
| 行 | 品名 | 数量 |
|----|------|------|
| 1 | 苹果 | 2 |
| 2 | 梨 | 3 |
*`第一` = `订单`[^1] *
> print text=`第一`
*`名` = `订单`[^1][^品名] *
> print text=`名`
*`量` = `订单`[^2][^数量] *
> print text=`量`
- [`记录`](`订单`)
> print text=`记录`
+25
View File
@@ -0,0 +1,25 @@
---
title: 脚注取元(列表下标)
---
# main
`篮子` =
| 果 |
|----|
| 苹果 |
| 梨 |
| 桃 |
*`第一` = `篮子`[^1] *
> print text=`第一`
*`第二` = `篮子`[^2] *
> print text=`第二`
*`第三` = `篮子`[^3] *
> print text=`第三`