From a5d30c00b39eb629818d3863aa6eac3ecb634e9f Mon Sep 17 00:00:00 2001 From: cflmy Date: Wed, 5 Aug 2026 09:14:26 +0800 Subject: [PATCH] Add bilingual public docs, keyword aliases, and frontmatter stdin for view. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit English/Chinese user pages sit side by side; L0 builtins and lib/ text|表 dual APIs land with gold coverage. Capture/view input demos use stdin:/输入: so static export and first page load succeed. Co-authored-by: Cursor --- .github/workflows/pages.yml | 2 +- doc/README.md | 5 +- doc/design/call-arguments.md | 6 +- doc/design/keywords-i18n.md | 137 +++++++++++++++++++ doc/design/keywords.md | 88 +++++++------ doc/design/stdlib-i18n.md | 134 +++++++++++++++++++ doc/design/stdlib.md | 87 ++++++++++++ doc/design/user-site.md | 2 +- doc/roadmap/next-phase.md | 6 +- lib/table.mq.md | 15 +++ lib/text.mq.md | 21 +++ lib/文本.mq.md | 21 +++ lib/表.mq.md | 15 +++ public/00-welcome.mq.md | 30 ++--- public/00-欢迎.mq.md | 27 ++++ public/README.md | 13 +- public/features/01-phase-i-treewalk.mq.md | 12 +- public/features/01-树遍历.mq.md | 14 ++ public/features/02-bytecode.mq.md | 12 +- public/features/02-字节码.mq.md | 18 +++ public/features/03-view-and-docs.mq.md | 14 +- public/features/03-view与文档.mq.md | 16 +++ public/keywords/bool-logic.mq.md | 6 +- public/keywords/input.mq.md | 7 +- public/keywords/print.mq.md | 8 +- public/keywords/stdlib.mq.md | 26 +++- public/keywords/内核双名.mq.md | 16 +++ public/keywords/布尔逻辑.mq.md | 23 ++++ public/keywords/打印.mq.md | 14 ++ public/keywords/标准库.mq.md | 34 +++++ public/keywords/输入.mq.md | 13 ++ public/lib-import.mq.md | 13 ++ public/lib-导入.mq.md | 13 ++ public/structure/01-hello.mq.md | 6 +- public/structure/01-你好.mq.md | 12 ++ public/structure/02-function.mq.md | 16 +-- public/structure/02-函数.mq.md | 17 +++ public/structure/03-positional-call.mq.md | 18 +-- public/structure/03-位置调用.mq.md | 19 +++ public/structure/04-branch.mq.md | 12 +- public/structure/04-分支.mq.md | 17 +++ public/structure/05-loop.mq.md | 24 ++-- public/structure/05-循环.mq.md | 28 ++++ public/structure/06-collection.mq.md | 22 ++-- public/structure/06-集合.mq.md | 19 +++ public/structure/import/main.mq.md | 12 +- public/structure/import/utils.mq.md | 12 +- public/structure/import/主.mq.md | 17 +++ public/structure/import/工具.mq.md | 14 ++ src/aliases.rs | 89 +++++++++++++ src/builtin.rs | 78 +++++++++++ src/bytecode/compile.rs | 92 +++++++++++-- src/bytecode/mod.rs | 8 ++ src/bytecode/vm.rs | 36 +++-- src/input_feed.rs | 154 +++++++++++++++++++++- src/interp.rs | 66 +++++++++- src/lib.rs | 14 +- src/load.rs | 76 ++++++++++- src/parse/expr.rs | 68 ++++++---- src/parse/mod.rs | 6 + src/view/html.rs | 14 +- src/view/mod.rs | 21 +-- tests/errors/bad-split-sep.mq.md | 7 + tests/gold.rs | 97 ++++++++++++++ tests/keywords/stdlib-more.mq.md | 30 +++++ tests/keywords/zh-bool.mq.md | 20 +++ tests/keywords/zh-builtins.mq.md | 18 +++ tests/structure/import-lib.mq.md | 26 ++++ 68 files changed, 1812 insertions(+), 241 deletions(-) create mode 100644 doc/design/keywords-i18n.md create mode 100644 doc/design/stdlib-i18n.md create mode 100644 doc/design/stdlib.md create mode 100644 lib/table.mq.md create mode 100644 lib/text.mq.md create mode 100644 lib/文本.mq.md create mode 100644 lib/表.mq.md create mode 100644 public/00-欢迎.mq.md create mode 100644 public/features/01-树遍历.mq.md create mode 100644 public/features/02-字节码.mq.md create mode 100644 public/features/03-view与文档.mq.md create mode 100644 public/keywords/内核双名.mq.md create mode 100644 public/keywords/布尔逻辑.mq.md create mode 100644 public/keywords/打印.mq.md create mode 100644 public/keywords/标准库.mq.md create mode 100644 public/keywords/输入.mq.md create mode 100644 public/lib-import.mq.md create mode 100644 public/lib-导入.mq.md create mode 100644 public/structure/01-你好.mq.md create mode 100644 public/structure/02-函数.mq.md create mode 100644 public/structure/03-位置调用.mq.md create mode 100644 public/structure/04-分支.mq.md create mode 100644 public/structure/05-循环.mq.md create mode 100644 public/structure/06-集合.mq.md create mode 100644 public/structure/import/主.mq.md create mode 100644 public/structure/import/工具.mq.md create mode 100644 src/aliases.rs create mode 100644 tests/errors/bad-split-sep.mq.md create mode 100644 tests/keywords/stdlib-more.mq.md create mode 100644 tests/keywords/zh-bool.mq.md create mode 100644 tests/keywords/zh-builtins.mq.md create mode 100644 tests/structure/import-lib.mq.md diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index f1f3cc3..e89d029 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -28,7 +28,7 @@ jobs: - name: Build & export site run: | cargo build --release - find public -name '*.mq.md' ! -name 'utils.mq.md' -print0 \ + find public -name '*.mq.md' ! -name 'utils.mq.md' ! -name '¹¤¾ß.mq.md' -print0 \ | xargs -0 -n1 ./target/release/marqdo run ./target/release/marqdo view output public -o public diff --git a/doc/README.md b/doc/README.md index ad7a643..a844724 100644 --- a/doc/README.md +++ b/doc/README.md @@ -22,7 +22,10 @@ | [design/tech-stack.md](design/tech-stack.md) | 实现栈对比 | | [adr/0001-implementation-language.md](adr/0001-implementation-language.md) | **Accepted:Rust 参考解释器;不用 Flex/Bison** | | [design/dependencies.md](design/dependencies.md) | 依赖详单(无 Flex/Bison) | -| [design/keywords.md](design/keywords.md) | **英文最小关键字 / 内置 `print` `input`** | +| [design/keywords.md](design/keywords.md) | **英文最小关键字 / 内置函数** | +| [design/keywords-i18n.md](design/keywords-i18n.md) | **内核中英双名(无需导入;少而精)** | +| [design/stdlib.md](design/stdlib.md) | **P2 标准库:内置 + `lib/` + 错误约定** | +| [design/stdlib-i18n.md](design/stdlib-i18n.md) | **标准库中英命名:靠库文件名区分,无 lang 开关** | | [design/call-arguments.md](design/call-arguments.md) | **调用:具名 + 位置实参** | | [design/examples-and-tests.md](design/examples-and-tests.md) | **tests/ 金样例目录布局** | | [design/view.md](design/view.md) | **`marqdo view` / `view output` 黑白极简 + 静态文档** | diff --git a/doc/design/call-arguments.md b/doc/design/call-arguments.md index 1864769..7bfe0db 100644 --- a/doc/design/call-arguments.md +++ b/doc/design/call-arguments.md @@ -32,8 +32,10 @@ positional ::= value_token - `value`(具名右侧):可含空格与 `` `var` `` 插值,直到下一个 `ident=` 边界。 - `value_token`(位置):空白分隔的一个词法单元——数字、`` `名` ``、标识/文本词;**不含空格**。多词字符串请用具名,例如 `> print text=Hello World!`。 -- 内置 `print` 形参名为 `text`:`> print Hi` 与 `> print text=Hi` 等价。 -- 内置 `len` / `str` / `int` 形参名为 `value`。 +- 内置 `print` / `打印` 形参:`text` ≡ `内容`。 +- `input` / `输入`:`prompt` ≡ `提示`。 +- `len` / `长度`、`str` / `文本`、`int` / `整数`:`value` ≡ `值`。 +- 完整中英双名见 [keywords-i18n.md](keywords-i18n.md)。 --- diff --git a/doc/design/keywords-i18n.md b/doc/design/keywords-i18n.md new file mode 100644 index 0000000..aea629d --- /dev/null +++ b/doc/design/keywords-i18n.md @@ -0,0 +1,137 @@ +# 内置关键字 / 函数:中英双名(草案) + +| | | +|---|---| +| 状态 | **已定(已实现)** | +| 日期 | 2026-08-05 | +| 原则 | **无需导入**;中英为**同一语义的别名**,不是语言模式开关 | +| 相关 | [keywords.md](keywords.md) · [stdlib-i18n.md](stdlib-i18n.md) · [call-arguments.md](call-arguments.md) | + +--- + +## 1. 动机 + +Marqdo 要中英文都能自然书写。标准库已约定「**库文件名区分语言**」(见 [stdlib-i18n.md](stdlib-i18n.md));对**不必导入**的一层——字面量关键字与极少内置函数——也要对等提供中文名。 + +正因为每增加一个内置名,就要同时维护中英(及日后更多语言)别名,所以: + +> **关键字 / 内置必须少而精**——体积在「名字 × 语言」上放大,而不是在功能清单上堆满。 + +更多能力进可导入的 `lib/`,用中英**不同库文件、不同函数名**扩展,不膨胀解释器内核。 + +--- + +## 2. 分层(与标准库对齐) + +| 层 | 是否导入 | 中英怎么区分 | +|----|----------|--------------| +| **L0 内核** | 否 | **同一文件内双名**:`print` ≡ `打印`;`True` ≡ `真` | +| **L1 标准库** | 是(`> lib/…`) | **不同文件**:`text.mq.md` vs `文本.mq.md`(见 i18n 草案) | + +L0 **不做** `lang:`、不做「当前语言模式」;写英文名就用英文,写中文名就用中文,可在同一程序里混用。 + +--- + +## 3. 范围:哪些要双名 + +### 3.1 字面量 / 逻辑关键字(词法保留) + +控制流仍靠 Markdown(`#` `+` `-` `*` `**`),**不**为 `if`/`while`/`def` 做中英关键字。 + +| 英文 | 中文(提案) | 备注 | +|------|--------------|------| +| `True` | `真` | 布尔真 | +| `False` | `假` | 布尔假 | +| `None` | `空` | 空值 | +| `and` | `且` | 逻辑与 | +| `or` | `或` | 逻辑或 | +| `not` | `非` | 逻辑非 | + +中英文名均**不可作变量名**(同一保留集)。 + +### 3.2 内置函数(可调用、无需导入) + +**仅**下列核心五项做中英双名(与「少而精」一致): + +| 英文 | 中文(提案) | 作用 | +|------|--------------|------| +| `print` | `打印` | 写 stdout | +| `input` | `输入` | 读一行 | +| `len` | `长度` | 文本/表长度 | +| `str` | `文本` | 转为显示文本 | +| `int` | `整数` | 转为整数 | + +形参名也提供中英别名(便于纯中文调用): + +| 英文形参 | 中文形参 | 用于 | +|----------|----------|------| +| `text` | `内容` | `print` / `打印` | +| `prompt` | `提示` | `input` / `输入` | +| `value` | `值` | `len`/`str`/`int` 及对应中文名 | + +示例(等价): + +```markdown +> print text=Hello +> 打印 内容=你好 + +*`n` = > len `s`* +*`n` = > 长度 值=`s`* +``` + +### 3.3 明确不进 L0 双名表 + +下列若已在解释器中实现,视为**宿主原语 / 过渡 API**,**不**再批中文内核别名;应迁入或仅通过标准库暴露(中英分文件): + +| 英文名 | 去向 | +|--------|------| +| `type` | L1 或维持实现细节,不进「关键字最少集」宣传 | +| `trim` `split` `join` | L1:`lib/text.mq.md` / `lib/文本.mq.md` | +| `at` | L1:`lib/table.mq.md` / `lib/表.mq.md` | + +这样 L0 公开面 ≈ **6 个关键字词 ×2 + 5 个函数 ×2**,而不是「每个工具函数都 ×2」。 + +--- + +## 4. 语义规则 + +1. **别名等价**:中英文名绑定同一实现;诊断文案可用英文稳定串(金样例已有),用户文档中英均可举例。 +2. **可混用**:同一文件可同时出现 `print` 与 `打印`、`True` 与 `真`。 +3. **遮蔽**:用户 `# 打印` 与 `# print` 均会遮蔽对应内置名(实现阶段应警告)。 +4. **大小写**:英文关键字保持 Python 风格(`True`/`False`/`None`);中文无名感大小写问题。 +5. **扩语言**:日后日文等 → 再为 L0 增加第三个别名列;仍无「名字表」而非语言开关。标准库继续用**文件名**区分(见 i18n 草案)。 + +--- + +## 5. 与旧决议的关系 + +- 旧文「中文 `print` 废弃、统一为 `print`」:**废止**;改为正式双名 `print` / `打印`。 +- [keywords.md](keywords.md) 原则条「英文标识」改为「**内核双名;标准库分文件**」——实现阶段改正文。 +- 不引入中文控制流关键字(`如果`/`循环` 等);分支循环仍用 `+` / `-`。 + +--- + +## 6. 文档与金样例义务(实现时) + +| 项 | 要求 | +|----|------| +| `keywords.md` | L0 表改为中英并列;砍掉对 `trim`/`split`/… 的「内核关键字」宣传 | +| `public/` | 英 / 中文件同目录并列(拉丁名 vs 中文名) | +| `tests/` | 中文关键字 / `打印`·`长度` 等金样例;与英文样例对等 | +| 诊断 | 位置格式不变;message 可暂维持英文,或中英均可接受(另开小节) | + +--- + +## 7. 实现备忘(暂不开发) + +1. 词法 / 解析:字面量与 `and`/`or`/`not` 识别中文别名。 +2. 调用解析:内置表按别名归一到同一 `BuiltinId`。 +3. 形参绑定:`text`≡`内容`,`prompt`≡`提示`,`value`≡`值`。 +4. **不要**加 `lang:` 或全局「中文模式」。 +5. 与 [stdlib-i18n.md](stdlib-i18n.md) 一并落地时:先收束 L0 公开面,再铺 `lib/text` ↔ `lib/文本`。 + +--- + +## 8. 一句话 + +**内核:中英别名、无需导入、必须少;标准库:中英分文件、靠导入路径选择——这样 Marqdo 才能中英文通用而不把解释器撑爆。** diff --git a/doc/design/keywords.md b/doc/design/keywords.md index 83ddd32..1c6c4db 100644 --- a/doc/design/keywords.md +++ b/doc/design/keywords.md @@ -2,58 +2,63 @@ | | | |---|---| -| 状态 | 已定(前期够用) | -| 日期 | 2026-08-04 | -| 原则 | **英文**;参考 [Python](https://realpython.com/python-keywords/) 但远更少;控制流仍靠 Markdown 标记,不引入 `if`/`while`/`def` | -| 相关 | [markdown-mapping.md](markdown-mapping.md) | +| 状态 | 已定(中英双名) | +| 日期 | 2026-08-05 | +| 原则 | **少而精**;控制流靠 Markdown;内核中英**别名等价**(见 [keywords-i18n.md](keywords-i18n.md)) | +| 相关 | [markdown-mapping.md](markdown-mapping.md) · [keywords-i18n.md](keywords-i18n.md) · [stdlib-i18n.md](stdlib-i18n.md) | --- ## 1. 设计原则 1. **标记承担架构**:函数=`#`,分支=`+`,循环=`-`,返回=`**…**`,语句=`*…*`。因此 **不**把 `def`/`if`/`else`/`while`/`for`/`return` 做成关键字。 -2. **英文标识**:内置与字面量用英文,便于工具高亮与国际协作。 -3. **学 Python 的边界**:Python 3 里 [`print` / `input` 是内置函数,不是关键字](https://realpython.com/python-keywords/);布尔与空值是字面量关键字。Marqdo 同样区分 **关键字** vs **内置函数名**。 -4. **宁少勿多**:前期只列执行金样例所需;要加再进 ADR。 +2. **内核双名**:字面量 / 逻辑词 / 五个核心内置函数均有中英别名,**无需导入**,可混用。 +3. **学 Python 的边界**:区分 **关键字** vs **内置函数名**。 +4. **宁少勿多**:扩展能力进可导入标准库(中英分文件,见 [stdlib-i18n.md](stdlib-i18n.md))。 --- ## 2. 关键字(词法保留,不可作变量名) -| 关键字 | 含义 | 备注 | -|--------|------|------| -| `True` | 布尔真 | 对齐 Python 大小写 | -| `False` | 布尔假 | | -| `None` | 空值 | | -| `and` | 逻辑与 | 表达式内 | -| `or` | 逻辑或 | | -| `not` | 逻辑非 | | +| 英文 | 中文 | 含义 | +|------|------|------| +| `True` | `真` | 布尔真 | +| `False` | `假` | 布尔假 | +| `None` | `空` | 空值 | +| `and` | `且` | 逻辑与 | +| `or` | `或` | 逻辑或 | +| `not` | `非` | 逻辑非 | -**本期不引入:** `if` `else` `elif` `while` `for` `def` `class` `return` `import` `pass` `break` `continue` `in` `is` `lambda` … -(`else` 分支臂仍用臂头单独的 `*` 标记,不是单词 `else`。) +**不引入:** `if` `else` `while` `for` `def` `return` …(分支臂 `*` 不是单词 `else`。) --- -## 3. 内置函数(可调用名,建议勿遮蔽) +## 3. 内置函数(可调用,无需导入) -| 名称 | 作用 | 调用示例 | -|------|------|----------| -| `print` | 写到 stdout(副作用) | `> print text=Hello` 或 `> print Hello`(位置实参,见 [call-arguments.md](call-arguments.md)) | -| `input` | 从 stdin 读一行(返回文本) | `*`name` = > input prompt=Name: *` | -| `len` | 文本或表的长度 | `*`n` = > len `s`*` 或 `> len value=`s`` | -| `str` | 转为显示文本 | `*`t` = > str 42*` | -| `int` | 转为整数 | `*`i` = > int 7*` / `> int True` / 文本十进制 | +| 英文 | 中文 | 作用 | +|------|------|------| +| `print` | `打印` | 写 stdout | +| `input` | `输入` | 读一行;capture / view 用 frontmatter `stdin:` / `输入:`、表单或 `--stdin-file` 预置 | +| `len` | `长度` | 文本/表长度 | +| `str` | `文本` | 转为显示文本 | +| `int` | `整数` | 转为整数 | -参数约定(v0): +形参别名: -- `print`:具名实参 `text`(必填);日后可扩展 `end` 等。 -- `input`:可选 `prompt`;返回用户输入字符串(不含换行)。 -- `len` / `str` / `int`:形参名均为 `value`(可位置传入)。 - - `len`:文本按 Unicode 标量计数;表/列表按元素数。 - - `str`:与 `print` 相同的显示规则。 - - `int`:`Int` 原样;`Bool` → 0/1;文本 trim 后按十进制解析,失败则诊断。 +| 英文 | 中文 | 用于 | +|------|------|------| +| `text` | `内容` | `print` / `打印` | +| `prompt` | `提示` | `input` / `输入` | +| `value` | `值` | `len`/`str`/`int` 及其中文名 | -旧文档中的中文 `print` **废弃**,统一为 `print`。 +```markdown +> print text=Hello +> 打印 内容=你好 + +*`n` = > 长度 值=`s`* +``` + +宿主原语 `type` / `trim` / `split` / `join` / `at` **无**内核中文别名;文本/表扩展走标准库文件(见 [stdlib-i18n.md](stdlib-i18n.md))。转换错误见 [stdlib.md](stdlib.md)。 --- @@ -62,30 +67,29 @@ ```markdown # main -> print text=Hello World! +> 打印 内容=Hello World! *`n` = 1* + `n` > 0 > print text=positive + * - > print text=other + > 打印 内容=other ``` -- `>` 是**调用标记**(架构)。 -- `print` 是**被调名字**(内置库)。 -- 用户自定义 `# print` 会遮蔽内置(实现应警告)。 +- `>` 是调用标记;`print` / `打印` 是同一内置的别名。 +- 用户 `# print` 或 `# 打印` 会遮蔽对应名字。 --- ## 5. 标识符规则(摘要) -- 变量:行内 `` `name` ``;`name` 不可为上表关键字。 -- 函数名:`#` 标题文本;建议 ASCII/英文,中文标题仍允许但内置名保持英文。 -- 比较:`==` `>` `<` `>=` `<=`;逻辑:`and` `or` `not`。 +- 变量:`` `name` ``;不可为上表任一中英文关键字。 +- 函数名:`#` 标题;中英文均可。 +- 比较:`==` `>` `<` `>=` `<=`;逻辑:`and`/`且`、`or`/`或`、`not`/`非`。 --- ## 6. 后续可增(未批准) -`float`、`type`、`range`;以及 `break`/`continue`(若循环需要)。增加前开短 ADR。 +`float`、`range`;以及 `break`/`continue`。增加前开短 ADR,并同步考虑是否值得占用双名配额。 diff --git a/doc/design/stdlib-i18n.md b/doc/design/stdlib-i18n.md new file mode 100644 index 0000000..0325211 --- /dev/null +++ b/doc/design/stdlib-i18n.md @@ -0,0 +1,134 @@ +# 标准库多语言命名(草案) + +| | | +|---|---| +| 状态 | **草案(先文档、后实现)** | +| 日期 | 2026-08-04 | +| 原则 | **不指定语言**;靠**库文件名**区分中英(及日后其它语言) | +| 相关 | [stdlib.md](stdlib.md) · [keywords.md](keywords.md) · [keywords-i18n.md](keywords-i18n.md) · [user-site.md](user-site.md) | + +--- + +## 1. 要解决什么 + +- 内置(解释器里的名字)必须**少而精**;更多能力放进可 `>` 导入的标准库。 +- 标准库需要**中英两套 API**(函数名不同),并方便以后再加日文、西班牙文等。 +- **不要**用 frontmatter `lang:`、环境变量默认语言、或「同一导入路径再解析语言」——那是负累,也不符合「文档即代码」的直观性。 + +--- + +## 2. 方案(采用) + +**导入哪个库文件,就用哪套函数名。** +文件名本身表达语言;解释器只做路径解析,不做语言推断。 + +### 2.1 推荐:库名用目标语言书写 + +| 导入 | 库内函数名(示例) | +|------|-------------------| +| `> lib/text.mq.md` | `trim` · `split` · `join` | +| `> lib/文本.mq.md` | `去空白` · `拆分` · `拼接` | +| `> lib/table.mq.md` | `rows` · `row_at` | +| `> lib/表.mq.md` | `行数` · `取行` | + +示例: + +```markdown +--- +> lib/text.mq.md +--- + +# main +*`xs` = > split value=a,b,c sep=,* +``` + +```markdown +--- +> lib/文本.mq.md +--- + +# main +*`xs` = > 拆分 s=a,b,c sep=,* +``` + +读者看到导入路径就能知道后面该用英文还是中文函数名——**无需再声明语言**。 + +### 2.2 可选:同概念用后缀区分(同目录、同「概念」) + +若希望「同一概念」在文件名上仍共享拉丁词根,可用: + +| 导入 | 含义 | +|------|------| +| `> lib/text-en.mq.md` | 英文 API | +| `> lib/text-zh.mq.md` | 中文 API | + +这与 §2.1 **等价可选**,不是第二套解析器:仍然是「写哪个路径就加载哪个文件」。 +**优先推荐 §2.1**(`text` / `文本`),后缀形式留给需要 ASCII-only 路径的环境。 + +### 2.3 明确不做 + +| 不做 | 原因 | +|------|------| +| `lang: zh` / `MARQDO_LANG` | 隐式状态,难读、难测 | +| `> std/text` 再按语言展开 | 多一次魔法 | +| 同一文件内中英函数双份导出 | 遮蔽与文档混乱 | +| 强制用户只许用中文或只许用英文 | Marqdo 本就多语言友好 | + +--- + +## 3. 与「少而精内置」的边界 + +| 层 | 内容 | 如何获得 | +|----|------|----------| +| **内置(L0)** | 极少:`print` `input` `len` `str` `int`(及语言字面量关键字) | 直接调用,无需导入 | +| **标准库(L1)** | 文本/表等扩展 API;**中英各一套文件、各一套函数名** | frontmatter `> lib/…` | +| **宿主原语(实现细节)** | 若 `trim`/`split` 等暂由解释器实现 | 仅供标准库包装调用;**文档与用户站引导走 L1**,不鼓励当「关键字」堆砌 | + +日后若某能力足够「核心」,可再升格为 L0;升格前先留在 L1。 + +--- + +## 4. 目录与扩展约定 + +```text +lib/ + text.mq.md # 英文文本库 + 文本.mq.md # 中文文本库 + table.mq.md # 英文表库 + 表.mq.md # 中文表库 + # 日后:texte.mq.md / テキスト.mq.md … +``` + +扩展新语言时: + +1. **新加一个库文件**(文件名用该语言或 `概念-xx`)。 +2. 库内函数名用该语言习惯。 +3. 文档表增加一行映射;**无需改解释器语言开关**。 + +导入解析仍沿用现有规则:相对路径 → 官方 `lib/` 根(`MARQDO_LIB` / 工作区 `lib/` 等),**不增加语言分支**。 + +--- + +## 5. 文档与示例义务 + +- 用户站:英文库、中文库各给一页(或同页两小节),导入路径与调用名并排出现。 +- 金样例:`tests/…` 中英导入至少各一条,避免只测中文或只测英文。 +- [keywords.md](keywords.md) 只列 L0;L1 指向本文 + [stdlib.md](stdlib.md)。 + +--- + +## 6. 实现备忘(暂不开发) + +实现阶段仅需: + +1. 落地 `lib/text.mq.md` 与 `lib/文本.mq.md`(及 table / 表)两套文件与函数名。 +2. 更新导入示例与金样例;删除「仅中文库名」的单轨示例。 +3. **不要**实现 `lang:`、默认语言、或 `std/text` 自动选语言。 + +若历史上加过 `Module.lang` / `lang:` 解析,应撤回,与本草案对齐。 + +--- + +## 7. 一句话 + +**标准库用文件名区分语言;英文库名进英文 API,中文库名进中文 API——导入即选择,无语言开关。** diff --git a/doc/design/stdlib.md b/doc/design/stdlib.md new file mode 100644 index 0000000..d8e00ca --- /dev/null +++ b/doc/design/stdlib.md @@ -0,0 +1,87 @@ +# 标准库(P2) + +| | | +|---|---| +| 状态 | **S0–S3 落地** | +| 日期 | 2026-08-04 | +| 相关 | [keywords.md](keywords.md) · [call-arguments.md](call-arguments.md) · [stdlib-i18n.md](stdlib-i18n.md) · [roadmap/next-phase.md](../roadmap/next-phase.md) | + +> **多语言库命名**已单独定稿方向:见 [stdlib-i18n.md](stdlib-i18n.md)。 +> 要点:不设 `lang:`;`lib/text.mq.md`(英文函数)与 `lib/文本.mq.md`(中文函数)分文件导入。下文 §3 的单轨中文示例将在实现阶段按该草案改掉。 + +--- + +## 1. 分层 + +| 层 | 内容 | +|----|------| +| **L0 内置** | 解释器内:`print` `input` `len` `str` `int` `type` `trim` `split` `join` `at` | +| **L1 官方库** | 仓库根目录 [`lib/`](../../lib/)(`.mq.md`);可用 `lib/…` 或别名 `std/…` 导入 | +| **L2** | catalog / 用户站收录(随发版) | + +--- + +## 2. 内置一览(S0 + S1) + +| 名 | 形参 | 结果 | +|----|------|------| +| `len` | `value` | 文本标量数或列表长度 | +| `str` | `value` | 显示文本 | +| `int` | `value` | 整数(失败 → 诊断) | +| `type` | `value` | `none`/`bool`/`int`/`text`/`list` | +| `trim` | `value` | 去首尾空白 | +| `split` | `value`, `sep` | 文本列表 | +| `join` | `value`, `sep` | 拼接文本 | +| `at` | `value`, `index` | 列表下标(越界 → `None`) | + +表(单列表格)在运行时是 `list`:行数用 `len`,取行用 `at`。 + +--- + +## 3. 官方库导入(S2) + +Frontmatter: + +```markdown +--- +> lib/text.mq.md +> lib/table.mq.md +--- +``` + +`std/text.mq.md` 等价于 `lib/text.mq.md`。解析顺序: + +1. 相对当前文件 +2. `MARQDO_LIB`(可指向 `lib` 目录或仓库根) +3. 当前工作目录的 `lib/` +4. 可执行文件附近的 `lib/`(含 `cargo run` 的相对路径) + +当前模块: + +| 路径 | 导出函数 | +|------|----------| +| `lib/text.mq.md` | `去空白` `拆分` `拼接` | +| `lib/table.mq.md` | `行数` `取行` | + +--- + +## 4. 转换错误约定(S3) + +用户可见失败统一为: + +```text +path:line:col: message +``` + +内置转换相关文案(稳定子集,金样例断言): + +| 情况 | message | +|------|---------| +| 非法整数文本 | `cannot convert to int: "…"` | +| `int` 类型不对 | `int needs int, bool, or text` | +| `len` 类型不对 | `len needs text or list` | +| `trim` 非文本 | `trim needs text` | +| `split`/`join` 参数类型 | `split needs text value` 等 | +| 空分隔符 | `split sep must not be empty` | + +不引入独立异常类型对象;一律走 `Diagnostic`。 diff --git a/doc/design/user-site.md b/doc/design/user-site.md index f879ab6..ada21fb 100644 --- a/doc/design/user-site.md +++ b/doc/design/user-site.md @@ -13,7 +13,7 @@ | 路径 | 是否入库 | 职责 | |------|----------|------| | `doc/` | 是 | 开发者设计 / ADR / 路线图(单数 `doc`,勿再造 `docs/`) | -| `public/**/*.mq.md` | 是 | 用户可读、可执行、可下载的介绍(结构 / 关键字 / 特性迭代) | +| `public/**/*.mq.md` | 是 | 用户可读、可执行、可下载的介绍(结构 / 关键字 / 特性迭代);**双语**:拉丁文件名 = 英文,中文文件名 = 中文编程,同目录并列 | | `public/index.html`、`public/pages/` | **否**(ignore) | `marqdo view output` 生成的 HTML | | `tests/{structure,keywords,errors}/` | 是 | 金样例与失败夹具(含 errors) | | 远程分支 `gh-pages` | 发布产物 | 发布整个 `public/`(源文件 + 生成 HTML) | diff --git a/doc/roadmap/next-phase.md b/doc/roadmap/next-phase.md index cf6b851..86a7dce 100644 --- a/doc/roadmap/next-phase.md +++ b/doc/roadmap/next-phase.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **进行中**(P0–P1b / P2-S0 / P3-D0–D1 初版;下一:P3-D2 或 P2-S1) | +| 状态 | **进行中**(P2 完成;下一:P3-D2 调试会话) | | 日期 | 2026-08-04 | | 目标 | 交互 I/O、可信诊断、可生长标准库;view 渐进成为调试宿主 | | 相关 | [interpreter.md](interpreter.md) · [keywords.md](../design/keywords.md) · [pipeline-debug.md](../design/pipeline-debug.md) · [view.md](../design/view.md) | @@ -14,10 +14,10 @@ | 能力 | 现状 | 结论 | |------|------|------| | **`print`** | 树遍历 + 字节码均可用 | 够用 | -| **`input`** | CLI 双后端 + `--stdin-file`;live view 预置输入表单;无队列时 capture 仍拒绝 | **P1a + P1b 完成** | +| **`input`** | CLI 双后端 + `--stdin-file`;frontmatter `stdin:`/`输入:`;live view 表单覆盖;无预置时 capture 提示补线 | **P1a + P1b 完成** | | **诊断** | 语句级 `path:line:col: message`;字节码指令带 `spans`;errors 金样例双后端断言位置 | **P0 完成** | | **view** | 结构 + 一次执行 + 源码;注释已 Markdown 渲染;无暂停/断点 | **文档浏览器,不是调试器** | -| **标准库** | S0:`len` / `str` / `int` 双后端可用;尚无官方 `lib/` | **P2-S0 完成** | +| **标准库** | S0–S3:`len`/`str`/`int`/`type`/`trim`/`split`/`join`/`at` + 官方 `lib/` | **P2 完成** | | **模块** | `> file.mq.md` 顶层函数合并,无命名空间 | 短期可继续用 | 用户点名的三件事都对,但**不能并行硬开**:断点调试依赖「可信位置 + 可暂停执行」;标准库依赖稳定运行时与 I/O;`input` 在 CLI 与 view 是两条路径。 diff --git a/lib/table.mq.md b/lib/table.mq.md new file mode 100644 index 0000000..1b6a8f1 --- /dev/null +++ b/lib/table.mq.md @@ -0,0 +1,15 @@ +--- +title: lib/table +description: English table helpers over len / at +--- + +# rows + - xs + +**> len `xs`** + +# row_at + - xs + - i + +**> at value=`xs` index=`i`** diff --git a/lib/text.mq.md b/lib/text.mq.md new file mode 100644 index 0000000..07e66ac --- /dev/null +++ b/lib/text.mq.md @@ -0,0 +1,21 @@ +--- +title: lib/text +description: English text helpers over trim / split / join +--- + +# str_trim + - s + +**> trim `s`** + +# str_split + - s + - sep + +**> split value=`s` sep=`sep`** + +# str_join + - xs + - sep + +**> join value=`xs` sep=`sep`** diff --git a/lib/文本.mq.md b/lib/文本.mq.md new file mode 100644 index 0000000..cd3f7cf --- /dev/null +++ b/lib/文本.mq.md @@ -0,0 +1,21 @@ +--- +title: lib/文本 +description: 中文文本库:去空白 / 拆分 / 拼接 +--- + +# 去空白 + - s + +**> trim `s`** + +# 拆分 + - s + - sep + +**> split value=`s` sep=`sep`** + +# 拼接 + - xs + - sep + +**> join value=`xs` sep=`sep`** diff --git a/lib/表.mq.md b/lib/表.mq.md new file mode 100644 index 0000000..47bdc19 --- /dev/null +++ b/lib/表.mq.md @@ -0,0 +1,15 @@ +--- +title: lib/表 +description: 中文表库:行数 / 取行 +--- + +# 行数 + - xs + +**> len `xs`** + +# 取行 + - xs + - i + +**> at value=`xs` index=`i`** diff --git a/public/00-welcome.mq.md b/public/00-welcome.mq.md index c87dfa2..cd99688 100644 --- a/public/00-welcome.mq.md +++ b/public/00-welcome.mq.md @@ -1,31 +1,27 @@ --- -title: 欢迎使用 Marqdo -description: 用户文档首页 — 代码即文档 +title: Welcome to Marqdo +description: User docs home — code is documentation --- # main -阅读到这里的朋友你好!我是marqdo的开发者,很高兴你看到这个网站,marqdo是一个代码即文档的编程语言,作者想要做这个项目来源于一个小小的想法,AI输出的首选语言是markdown,为什么不能基于markdown创建一个新式的编程语言,不再区分文档和代码,代码写出来就是一份文档,文档也是代码(这个项目的野心实际更大些,项目立项之处就调研了谷歌OKF规范,计划自动生成YAML使得代码和文档能够自动的变成知识库,与此同时还有更多可能,例如规范化生成的PPT)。 +Hi — thanks for opening this site. Marqdo is a language where **code is documentation**: Markdown markers are the program structure, so what you read is what runs. -所以marqdo产生了,为了确保我们的新语言能够百分百被markdown渲染,这门语言甚至采用了`.mq.md`的双层嵌套后缀,所以不需要有压力使用这门语言,就算出现了巨大的问题,就当让ai写文档好了,如果成功了,试想这样一种场景,你不再需要让ai生成代码的文档,ai写的代码能够便捷的被你读懂,至少能省点token,毕竟烧了太多,钱包容易饿瘦。 +AI already prefers Markdown. Marqdo asks: why keep docs and code as two worlds? A `.mq.md` file is both. The longer ambition includes OKF-style knowledge YAML and more; for now the focus is a solid interpreter and this site (yes — generated by Marqdo itself). -这门语言还是起步阶段,目前计划是制作一个解释型的语言,现在的marqdo支持一些特定的语法结构和关键字,并且允许自由的输出调试信息,以及直接通过前端预览各个代码块,生成静态文件,是的,没错,这个网站就是marqdo制作的,至少我相信marqdo会成为一个博客工具。 +The language is young. You get structure markers, a small bilingual core (`print` / `打印`, …), optional stdlib files (`lib/text.mq.md` vs `lib/文本.mq.md`), local `view`, and static export. Contribute on [GitHub](https://github.com/cflmy/marqdo). -除了部分内置的关键字,marqdo并不限制必须使用英文编程,当然这并不意味着我要开发一个中文编程系统,事实上,这是由于文档即代码、代码即文档的结构决定的,如果只支持英文,那还有什么作用?还要掌握一门语言,这并不是让人愉悦的阅读体验,所以marqdo会长期支持多语言编程的可能。 +中文文档请看同目录的 [`00-欢迎.mq.md`](00-欢迎.mq.md)(叙述与内置均用中文)。 -欢迎各位加入开源库,共同建设和完成这个项目[marqdo的github仓库链接](https://github.com/cflmy/marqdo) +A classic hello via a small function: -最后,引用所有程序员的开始欢迎各位: +> greet who=marqdo -> 问候 marqdo +Named args allow spaces in values: -如果你是一个敏锐的程序员应该会察觉到一个小问题,这个问题的解决方案是像下面这样的,目前来看这样的解决方案没有问题,我并不能很有远见的判断后续一定不会出错,所以我暂且放在这里,欢迎你,敏锐的程序员朋友。 +> greet who=marqdo user -> 问候 谁=marqdo user +## greet + - who -## 问候 - - 谁 - -> print text=欢迎,`谁`! - ---- +> print text=Welcome, `who`! diff --git a/public/00-欢迎.mq.md b/public/00-欢迎.mq.md new file mode 100644 index 0000000..54caf97 --- /dev/null +++ b/public/00-欢迎.mq.md @@ -0,0 +1,27 @@ +--- +title: 欢迎使用 Marqdo +description: 用户文档首页 — 代码即文档(中文版) +--- + +# main + +阅读到这里的朋友你好!我是 Marqdo 的开发者。Marqdo 是一门**代码即文档**的语言:Markdown 标记就是程序结构,你读到的就是能跑的程序。 + +AI 输出本就偏爱 Markdown。作者的念头是:何必再把文档和代码拆成两套?`.mq.md` 双后缀保证它仍是合法 Markdown。更长远的目标包括 OKF 式知识清单等;眼下先把解释器与本站做好——对,这个站点就是 Marqdo 生成的。 + +语言仍在起步:结构标记、中英内核双名(`打印` / `print` …)、可导入的标准库(`lib/文本.mq.md` 与 `lib/text.mq.md`)、本地 `view` 与静态导出。欢迎到 [GitHub](https://github.com/cflmy/marqdo) 一起做。 + +English docs: [`00-welcome.mq.md`](00-welcome.mq.md) (English prose and English builtins). + +用一个小函数打个招呼: + +> 问候 谁=marqdo + +具名实参可以带空格: + +> 问候 谁=marqdo user + +## 问候 + - 谁 + +> 打印 内容=欢迎,`谁`! diff --git a/public/README.md b/public/README.md index b5721f2..5a2bd7b 100644 --- a/public/README.md +++ b/public/README.md @@ -1,13 +1,16 @@ -# 用户文档(可执行 · 可下载) +# 用户文档(可执行 · 可下载 · 中英双语) 本目录即面向访客的 Marqdo 介绍:每个 `.mq.md` 既是文稿也能 `marqdo run`,并随仓库 / 静态站一起下载。 +**双语约定:** 拉丁文件名 → 英文叙述与英文内置;中文文件名 → 中文叙述与中文编程(`打印`、`长度` …)。成对放在同一目录(如 `structure/01-hello.mq.md` 与 `structure/01-你好.mq.md`)。标准库按路径选 API:`lib/text.mq.md` vs `lib/文本.mq.md`。 + | 路径 | 内容 | |------|------| -| [`00-welcome.mq.md`](00-welcome.mq.md) | 首页 | -| [`structure/`](structure/) | 基本结构 | -| [`keywords/`](keywords/) | 关键字与内置 `print` | -| [`features/`](features/) | 特性迭代说明 | +| [`00-welcome.mq.md`](00-welcome.mq.md) / [`00-欢迎.mq.md`](00-欢迎.mq.md) | 首页(英 / 中) | +| [`structure/`](structure/) | 基本结构(英 / 中并列) | +| [`keywords/`](keywords/) | 关键字与内置(英 / 中并列) | +| [`features/`](features/) | 特性迭代(英 / 中并列) | +| [`lib-import.mq.md`](lib-import.mq.md) / [`lib-导入.mq.md`](lib-导入.mq.md) | 导入 `lib/text` / `lib/文本` | **不放** `errors/`:失败样例只在 `tests/errors/`,避免用户站出现红色执行失败。 diff --git a/public/features/01-phase-i-treewalk.mq.md b/public/features/01-phase-i-treewalk.mq.md index be80a61..50f4397 100644 --- a/public/features/01-phase-i-treewalk.mq.md +++ b/public/features/01-phase-i-treewalk.mq.md @@ -1,14 +1,14 @@ --- -title: Phase I — 树遍历解释器 -description: 词法 · 语法 · 语义 · 树遍历已贯通 +title: Phase I — tree-walk interpreter +description: Lex · parse · check · tree-walk end to end --- # main -里程碑:Phase I(树遍历)。 +Milestone: Phase I (tree-walk). -流水线:加载 → 行分类 → 递归下降语法 → 语义检查 → 树遍历执行。实现不用 Flex/Bison。 +Pipeline: load → line classify → recursive-descent parse → semantic check → tree-walk eval. No Flex/Bison. -本页本身即可运行,证明「文档即程序」在解释器里已落地: +This page runs as a program — documentation is executable: -> print text=Phase I:tree-walk interpreter is live. +> print text=Phase I: tree-walk interpreter is live. diff --git a/public/features/01-树遍历.mq.md b/public/features/01-树遍历.mq.md new file mode 100644 index 0000000..2e69b6c --- /dev/null +++ b/public/features/01-树遍历.mq.md @@ -0,0 +1,14 @@ +--- +title: 第一阶段 — 树遍历解释器 +description: 词法 · 语法 · 语义 · 树遍历已贯通 +--- + +# main + +里程碑:第一阶段(树遍历)。 + +流水线:加载 → 行分类 → 递归下降语法 → 语义检查 → 树遍历执行。实现不用 Flex/Bison。 + +本页本身即可运行,证明「文档即程序」已落地: + +> 打印 内容=第一阶段:树遍历解释器已就绪。 diff --git a/public/features/02-bytecode.mq.md b/public/features/02-bytecode.mq.md index b6d178d..79a404a 100644 --- a/public/features/02-bytecode.mq.md +++ b/public/features/02-bytecode.mq.md @@ -1,18 +1,18 @@ --- -title: 字节码后端 -description: --backend bytecode 与树遍历共用语义 +title: Bytecode backend +description: `--backend bytecode` shares semantics with tree-walk --- # main -里程碑:字节码原型。 +Milestone: bytecode prototype. -同一套 .mq.md 可用树遍历或字节码 VM 执行。命令示例: +The same `.mq.md` runs on tree-walk or the bytecode VM: marqdo run FILE --backend tree marqdo run FILE --backend bytecode -下面这段在两种后端下输出一致: +Output matches on both backends: -> print text=Bytecode backend:same program, alternate engine. +> print text=Bytecode backend: same program, alternate engine. diff --git a/public/features/02-字节码.mq.md b/public/features/02-字节码.mq.md new file mode 100644 index 0000000..50e3b33 --- /dev/null +++ b/public/features/02-字节码.mq.md @@ -0,0 +1,18 @@ +--- +title: 字节码后端 +description: `--backend bytecode` 与树遍历共用语义 +--- + +# main + +里程碑:字节码原型。 + +同一套 `.mq.md` 可用树遍历或字节码 VM: + + marqdo run FILE --backend tree + + marqdo run FILE --backend bytecode + +两种后端输出一致: + +> 打印 内容=字节码后端:同一程序,另一引擎。 diff --git a/public/features/03-view-and-docs.mq.md b/public/features/03-view-and-docs.mq.md index 6fa24d7..ba6e46f 100644 --- a/public/features/03-view-and-docs.mq.md +++ b/public/features/03-view-and-docs.mq.md @@ -1,16 +1,16 @@ --- -title: view 与用户文档站 -description: 本地浏览与静态导出由解释器生成 +title: view and the user docs site +description: Local browse and static export from the interpreter --- # main -里程碑:marqdo view 与 view output。 +Milestone: `marqdo view` and `view output`. -本地浏览:marqdo view public +Local: `marqdo view public` -静态导出:marqdo view output public -o public +Static export: `marqdo view output public -o public` -用户可执行文档就在 public/;生成的 HTML(index.html / pages/)供静态托管,CI 发布到 gh-pages。 +Executable user docs live under `public/`. Generated HTML (`index.html` / `pages/`) is for hosting; CI publishes to `gh-pages`. -> print text=Docs site:generated by the Marqdo interpreter, not hand-written HTML. +> print text=Docs site: generated by the Marqdo interpreter, not hand-written HTML. diff --git a/public/features/03-view与文档.mq.md b/public/features/03-view与文档.mq.md new file mode 100644 index 0000000..33c9fc7 --- /dev/null +++ b/public/features/03-view与文档.mq.md @@ -0,0 +1,16 @@ +--- +title: view 与用户文档站 +description: 本地浏览与静态导出由解释器生成 +--- + +# main + +里程碑:`marqdo view` 与 `view output`。 + +本地浏览:`marqdo view public` + +静态导出:`marqdo view output public -o public` + +用户可执行文档在 `public/`;生成的 HTML(`index.html` / `pages/`)供静态托管,CI 发布到 `gh-pages`。 + +> 打印 内容=文档站:由 Marqdo 解释器生成,不是手写 HTML。 diff --git a/public/keywords/bool-logic.mq.md b/public/keywords/bool-logic.mq.md index a6b21a8..276a126 100644 --- a/public/keywords/bool-logic.mq.md +++ b/public/keywords/bool-logic.mq.md @@ -1,11 +1,11 @@ --- -title: 布尔与逻辑 -description: True / False / None 与 and / or / not +title: Booleans and logic +description: True / False / None and and / or / not --- # main -关键字:`True`、`False`、`None`,以及 `and` / `or` / `not`。 +Keywords: `True`, `False`, `None`, and `and` / `or` / `not`. *`a` = True* *`b` = False* diff --git a/public/keywords/input.mq.md b/public/keywords/input.mq.md index 65227a4..efcaa2b 100644 --- a/public/keywords/input.mq.md +++ b/public/keywords/input.mq.md @@ -1,11 +1,12 @@ --- -title: 内置 input -description: 从 stdin 读一行;可选 prompt。可用 --stdin-file 或 live view 预置输入。 +title: Built-in input +description: Read one line from stdin; optional prompt. Demo via frontmatter stdin. +stdin: Ada --- # main -CLI 可用管道或 --stdin-file 喂入一行;live marqdo view 在 Execution 区可填预置输入后重跑。静态站点默认无 stdin,会看到 capture 提示。 +The input builtin reads one line. For demos and marqdo view / static export, put sample lines in frontmatter (stdin:). CLI can also use a pipe or --stdin-file. Live view can override with the Preset input box. *`name` = > input prompt=Name: * diff --git a/public/keywords/print.mq.md b/public/keywords/print.mq.md index 0d28005..8ce7708 100644 --- a/public/keywords/print.mq.md +++ b/public/keywords/print.mq.md @@ -1,14 +1,14 @@ --- -title: 内置 print -description: 具名与位置两种写法 +title: Built-in print +description: Named and positional forms --- # main -内置 print 接受具名或位置实参: +The `print` builtin accepts named or positional arguments: > print text=named form > print positional -这里的设计思路是具名实参允许空格的传入,位置实参则不允许。 \ No newline at end of file +Named args may contain spaces; positional args may not. diff --git a/public/keywords/stdlib.mq.md b/public/keywords/stdlib.mq.md index 17688a6..812388d 100644 --- a/public/keywords/stdlib.mq.md +++ b/public/keywords/stdlib.mq.md @@ -1,11 +1,11 @@ --- -title: 内置 len / str / int -description: 长度与类型转换(S0 最小标准库) +title: Built-ins len / str / int / type / trim / split / join / at +description: Host builtins for strings and tables --- # main -len 接受文本(按 Unicode 标量计)或表/列表: +Length and type: *`s` = hello* @@ -13,10 +13,22 @@ len 接受文本(按 Unicode 标量计)或表/列表: > print text=`n` -str 把值转成显示文本;int 解析整数(或把 True / False 当成 1 / 0): +*`ty` = > type `s`* -*`t` = > str 7* +> print text=`ty` -*`i` = > int `t`* +Trim, split, join, and index: -> print text=`i` +*`t` = > trim value= hi * + +*`parts` = > split value=a,b sep=,* + +*`mid` = > at value=`parts` index=0* + +*`j` = > join value=`parts` sep=-* + +> print text=`t` + +> print text=`mid` + +> print text=`j` diff --git a/public/keywords/内核双名.mq.md b/public/keywords/内核双名.mq.md new file mode 100644 index 0000000..1d165c3 --- /dev/null +++ b/public/keywords/内核双名.mq.md @@ -0,0 +1,16 @@ +--- +title: 中英内核双名 +description: 无需导入:打印、长度、文本、整数 与 print / len / … +--- + +# main + +内核中英别名等价,可混用: + +*`s` = 你好* + +*`n` = > 长度 值=`s`* + +> 打印 内容=`n` + +> print text=also-english diff --git a/public/keywords/布尔逻辑.mq.md b/public/keywords/布尔逻辑.mq.md new file mode 100644 index 0000000..9211cc2 --- /dev/null +++ b/public/keywords/布尔逻辑.mq.md @@ -0,0 +1,23 @@ +--- +title: 布尔与逻辑 +description: 真 / 假 / 空 与 且 / 或 / 非 +--- + +# main + +关键字:`真`、`假`、`空`,以及 `且` / `或` / `非`。 + +*`a` = 真* +*`b` = 假* + ++ `a` 且 非 `b` + > 打印 内容=通过 ++ * + > 打印 内容=失败 + +*`probe` = 1* + ++ 空 + > 打印 内容=空为真 ++ * + > 打印 内容=空为假 diff --git a/public/keywords/打印.mq.md b/public/keywords/打印.mq.md new file mode 100644 index 0000000..07391e6 --- /dev/null +++ b/public/keywords/打印.mq.md @@ -0,0 +1,14 @@ +--- +title: 内置 打印 +description: 具名与位置两种写法 +--- + +# main + +内置 `打印` 接受具名或位置实参: + +> 打印 内容=具名写法 + +> 打印 位置写法 + +具名实参可以带空格;位置实参不可以。 diff --git a/public/keywords/标准库.mq.md b/public/keywords/标准库.mq.md new file mode 100644 index 0000000..bbfc988 --- /dev/null +++ b/public/keywords/标准库.mq.md @@ -0,0 +1,34 @@ +--- +title: 内置 长度 / 文本 / 整数 与 trim 等 +description: 主机内置;中文别名覆盖常用几个 +--- + +# main + +长度与英文 `type`(类型无中文内核别名,见标准库文档): + +*`s` = 你好* + +*`n` = > 长度 值=`s`* + +> 打印 内容=`n` + +*`ty` = > type `s`* + +> 打印 内容=`ty` + +去空白、拆分、拼接、按下标(主机名仍为英文): + +*`t` = > trim value= 嗨 * + +*`parts` = > split value=甲,乙 sep=,* + +*`mid` = > at value=`parts` index=0* + +*`j` = > join value=`parts` sep=-* + +> 打印 内容=`t` + +> 打印 内容=`mid` + +> 打印 内容=`j` diff --git a/public/keywords/输入.mq.md b/public/keywords/输入.mq.md new file mode 100644 index 0000000..bde7604 --- /dev/null +++ b/public/keywords/输入.mq.md @@ -0,0 +1,13 @@ +--- +title: 内置 输入 +description: 从 stdin 读一行;可选提示。演示数据写在 frontmatter 输入。 +输入: 小明 +--- + +# main + +内置「输入」读一行。演示与 marqdo view / 静态导出可在 frontmatter 写「输入:」(或 stdin:)。CLI 也可用管道或 --stdin-file。Live view 可用 Preset input 覆盖。 + +*`名字` = > 输入 提示=名字: * + +> 打印 内容=你好 `名字`! diff --git a/public/lib-import.mq.md b/public/lib-import.mq.md new file mode 100644 index 0000000..32c31b8 --- /dev/null +++ b/public/lib-import.mq.md @@ -0,0 +1,13 @@ +--- +title: Import official lib +description: Frontmatter `lib/…` or `std/…` +> lib/text.mq.md +--- + +# main + +After importing `lib/text.mq.md`, call the English wrappers: + +*`t` = > str_trim s= marqdo * + +> print text=`t` diff --git a/public/lib-导入.mq.md b/public/lib-导入.mq.md new file mode 100644 index 0000000..ae21ef3 --- /dev/null +++ b/public/lib-导入.mq.md @@ -0,0 +1,13 @@ +--- +title: 导入官方库 +description: frontmatter 使用 lib/… 或 std/… +> lib/文本.mq.md +--- + +# main + +导入 `lib/文本.mq.md` 后可调用中文包装函数: + +*`t` = > 去空白 s= marqdo * + +> 打印 内容=`t` diff --git a/public/structure/01-hello.mq.md b/public/structure/01-hello.mq.md index 0cbd2ce..701da23 100644 --- a/public/structure/01-hello.mq.md +++ b/public/structure/01-hello.mq.md @@ -1,12 +1,12 @@ --- title: Hello World -description: 最简单的可执行文档 +description: Smallest runnable doc --- # main -普通段落是注释。print 是内置函数,不是语法架构。 +Ordinary paragraphs are comments. `print` is a built-in, not a syntax marker. -注释里的粗体与斜体标记若出现在行首会被当成代码,所以叙述行请用普通文字开头。 +Lines that start with Markdown emphasis markers can be treated as code — keep narrative as plain prose. > print text=Hello World! diff --git a/public/structure/01-你好.mq.md b/public/structure/01-你好.mq.md new file mode 100644 index 0000000..260e089 --- /dev/null +++ b/public/structure/01-你好.mq.md @@ -0,0 +1,12 @@ +--- +title: 你好世界 +description: 最小可运行文档 +--- + +# main + +普通段落是注释。`打印` 是内置函数,不是语法标记。 + +以 Markdown 强调标记开头的行可当作代码——叙述请用普通段落。 + +> 打印 内容=你好世界! diff --git a/public/structure/02-function.mq.md b/public/structure/02-function.mq.md index f65e905..9188bc6 100644 --- a/public/structure/02-function.mq.md +++ b/public/structure/02-function.mq.md @@ -1,17 +1,17 @@ --- -title: 函数与具名调用 -description: `#` 定义函数,`>` 调用;`-` 下列纯名为形参 +title: Functions and named calls +description: `#` defines functions; `>` calls; `-` lists parameter names --- # main -用 `#` / `##` 定义函数。形参写在函数头下方的 `-` 纯名行。 +Use `#` / `##` for functions. Parameters are bare `- name` lines under the heading. -调用用 `>`:具名实参写作 `形参=值`。 +Call with `>` and named args `param=value`: -> 问候 谁=World +> greet who=World -## 问候 - - 谁 +## greet + - who -> print text=Hello `谁`! +> print text=Hello `who`! diff --git a/public/structure/02-函数.mq.md b/public/structure/02-函数.mq.md new file mode 100644 index 0000000..973a605 --- /dev/null +++ b/public/structure/02-函数.mq.md @@ -0,0 +1,17 @@ +--- +title: 函数与具名调用 +description: `#` 定义函数;`>` 调用;`-` 列出参数名 +--- + +# main + +用 `#` / `##` 定义函数。参数是标题下的裸 `- 名` 行。 + +用 `>` 与具名实参 `参数=值` 调用: + +> 问候 谁=世界 + +## 问候 + - 谁 + +> 打印 内容=你好 `谁`! diff --git a/public/structure/03-positional-call.mq.md b/public/structure/03-positional-call.mq.md index fcac923..77bec9c 100644 --- a/public/structure/03-positional-call.mq.md +++ b/public/structure/03-positional-call.mq.md @@ -1,19 +1,19 @@ --- -title: 位置实参 -description: 按形参顺序传参;也可继续用具名 +title: Positional arguments +description: Bind by parameter order; named form still works --- # main -位置实参:按形参声明顺序绑定,不必写 `谁=`。 +Positional args bind in declaration order (no `who=` needed): -> 问候 Marqdo +> greet Marqdo -具名形式仍然可用: +Named form still works: -> 问候 谁=World +> greet who=World -## 问候 - - 谁 +## greet + - who -> print text=Hello `谁`! +> print text=Hello `who`! diff --git a/public/structure/03-位置调用.mq.md b/public/structure/03-位置调用.mq.md new file mode 100644 index 0000000..4cb94ff --- /dev/null +++ b/public/structure/03-位置调用.mq.md @@ -0,0 +1,19 @@ +--- +title: 位置实参 +description: 按参数声明顺序绑定;具名写法仍然可用 +--- + +# main + +位置实参按声明顺序绑定(不必写 `谁=`): + +> 问候 Marqdo + +具名写法仍然可用: + +> 问候 谁=世界 + +## 问候 + - 谁 + +> 打印 内容=你好 `谁`! diff --git a/public/structure/04-branch.mq.md b/public/structure/04-branch.mq.md index 4f590cb..4f5d797 100644 --- a/public/structure/04-branch.mq.md +++ b/public/structure/04-branch.mq.md @@ -1,17 +1,17 @@ --- -title: 分支 -description: `+` 臂;整行 `*` 为 else +title: Branch +description: `+` arms; a lone `*` arm is else --- # main -斜体行是程序语句。分支用 `+`;臂头单独一行 `*` 表示 else。 +Italic lines are statements. Branches use `+`; a head that is only `*` is the else arm. *`x` = 0* + `x` > 0 - > print text=正数 + > print text=positive + `x` < 0 - > print text=负数 + > print text=negative + * - > print text=零 + > print text=zero diff --git a/public/structure/04-分支.mq.md b/public/structure/04-分支.mq.md new file mode 100644 index 0000000..d1504fa --- /dev/null +++ b/public/structure/04-分支.mq.md @@ -0,0 +1,17 @@ +--- +title: 分支 +description: `+` 各臂;单独的 `*` 臂为否则 +--- + +# main + +斜体行是语句。分支用 `+`;表头仅为 `*` 的是否则臂。 + +*`x` = 0* + ++ `x` > 0 + > 打印 内容=正数 ++ `x` < 0 + > 打印 内容=负数 ++ * + > 打印 内容=零 diff --git a/public/structure/05-loop.mq.md b/public/structure/05-loop.mq.md index 461b5ba..5541d9a 100644 --- a/public/structure/05-loop.mq.md +++ b/public/structure/05-loop.mq.md @@ -1,13 +1,13 @@ --- -title: 循环 -description: 条件循环与表格遍历 +title: Loops +description: Condition loops and table walks --- # main -函数体内的 `-` 是循环(不是形参)。 +Inside a function body, `-` starts a loop (not a parameter). -倒数: +Countdown: *`n` = 3* @@ -15,14 +15,14 @@ description: 条件循环与表格遍历 > print text=`n` *`n` = `n` - 1* -遍历篮子(表格是集合): +Walk a table (tables are collections): -`篮子` = +`basket` = -| 果 | -|----| -| 苹果 | -| 梨 | +| fruit | +|-------| +| apple | +| pear | -- [果](篮子) - > print text=今天吃`果` +- [fruit](basket) + > print text=today `fruit` diff --git a/public/structure/05-循环.mq.md b/public/structure/05-循环.mq.md new file mode 100644 index 0000000..c8fac8a --- /dev/null +++ b/public/structure/05-循环.mq.md @@ -0,0 +1,28 @@ +--- +title: 循环 +description: 条件循环与表遍历 +--- + +# main + +在函数体里,`-` 表示循环(不是参数)。 + +倒数: + +*`n` = 3* + +- `n` > 0 + > 打印 内容=`n` + *`n` = `n` - 1* + +遍历表(表即集合): + +`篮子` = + +| 水果 | +|------| +| 苹果 | +| 梨 | + +- [水果](篮子) + > 打印 内容=今天 `水果` diff --git a/public/structure/06-collection.mq.md b/public/structure/06-collection.mq.md index 9ac93be..d732be2 100644 --- a/public/structure/06-collection.mq.md +++ b/public/structure/06-collection.mq.md @@ -1,19 +1,19 @@ --- -title: 集合(表格) -description: GFM 表格即集合 +title: Collections (tables) +description: GFM tables are collections --- # main -Markdown 表格在 Marqdo 里就是集合,可用循环逐行取出。 +A Markdown table is a collection; loop to read each row. -`篮子` = +`basket` = -| 果 | -|----| -| 苹果 | -| 梨 | -| 桃 | +| fruit | +|-------| +| apple | +| pear | +| peach | -- [果](篮子) - > print text=`果` +- [fruit](basket) + > print text=`fruit` diff --git a/public/structure/06-集合.mq.md b/public/structure/06-集合.mq.md new file mode 100644 index 0000000..5686d81 --- /dev/null +++ b/public/structure/06-集合.mq.md @@ -0,0 +1,19 @@ +--- +title: 集合(表) +description: GFM 表格即集合 +--- + +# main + +Markdown 表是集合;用循环读每一行。 + +`篮子` = + +| 水果 | +|------| +| 苹果 | +| 梨 | +| 桃 | + +- [水果](篮子) + > 打印 内容=`水果` diff --git a/public/structure/import/main.mq.md b/public/structure/import/main.mq.md index 19a0051..836d0c8 100644 --- a/public/structure/import/main.mq.md +++ b/public/structure/import/main.mq.md @@ -1,17 +1,17 @@ --- -title: 跨文件导入 -description: frontmatter 中 `> 文件.mq.md` 导入模块 +title: Cross-file import +description: Frontmatter `> file.mq.md` merges modules > utils.mq.md --- # main -文件头 YAML 里写 `> utils.mq.md` 即可导入同目录模块。 +In the YAML header, `> utils.mq.md` imports a sibling module. -导入后:用返回值绑定,再输出;并直接调用问候。 +Bind a return value, print it, then call greet: -*`y` = > 加一 n=41* +*`y` = > add_one n=41* > print text=`y` -> 问候 谁=Marqdo +> greet who=Marqdo diff --git a/public/structure/import/utils.mq.md b/public/structure/import/utils.mq.md index 6fdedd0..91d02a9 100644 --- a/public/structure/import/utils.mq.md +++ b/public/structure/import/utils.mq.md @@ -1,14 +1,14 @@ --- -title: 工具模块 -description: 被 main 导入;粗体是返回值 +title: Utility module +description: Imported by main; bold is a return value --- -# 加一 +# add_one - n **`n` + 1** -# 问候 - - 谁 +# greet + - who -> print text=你好,`谁`! +> print text=Hello, `who`! diff --git a/public/structure/import/主.mq.md b/public/structure/import/主.mq.md new file mode 100644 index 0000000..87fd7dd --- /dev/null +++ b/public/structure/import/主.mq.md @@ -0,0 +1,17 @@ +--- +title: 跨文件导入 +description: frontmatter 中 `> 文件.mq.md` 合并模块 +> 工具.mq.md +--- + +# main + +在 YAML 头里写 `> 工具.mq.md` 可导入同级模块。 + +绑定返回值、打印,再调用问候: + +*`y` = > 加一 n=41* + +> 打印 内容=`y` + +> 问候 谁=Marqdo diff --git a/public/structure/import/工具.mq.md b/public/structure/import/工具.mq.md new file mode 100644 index 0000000..45ff898 --- /dev/null +++ b/public/structure/import/工具.mq.md @@ -0,0 +1,14 @@ +--- +title: 工具模块 +description: 被 main 导入;粗体为返回值 +--- + +# 加一 + - n + +**`n` + 1** + +# 问候 + - 谁 + +> 打印 内容=你好,`谁`! diff --git a/src/aliases.rs b/src/aliases.rs new file mode 100644 index 0000000..b733b1d --- /dev/null +++ b/src/aliases.rs @@ -0,0 +1,89 @@ +//! Canonical names and Chinese aliases for L0 keywords / builtins / params. +//! +//! See `doc/design/keywords-i18n.md`. No language mode — aliases are equivalent. + +/// Map a literal / logic keyword to its English canonical form, if reserved. +pub fn canonical_keyword(name: &str) -> Option<&'static str> { + match name { + "True" | "真" => Some("True"), + "False" | "假" => Some("False"), + "None" | "空" => Some("None"), + "and" | "且" => Some("and"), + "or" | "或" => Some("or"), + "not" | "非" => Some("not"), + _ => None, + } +} + +pub fn is_reserved_keyword(name: &str) -> bool { + canonical_keyword(name).is_some() +} + +/// Map a builtin callee (EN or ZH alias) to its English canonical name. +/// Host primitives without ZH L0 aliases only match English. +pub fn canonical_builtin(name: &str) -> Option<&'static str> { + match name { + "print" | "打印" => Some("print"), + "input" | "输入" => Some("input"), + "len" | "长度" => Some("len"), + "str" | "文本" => Some("str"), + "int" | "整数" => Some("int"), + "type" => Some("type"), + "trim" => Some("trim"), + "split" => Some("split"), + "join" => Some("join"), + "at" => Some("at"), + _ => None, + } +} + +/// Normalize a named-argument key for a builtin to the English param name. +pub fn canonical_param(builtin: &str, param: &str) -> String { + let b = canonical_builtin(builtin).unwrap_or(builtin); + match (b, param) { + ("print", "text" | "内容") => "text".into(), + ("input", "prompt" | "提示") => "prompt".into(), + ("len" | "str" | "int" | "type" | "trim", "value" | "值") => "value".into(), + ("split" | "join", "value" | "值") => "value".into(), + ("split" | "join", "sep" | "分隔") => "sep".into(), + ("at", "value" | "值") => "value".into(), + ("at", "index" | "下标") => "index".into(), + _ => param.to_string(), + } +} + +/// Rewrite callee + named args to English canonical forms when this is a builtin. +/// Returns the callee to dispatch on (canonical builtin or original user/fn name). +pub fn normalize_call_callee_and_args(callee: &str, args: &mut [crate::ast::Arg]) -> String { + match canonical_builtin(callee) { + Some(canon) => { + for a in args.iter_mut() { + if let crate::ast::Arg::Named { name, .. } = a { + *name = canonical_param(canon, name); + } + } + canon.to_string() + } + None => callee.to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keyword_aliases() { + assert_eq!(canonical_keyword("真"), Some("True")); + assert_eq!(canonical_keyword("且"), Some("and")); + assert!(is_reserved_keyword("空")); + } + + #[test] + fn builtin_aliases() { + assert_eq!(canonical_builtin("打印"), Some("print")); + assert_eq!(canonical_builtin("长度"), Some("len")); + assert_eq!(canonical_param("打印", "内容"), "text"); + assert_eq!(canonical_param("print", "内容"), "text"); + } +} diff --git a/src/builtin.rs b/src/builtin.rs index 7a5445e..cb905e6 100644 --- a/src/builtin.rs +++ b/src/builtin.rs @@ -30,3 +30,81 @@ pub fn builtin_int(v: &Value) -> Result { _ => Err("int needs int, bool, or text".into()), } } + +/// `type`: type tag as text (`none` / `bool` / `int` / `text` / `list`). +pub fn builtin_type(v: &Value) -> Value { + Value::Text( + match v { + Value::None => "none", + Value::Bool(_) => "bool", + Value::Int(_) => "int", + Value::Text(_) => "text", + Value::List(_) => "list", + } + .into(), + ) +} + +/// `trim`: strip leading/trailing Unicode whitespace from text. +pub fn builtin_trim(v: &Value) -> Result { + match v { + Value::Text(s) => Ok(Value::Text(s.trim().to_string())), + _ => Err("trim needs text".into()), + } +} + +/// `split`: split text by separator → list of text parts. +pub fn builtin_split(value: &Value, sep: &Value) -> Result { + let text = match value { + Value::Text(s) => s.as_str(), + _ => return Err("split needs text value".into()), + }; + let sep = match sep { + Value::Text(s) => s.as_str(), + _ => return Err("split needs text sep".into()), + }; + if sep.is_empty() { + return Err("split sep must not be empty".into()); + } + let parts: Vec = text + .split(sep) + .map(|p| Value::Text(p.to_string())) + .collect(); + Ok(Value::List(parts)) +} + +/// `join`: join list elements with separator → text. +pub fn builtin_join(value: &Value, sep: &Value) -> Result { + let items = match value { + Value::List(xs) => xs, + _ => return Err("join needs list value".into()), + }; + let sep = match sep { + Value::Text(s) => s.as_str(), + _ => return Err("join needs text sep".into()), + }; + let mut out = String::new(); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push_str(sep); + } + out.push_str(&item.as_display()); + } + Ok(Value::Text(out)) +} + +/// `at`: list element at index (0-based); out of range → None. +pub fn builtin_at(value: &Value, index: &Value) -> Result { + let xs = match value { + Value::List(xs) => xs, + _ => return Err("at needs list value".into()), + }; + let i = match index { + Value::Int(n) => *n, + _ => return Err("at needs int index".into()), + }; + if i < 0 || (i as usize) >= xs.len() { + return Ok(Value::None); + } + Ok(xs[i as usize].clone()) +} diff --git a/src/bytecode/compile.rs b/src/bytecode/compile.rs index bec7a16..c2596ec 100644 --- a/src/bytecode/compile.rs +++ b/src/bytecode/compile.rs @@ -120,6 +120,40 @@ impl<'a> FnCompiler<'a> { self.chunk.spans.push(self.stmt_span); } + fn named_or_first<'b>(&self, call: &'b CallExpr, name: &str) -> Option<&'b Expr> { + call.args + .iter() + .find_map(|a| match a { + Arg::Named { name: n, value } if n == name => Some(value), + _ => None, + }) + .or_else(|| { + call.args.iter().find_map(|a| match a { + Arg::Positional(e) => Some(e), + _ => None, + }) + }) + } + + fn named_or_pos<'b>(&self, call: &'b CallExpr, name: &str, pos: usize) -> Option<&'b Expr> { + if let Some(e) = call.args.iter().find_map(|a| match a { + Arg::Named { name: n, value } if n == name => Some(value), + _ => None, + }) { + return Some(e); + } + let mut i = 0usize; + for a in &call.args { + if let Arg::Positional(e) = a { + if i == pos { + return Some(e); + } + i += 1; + } + } + None + } + fn here(&self) -> u16 { self.chunk.code.len() as u16 } @@ -286,6 +320,10 @@ impl<'a> FnCompiler<'a> { } fn compile_call(&mut self, call: &CallExpr, as_stmt: bool) -> Result<()> { + let mut call = call.clone(); + call.callee = + crate::aliases::normalize_call_callee_and_args(&call.callee, &mut call.args); + match call.callee.as_str() { "print" => { let text_expr = call @@ -335,27 +373,18 @@ impl<'a> FnCompiler<'a> { } return Ok(()); } - "len" | "str" | "int" => { + "len" | "str" | "int" | "type" | "trim" => { let name = call.callee.as_str(); - let value_expr = call - .args - .iter() - .find_map(|a| match a { - Arg::Named { name, value } if name == "value" => Some(value), - _ => None, - }) - .or_else(|| { - call.args.iter().find_map(|a| match a { - Arg::Positional(e) => Some(e), - _ => None, - }) - }) + let value_expr = self + .named_or_first(&call, "value") .ok_or_else(|| self.err(format!("{name} requires value")))?; self.compile_expr(value_expr)?; self.emit(match name { "len" => Op::Len, "str" => Op::Str, "int" => Op::Int, + "type" => Op::TypeOf, + "trim" => Op::Trim, _ => unreachable!(), }); if as_stmt { @@ -363,6 +392,41 @@ impl<'a> FnCompiler<'a> { } return Ok(()); } + "split" | "join" => { + let name = call.callee.as_str(); + let value_expr = self + .named_or_pos(&call, "value", 0) + .ok_or_else(|| self.err(format!("{name} requires value")))?; + let sep_expr = self + .named_or_pos(&call, "sep", 1) + .ok_or_else(|| self.err(format!("{name} requires sep")))?; + self.compile_expr(value_expr)?; + self.compile_expr(sep_expr)?; + self.emit(match name { + "split" => Op::Split, + "join" => Op::Join, + _ => unreachable!(), + }); + if as_stmt { + self.emit(Op::Pop); + } + return Ok(()); + } + "at" => { + let value_expr = self + .named_or_pos(&call, "value", 0) + .ok_or_else(|| self.err("at requires value"))?; + let index_expr = self + .named_or_pos(&call, "index", 1) + .ok_or_else(|| self.err("at requires index"))?; + self.compile_expr(value_expr)?; + self.compile_expr(index_expr)?; + self.emit(Op::GetIndex); + if as_stmt { + self.emit(Op::Pop); + } + return Ok(()); + } _ => {} } diff --git a/src/bytecode/mod.rs b/src/bytecode/mod.rs index 4d06fe9..ab83274 100644 --- a/src/bytecode/mod.rs +++ b/src/bytecode/mod.rs @@ -43,6 +43,14 @@ pub enum Op { Str, /// Pop value → push int (or fail). Int, + /// Pop value → push type name text. + TypeOf, + /// Pop text → push trimmed text. + Trim, + /// Pop sep, then value → push list of text parts. + Split, + /// Pop sep, then list → push joined text. + Join, GetIndex, /// Call function by index; argc values are on the stack (param order). Call(u16, u8), diff --git a/src/bytecode/vm.rs b/src/bytecode/vm.rs index 5cc14cb..e8e1e51 100644 --- a/src/bytecode/vm.rs +++ b/src/bytecode/vm.rs @@ -4,7 +4,10 @@ use anyhow::Result; use std::io::Write; use std::path::{Path, PathBuf}; -use crate::builtin::{builtin_int, builtin_len, builtin_str}; +use crate::builtin::{ + builtin_at, builtin_int, builtin_join, builtin_len, builtin_split, builtin_str, builtin_trim, + builtin_type, +}; use crate::bytecode::{Op, Program}; use crate::debug::emit_trace; use crate::diagnostics::{bail_at, Span}; @@ -218,8 +221,9 @@ impl Vm { let text = prompt.as_display(); self.emit_prompt(&text); let line = self.input.read_line().map_err(|e| { - if e.to_string().contains("input is not available") { - self.err_at(span, "input is not available under capture / view") + let msg = e.to_string(); + if msg.contains("input needs a line") { + self.err_at(span, msg) } else { e } @@ -249,16 +253,28 @@ impl Vm { let n = builtin_int(&v).map_err(|m| self.err_at(span, m))?; stack.push(Value::Int(n)); } + Op::TypeOf => { + let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; + stack.push(builtin_type(&v)); + } + Op::Trim => { + let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?; + stack.push(builtin_trim(&v).map_err(|m| self.err_at(span, m))?); + } + Op::Split => { + let sep = pop(&mut stack).map_err(|m| self.err_at(span, m))?; + let value = pop(&mut stack).map_err(|m| self.err_at(span, m))?; + stack.push(builtin_split(&value, &sep).map_err(|m| self.err_at(span, m))?); + } + Op::Join => { + let sep = pop(&mut stack).map_err(|m| self.err_at(span, m))?; + let value = pop(&mut stack).map_err(|m| self.err_at(span, m))?; + stack.push(builtin_join(&value, &sep).map_err(|m| self.err_at(span, m))?); + } Op::GetIndex => { let idx = pop(&mut stack).map_err(|m| self.err_at(span, m))?; let list = pop(&mut stack).map_err(|m| self.err_at(span, m))?; - match (list, idx) { - (Value::List(xs), Value::Int(i)) if i >= 0 && (i as usize) < xs.len() => { - stack.push(xs[i as usize].clone()); - } - (Value::List(_), Value::Int(_)) => stack.push(Value::None), - _ => return Err(self.err_at(span, "GetIndex needs list and int")), - } + stack.push(builtin_at(&list, &idx).map_err(|m| self.err_at(span, m))?); } Op::Call(fid, argc) => { let fid = fid as usize; diff --git a/src/input_feed.rs b/src/input_feed.rs index 4b47a32..895e270 100644 --- a/src/input_feed.rs +++ b/src/input_feed.rs @@ -1,4 +1,4 @@ -//! Preset stdin lines for `input` (CLI `--stdin-file`, view form, tests). +//! Preset stdin lines for `input` (CLI `--stdin-file`, view form, frontmatter, tests). use std::collections::VecDeque; use std::fs; @@ -23,6 +23,127 @@ pub fn load_stdin_file(path: &Path) -> Result> { Ok(split_stdin_text(&text)) } +/// Prefer explicit override (CLI / view form); else frontmatter `stdin:` / `输入:`. +pub fn effective_stdin(source: &str, override_lines: &[String]) -> Vec { + if !override_lines.is_empty() { + return override_lines.to_vec(); + } + extract_frontmatter_stdin(source) +} + +/// Read demo / preset lines from YAML-ish frontmatter. +/// +/// Supported shapes: +/// - `stdin: Alice` / `输入: 小明` +/// - block scalar: +/// ```text +/// stdin: | +/// Alice +/// Bob +/// ``` +/// - list: +/// ```text +/// stdin: +/// - Alice +/// - Bob +/// ``` +pub fn extract_frontmatter_stdin(source: &str) -> Vec { + let source = source.strip_prefix('\u{feff}').unwrap_or(source); + let lines: Vec<&str> = source.lines().collect(); + if lines.first().map(|l| l.trim()) != Some("---") { + return Vec::new(); + } + + let mut i = 1usize; + while i < lines.len() { + let raw = lines[i]; + let t = raw.trim(); + if t == "---" { + break; + } + + let (key, rest) = match split_fm_key(t) { + Some(pair) => pair, + None => { + i += 1; + continue; + } + }; + if key != "stdin" && key != "输入" { + i += 1; + continue; + } + + let rest = rest.trim(); + if rest == "|" || rest == "|-" || rest == "|+" { + i += 1; + let mut out = Vec::new(); + while i < lines.len() { + let body = lines[i]; + let bt = body.trim(); + if bt == "---" || (!body.starts_with(' ') && !body.starts_with('\t') && !bt.is_empty()) + { + break; + } + if bt.is_empty() && (body.is_empty() || body.chars().all(|c| c == ' ' || c == '\t')) { + out.push(String::new()); + } else { + out.push(strip_block_indent(body)); + } + i += 1; + } + return out; + } + if rest.is_empty() { + i += 1; + let mut out = Vec::new(); + while i < lines.len() { + let body = lines[i]; + let bt = body.trim(); + if bt == "---" { + break; + } + if let Some(item) = bt.strip_prefix("- ") { + out.push(item.trim().trim_matches('"').to_string()); + i += 1; + continue; + } + if bt == "-" { + out.push(String::new()); + i += 1; + continue; + } + // end of list (next key or blank then key) + if !body.starts_with(' ') && !body.starts_with('\t') && !bt.is_empty() { + break; + } + if bt.is_empty() { + i += 1; + continue; + } + break; + } + return out; + } + return vec![rest.trim_matches('"').to_string()]; + } + Vec::new() +} + +fn split_fm_key(t: &str) -> Option<(&str, &str)> { + let (k, v) = t.split_once(':')?; + let k = k.trim(); + if k.is_empty() || k.starts_with('>') { + return None; + } + Some((k, v)) +} + +fn strip_block_indent(line: &str) -> String { + let s = line.strip_prefix(" ").or_else(|| line.strip_prefix('\t')).unwrap_or(line); + s.trim_end_matches('\r').to_string() +} + #[derive(Debug, Clone, Default)] pub struct InputFeed { queue: VecDeque, @@ -43,7 +164,9 @@ impl InputFeed { return Ok(line); } if self.capture { - anyhow::bail!("input is not available under capture / view"); + anyhow::bail!( + "input needs a line (frontmatter stdin:/输入:, view Preset input, or --stdin-file)" + ); } let mut line = String::new(); io::stdin().lock().read_line(&mut line)?; @@ -75,6 +198,33 @@ mod tests { assert_eq!(cap.stdout.trim_end(), "Name:Hello Alice!"); } + #[test] + fn capture_uses_frontmatter_stdin() { + let src = "---\ntitle: t\nstdin: Ada\n---\n\n# main\n\n*`n` = > input*\n\n> print text=`n`\n"; + let dir = std::env::temp_dir().join("marqdo-fm-stdin-test"); + let _ = fs::create_dir_all(&dir); + let path = dir.join("fm.mq.md"); + fs::write(&path, src).unwrap(); + let cap = run_file_capture(&path, &RunOptions::default()).expect("fm stdin"); + assert_eq!(cap.stdout.trim_end(), "Ada"); + } + + #[test] + fn extract_block_and_list() { + assert_eq!( + extract_frontmatter_stdin("---\nstdin: |\n a\n b\n---\n"), + vec!["a".to_string(), "b".to_string()] + ); + assert_eq!( + extract_frontmatter_stdin("---\n输入:\n - 甲\n - 乙\n---\n"), + vec!["甲".to_string(), "乙".to_string()] + ); + assert_eq!( + extract_frontmatter_stdin("---\nstdin: Zoe\n---\n"), + vec!["Zoe".to_string()] + ); + } + #[test] fn split_keeps_blank_middle_lines() { assert_eq!( diff --git a/src/interp.rs b/src/interp.rs index 4761a46..4e8471a 100644 --- a/src/interp.rs +++ b/src/interp.rs @@ -7,7 +7,10 @@ use std::path::{Path, PathBuf}; use crate::ast::{ Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp, }; -use crate::builtin::{builtin_int, builtin_len, builtin_str}; +use crate::builtin::{ + builtin_at, builtin_int, builtin_join, builtin_len, builtin_split, builtin_str, builtin_trim, + builtin_type, +}; use crate::debug::emit_trace; use crate::diagnostics::{bail_at, Span}; use crate::input_feed::InputFeed; @@ -388,6 +391,13 @@ impl Interpreter { env: &mut Env, call: &CallExpr, ) -> Result { + let mut call = call.clone(); + let callee = crate::aliases::normalize_call_callee_and_args( + &call.callee, + &mut call.args, + ); + call.callee = callee; + let mut ev_args = Vec::new(); for arg in &call.args { match arg { @@ -423,8 +433,9 @@ impl Interpreter { .unwrap_or_default(); self.emit_prompt(&prompt); let line = self.input.read_line().map_err(|e| { - if e.to_string().contains("input is not available") { - self.err("input is not available under capture / view") + let msg = e.to_string(); + if msg.contains("input needs a line") { + self.err(msg) } else { e } @@ -457,6 +468,55 @@ impl Interpreter { let n = builtin_int(v).map_err(|m| self.err(m))?; return Ok(Value::Int(n)); } + "type" => { + let bound = bind_args(&["value".into()], &ev_args, false) + .map_err(|m| self.err(m))?; + let v = bound + .get("value") + .ok_or_else(|| self.err("type requires value"))?; + return Ok(builtin_type(v)); + } + "trim" => { + let bound = bind_args(&["value".into()], &ev_args, false) + .map_err(|m| self.err(m))?; + let v = bound + .get("value") + .ok_or_else(|| self.err("trim requires value"))?; + return builtin_trim(v).map_err(|m| self.err(m)); + } + "split" => { + let bound = bind_args(&["value".into(), "sep".into()], &ev_args, false) + .map_err(|m| self.err(m))?; + let value = bound + .get("value") + .ok_or_else(|| self.err("split requires value"))?; + let sep = bound + .get("sep") + .ok_or_else(|| self.err("split requires sep"))?; + return builtin_split(value, sep).map_err(|m| self.err(m)); + } + "join" => { + let bound = bind_args(&["value".into(), "sep".into()], &ev_args, false) + .map_err(|m| self.err(m))?; + let value = bound + .get("value") + .ok_or_else(|| self.err("join requires value"))?; + let sep = bound + .get("sep") + .ok_or_else(|| self.err("join requires sep"))?; + return builtin_join(value, sep).map_err(|m| self.err(m)); + } + "at" => { + let bound = bind_args(&["value".into(), "index".into()], &ev_args, false) + .map_err(|m| self.err(m))?; + let value = bound + .get("value") + .ok_or_else(|| self.err("at requires value"))?; + let index = bound + .get("index") + .ok_or_else(|| self.err("at requires index"))?; + return builtin_at(value, index).map_err(|m| self.err(m)); + } _ => {} } diff --git a/src/lib.rs b/src/lib.rs index f389884..ef412d7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,7 @@ //! Pipeline: load → line classify → parse → tree-walk eval | bytecode VM. //! CLI also offers `view` for AST-backed browsing. +pub mod aliases; pub mod ast; pub mod builtin; pub mod bytecode; @@ -93,6 +94,7 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result { bail!("{} is empty", path.display()); } + let stdin_lines = crate::input_feed::effective_stdin(&source, &opts.stdin_lines); let path_label = path.display().to_string(); if opts.dump_lines { @@ -127,7 +129,7 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result { match opts.backend { Backend::Tree => { let mut interp = Interpreter::new(Some(path), opts.trace_eval) - .with_stdin(opts.stdin_lines.clone()); + .with_stdin(stdin_lines.clone()); if opts.trace_eval { eprintln!("=== marqdo: trace-eval ({path_label}) ==="); } @@ -142,7 +144,7 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result { print!("{}", program.disassemble()); } let mut vm = Vm::new(Some(path)) - .with_stdin(opts.stdin_lines.clone()) + .with_stdin(stdin_lines) .with_trace(opts.trace_eval); if opts.trace_eval { eprintln!("=== marqdo: trace-eval ({path_label}) ==="); @@ -165,11 +167,13 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result { /// Run and capture stdout (used by `view` and tests). pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result { + let source = std::fs::read_to_string(path) + .map_err(|e| anyhow::anyhow!("failed to read {}: {e}", path.display()))?; + let stdin_lines = crate::input_feed::effective_stdin(&source, &opts.stdin_lines); let module = load_module(path)?; match opts.backend { Backend::Tree => { - let mut interp = Interpreter::with_capture(Some(path), false) - .with_stdin(opts.stdin_lines.clone()); + let mut interp = Interpreter::with_capture(Some(path), false).with_stdin(stdin_lines); let value = interp.run_module(&module)?; Ok(RunCapture { stdout: interp.captured_stdout, @@ -178,7 +182,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result { } Backend::Bytecode => { let program = compile_module(Some(path), &module)?; - let mut vm = Vm::with_capture(Some(path)).with_stdin(opts.stdin_lines.clone()); + let mut vm = Vm::with_capture(Some(path)).with_stdin(stdin_lines); let value = vm.run(&program)?; Ok(RunCapture { stdout: vm.captured_stdout, diff --git a/src/load.rs b/src/load.rs index ef40be4..d8411f8 100644 --- a/src/load.rs +++ b/src/load.rs @@ -1,6 +1,7 @@ //! Load `.mq.md` files and merge frontmatter imports. use std::collections::HashSet; +use std::env; use std::path::{Path, PathBuf}; use anyhow::{bail, Context, Result}; @@ -30,7 +31,7 @@ fn load_module_inner(path: &Path, visited: &mut HashSet) -> Result) -> Result Result { + let rel = rel.replace('\\', "/"); + let direct = from_dir.join(&rel); + if direct.is_file() { + return Ok(direct); + } + + let normalized = if let Some(rest) = rel.strip_prefix("std/") { + format!("lib/{rest}") + } else { + rel.clone() + }; + + if let Some(remainder) = normalized.strip_prefix("lib/") { + for root in lib_search_roots() { + let as_lib_dir = root.join(remainder); + if as_lib_dir.is_file() { + return Ok(as_lib_dir); + } + let as_repo_root = root.join("lib").join(remainder); + if as_repo_root.is_file() { + return Ok(as_repo_root); + } + } + bail!( + "cannot resolve library import `{rel}` (set MARQDO_LIB or keep a lib/ next to the project)" + ); + } + + Ok(direct) +} + +fn lib_search_roots() -> Vec { + let mut roots = Vec::new(); + if let Ok(h) = env::var("MARQDO_LIB") { + roots.push(PathBuf::from(h)); + } + if let Ok(cwd) = env::current_dir() { + roots.push(cwd.join("lib")); + roots.push(cwd); + } + if let Ok(exe) = env::current_exe() { + if let Some(dir) = exe.parent() { + roots.push(dir.join("lib")); + roots.push(dir.join("../lib")); + roots.push(dir.join("../../lib")); + roots.push(dir.join("../../../lib")); + } + } + roots +} + fn attach_path(path: &Path, err: anyhow::Error) -> anyhow::Error { if let Some(d) = err.downcast_ref::() { if d.path.is_none() { @@ -47,7 +102,6 @@ fn attach_path(path: &Path, err: anyhow::Error) -> anyhow::Error { } return err; } - // Legacy `line:col: message` from parse bail! let msg = err.to_string(); if let Some((loc, rest)) = msg.split_once(": ") { if let Some((line_s, col_s)) = loc.split_once(':') { @@ -66,3 +120,21 @@ fn merge_top_level(into: &mut Vec, fun: Function) { into.push(fun); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn resolve_lib_from_cwd() { + let cwd = env::current_dir().unwrap(); + let lib_text = cwd.join("lib").join("text.mq.md"); + if !lib_text.is_file() { + return; + } + let p = resolve_import(Path::new("tests/keywords"), "lib/text.mq.md").unwrap(); + assert!(p.ends_with("text.mq.md")); + let p2 = resolve_import(Path::new("tests/keywords"), "std/text.mq.md").unwrap(); + assert!(p2.ends_with("text.mq.md")); + } +} diff --git a/src/parse/expr.rs b/src/parse/expr.rs index 1dc8b58..a1744d2 100644 --- a/src/parse/expr.rs +++ b/src/parse/expr.rs @@ -129,16 +129,24 @@ impl<'a> Parser<'a> { } } + /// Eat English or Chinese logic keyword with word-boundary check. + fn eat_logic_kw(&mut self, en: &str, zh: &str) -> bool { + if self.starts_with(en) && is_word_end(self.rest(), en.len()) { + self.i += en.len(); + return true; + } + if self.starts_with(zh) && is_word_end(self.rest(), zh.len()) { + self.i += zh.len(); + return true; + } + false + } + fn parse_or(&mut self) -> Result { let mut left = self.parse_and()?; loop { self.skip_ws(); - if self.eat("or") { - // ensure word boundary - if self.peek_char().map(|c| c.is_alphanumeric() || c == '_').unwrap_or(false) { - self.i -= 2; - break; - } + if self.eat_logic_kw("or", "或") { let right = self.parse_and()?; left = Expr::Binary { op: BinaryOp::Or, @@ -156,11 +164,7 @@ impl<'a> Parser<'a> { let mut left = self.parse_cmp()?; loop { self.skip_ws(); - if self.eat("and") { - if self.peek_char().map(|c| c.is_alphanumeric() || c == '_').unwrap_or(false) { - self.i -= 3; - break; - } + if self.eat_logic_kw("and", "且") { let right = self.parse_cmp()?; left = Expr::Binary { op: BinaryOp::And, @@ -255,16 +259,12 @@ impl<'a> Parser<'a> { fn parse_unary(&mut self) -> Result { self.skip_ws(); - if self.eat("not") { - if self.peek_char().map(|c| c.is_alphanumeric() || c == '_').unwrap_or(false) { - self.i -= 3; - } else { - let expr = self.parse_unary()?; - return Ok(Expr::Unary { - op: UnaryOp::Not, - expr: Box::new(expr), - }); - } + if self.eat_logic_kw("not", "非") { + let expr = self.parse_unary()?; + return Ok(Expr::Unary { + op: UnaryOp::Not, + expr: Box::new(expr), + }); } if self.eat("-") { let expr = self.parse_unary()?; @@ -312,14 +312,26 @@ impl<'a> Parser<'a> { self.i += 4; return Ok(Expr::Literal(Literal::Bool(true))); } + if self.starts_with("真") && is_word_end(self.rest(), '真'.len_utf8()) { + self.i += '真'.len_utf8(); + return Ok(Expr::Literal(Literal::Bool(true))); + } if self.starts_with("False") && is_word_end(self.rest(), 5) { self.i += 5; return Ok(Expr::Literal(Literal::Bool(false))); } + if self.starts_with("假") && is_word_end(self.rest(), '假'.len_utf8()) { + self.i += '假'.len_utf8(); + return Ok(Expr::Literal(Literal::Bool(false))); + } if self.starts_with("None") && is_word_end(self.rest(), 4) { self.i += 4; return Ok(Expr::Literal(Literal::None)); } + if self.starts_with("空") && is_word_end(self.rest(), '空'.len_utf8()) { + self.i += '空'.len_utf8(); + return Ok(Expr::Literal(Literal::None)); + } if self.peek_char().map(|c| c.is_ascii_digit()).unwrap_or(false) { let start = self.i; while self.peek_char().map(|c| c.is_ascii_digit()).unwrap_or(false) { @@ -485,8 +497,16 @@ mod tests { } #[test] - fn interp_hello() { - let e = parse_value_or_interp("Hello `谁`!").unwrap(); - assert!(matches!(e, Expr::Interp(_))); + fn chinese_logic_and_literals() { + let e = parse_expr("`a` 且 非 `b`").unwrap(); + assert!(matches!(e, Expr::Binary { op: BinaryOp::And, .. })); + assert!(matches!( + parse_expr("真").unwrap(), + Expr::Literal(Literal::Bool(true)) + )); + assert!(matches!( + parse_expr("空").unwrap(), + Expr::Literal(Literal::None) + )); } } diff --git a/src/parse/mod.rs b/src/parse/mod.rs index 3f61f9e..e85986e 100644 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -248,6 +248,9 @@ impl<'a> Cursor<'a> { return Ok(None); }; let name = rest[..end].to_string(); + if crate::aliases::is_reserved_keyword(&name) { + bail!("{span}: `{name}` is a reserved keyword"); + } let after = rest[end + 1..].trim_start(); if !after.starts_with('=') { return Ok(None); @@ -419,6 +422,9 @@ fn parse_assign_or_expr_stmt(inner: &str, span: Span) -> Result { if let Some(rest) = inner.strip_prefix('`') { if let Some(end) = rest.find('`') { let name = rest[..end].to_string(); + if crate::aliases::is_reserved_keyword(&name) { + bail!("{span}: `{name}` is a reserved keyword"); + } let after = rest[end + 1..].trim_start(); if let Some(rhs) = after.strip_prefix('=') { let rhs = rhs.trim(); diff --git a/src/view/html.rs b/src/view/html.rs index 9d537e1..f8ad7df 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -624,14 +624,24 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM LinkMode::Live => format!( r#"
- +
"#, path = escape(rel), stdin = escape(&vm.preset_stdin), ), - LinkMode::Static { .. } => String::new(), + LinkMode::Static { .. } => { + if vm.preset_stdin.is_empty() { + String::new() + } else { + format!( + r#"

Demo stdin from frontmatter (static export cannot re-run interactively):

+
{stdin}
"#, + stdin = escape(&vm.preset_stdin), + ) + } + } }; let title = Path::new(rel) .file_name() diff --git a/src/view/mod.rs b/src/view/mod.rs index 61979c1..1aff967 100644 --- a/src/view/mod.rs +++ b/src/view/mod.rs @@ -14,7 +14,7 @@ use std::process::Command; use anyhow::{bail, Context, Result}; use tiny_http::{Header, Method, Request, Response, Server, StatusCode}; -use crate::input_feed::split_stdin_text; +use crate::input_feed::{effective_stdin, split_stdin_text}; use crate::view::html::{escape, page_file, page_index, LinkMode}; use crate::view::render::{render_module_structure, FileViewModel}; use crate::{run_file_capture, RunOptions}; @@ -172,8 +172,9 @@ pub(crate) fn build_file_view( escape(&tidy_user_error(&format!("{e:#}"), abs, rel)) ), }; + let effective = effective_stdin(&source, stdin_lines); let opts = RunOptions { - stdin_lines: stdin_lines.to_vec(), + stdin_lines: effective.clone(), ..RunOptions::default() }; let (stdout, stderr, ok) = match run_file_capture(abs, &opts) { @@ -191,7 +192,7 @@ pub(crate) fn build_file_view( stdout, stderr, ok, - preset_stdin: stdin_lines.join("\n"), + preset_stdin: effective.join("\n"), }) } @@ -277,33 +278,33 @@ fn query_param<'a>(query: &'a str, key: &str) -> Option { } fn urlencoding_decode(s: &str) -> String { - // Minimal decode for %XX and + - let mut out = String::new(); + // Minimal decode for %XX and + (UTF-8 byte sequences, not Latin-1 chars). + let mut out = Vec::new(); let bytes = s.as_bytes(); let mut i = 0; while i < bytes.len() { match bytes[i] { b'+' => { - out.push(' '); + out.push(b' '); i += 1; } b'%' if i + 2 < bytes.len() => { let hex = &s[i + 1..i + 3]; if let Ok(v) = u8::from_str_radix(hex, 16) { - out.push(v as char); + out.push(v); i += 3; } else { - out.push('%'); + out.push(b'%'); i += 1; } } c => { - out.push(c as char); + out.push(c); i += 1; } } } - out + String::from_utf8_lossy(&out).into_owned() } fn files_json(files: &[PathBuf]) -> String { diff --git a/tests/errors/bad-split-sep.mq.md b/tests/errors/bad-split-sep.mq.md new file mode 100644 index 0000000..086a568 --- /dev/null +++ b/tests/errors/bad-split-sep.mq.md @@ -0,0 +1,7 @@ +--- +title: empty split sep +--- + +# main + +*`xs` = > split value=ab sep=* diff --git a/tests/gold.rs b/tests/gold.rs index 2169754..42683c1 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -165,6 +165,94 @@ fn bytecode_stdlib() { ); } + +#[test] +fn keywords_stdlib_more() { + assert_out( + "tests/keywords/stdlib-more.mq.md", + "hi +3 +b +a-b-c +list", + ); +} + +#[test] +fn bytecode_stdlib_more() { + assert_out_backend( + "tests/keywords/stdlib-more.mq.md", + "bytecode", + "hi +3 +b +a-b-c +list", + ); +} + + +#[test] +fn keywords_zh_builtins() { + assert_out( + "tests/keywords/zh-builtins.mq.md", + "5 +7", + ); +} + +#[test] +fn bytecode_zh_builtins() { + assert_out_backend( + "tests/keywords/zh-builtins.mq.md", + "bytecode", + "5 +7", + ); +} + +#[test] +fn keywords_zh_bool() { + assert_out( + "tests/keywords/zh-bool.mq.md", + "ok +none-falsy", + ); +} + +#[test] +fn bytecode_zh_bool() { + assert_out_backend( + "tests/keywords/zh-bool.mq.md", + "bytecode", + "ok +none-falsy", + ); +} + + +#[test] +fn structure_import_lib() { + assert_out( + "tests/structure/import-lib.mq.md", + "x +2 +a", + ); +} + +#[test] +fn bytecode_import_lib() { + assert_out_backend( + "tests/structure/import-lib.mq.md", + "bytecode", + "x +2 +a", + ); +} + + #[test] fn error_undefined_var() { assert_err( @@ -215,6 +303,15 @@ fn error_bad_int() { ); } +#[test] +fn error_bad_split_sep() { + assert_err( + "tests/errors/bad-split-sep.mq.md", + "7:1", + "split sep must not be empty", + ); +} + fn assert_out_backend(path: &str, backend: &str, expect: &str) { let (code, stdout, stderr) = run(&["run", path, "--backend", backend]); assert_eq!(code, 0, "{path} backend={backend} stderr={stderr}"); diff --git a/tests/keywords/stdlib-more.mq.md b/tests/keywords/stdlib-more.mq.md new file mode 100644 index 0000000..39aa056 --- /dev/null +++ b/tests/keywords/stdlib-more.mq.md @@ -0,0 +1,30 @@ +--- +title: stdlib text and table +description: trim split join at type + lib imports +--- + +# main + +*`raw` = hi * + +*`t` = > trim `raw`* + +> print text=`t` + +*`parts` = > split value=a,b,c sep=,* + +*`n` = > len `parts`* + +> print text=`n` + +*`mid` = > at value=`parts` index=1* + +> print text=`mid` + +*`joined` = > join value=`parts` sep=-* + +> print text=`joined` + +*`ty` = > type `parts`* + +> print text=`ty` diff --git a/tests/keywords/zh-bool.mq.md b/tests/keywords/zh-bool.mq.md new file mode 100644 index 0000000..9631870 --- /dev/null +++ b/tests/keywords/zh-bool.mq.md @@ -0,0 +1,20 @@ +--- +title: 中文布尔与逻辑 +--- + +# main + +*`a` = 真* +*`b` = 假* + ++ `a` 且 非 `b` + > 打印 内容=ok ++ * + > 打印 内容=fail + +*`probe` = 1* + ++ 空 + > 打印 内容=none-truthy ++ * + > 打印 内容=none-falsy diff --git a/tests/keywords/zh-builtins.mq.md b/tests/keywords/zh-builtins.mq.md new file mode 100644 index 0000000..6f6e39a --- /dev/null +++ b/tests/keywords/zh-builtins.mq.md @@ -0,0 +1,18 @@ +--- +title: 中文内置函数 +description: 打印 / 长度 / 文本 / 整数(与英文别名等价) +--- + +# main + +*`s` = hello* + +*`n` = > 长度 值=`s`* + +> 打印 内容=`n` + +*`t` = > 文本 值=7* + +*`i` = > 整数 值=`t`* + +> 打印 内容=`i` diff --git a/tests/structure/import-lib.mq.md b/tests/structure/import-lib.mq.md new file mode 100644 index 0000000..5c8d427 --- /dev/null +++ b/tests/structure/import-lib.mq.md @@ -0,0 +1,26 @@ +--- +title: import official lib (Chinese) +> lib/文本.mq.md +> lib/表.mq.md +--- + +# main + +*`t` = > 去空白 s= x * + +> 打印 内容=`t` + +`xs` = + +| v | +|---| +| a | +| b | + +*`n` = > 行数 xs=`xs`* + +> 打印 内容=`n` + +*`row` = > 取行 xs=`xs` i=0* + +> 打印 内容=`row`