diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index 079ae57..8b1f108 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -19,21 +19,22 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. 1. **File suffix** must be `.mq.md` (never plain `.md` for executable sources). 2. **Output is not `**bold**`.** Print with `> print text=…` (or `> 打印 内容=…`). Bold `**…**` is **return value only**. 3. **Prose vs code:** after a blank line, an unmarked first line starts a **comment paragraph**; every following non-blank line stays comment until the next blank line. Put a **blank line** between narration and executable lines. -4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: `+` branch, `-` loop, arm-head lone `*` = else, `#` = **object/type**, `##`+ = **function/method**, `**…**` = return. -5. **Structure lines are not wrapped in italics.** `#` `>` `+` `-` `|` lines stand alone; use `*…*` only for general statements (bindings / expressions). -6. **Paths in bare expressions:** `/` is division. Prefer `` `path` `` vars, same-dir names, or call args — not raw `a/b` in expressions. -7. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed. +4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`+` params** (under heading), **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**, `**…**` = return. +5. **Identifiers use backticks** — params `` + `name` ``, bindings `` `x` ``, foreach `` [`item`](`coll`) ``. **Complex text** uses `"..."` with escapes; bare tokens stay literal (no `\n` magic). +6. **Structure lines are not wrapped in italics.** `#` `>` `+` `-` `|` lines stand alone; use `*…*` only for general statements (bindings / expressions). +7. **Paths in bare expressions:** `/` is division. Prefer `` `path` `` vars, same-dir names, or call args — not raw `a/b` in expressions. +8. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed. -## Markup → meaning (v0.1) +## Markup → meaning (v0.2) | Marker | Meaning | |--------|---------| | `#` | **Object / type** (constructor body). `# main` = entry object. | | `##` … `######` | **Function / method** (nesting by heading depth). | -| `- name` under a heading | Parameter | -| `- …` inside body | Loop | -| `+ …` or `1.` | Branch arm (condition) | -| Line that is only `*` | Else arm | +| `` + `name` `` under heading | Parameter (optional `` `name`=default ``) | +| `1.` `2.` … in body | Branch arm (condition or `N. *` else) | +| `- …` inside body | Loop (`while` or `` [`item`](`coll`) ``) | +| Line `N. *` | Else arm | | `> fn args` | Call (named `k=v` or positional) | | `` > `obj`.method args `` | Method call (`obj` must be a map with `_type`) | | Frontmatter `> path.mq.md` | Import | @@ -43,6 +44,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. | Lone `---` / `***` in function body | End function body (no value) | | GFM table after empty RHS bind | Collection | | `` ```lang `` | Foreign code block (via `lib/foreign`) | +| `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped | | Unmarked prose | Comment | Entry: load file (often `index.mq.md`) → collect defs → run `# main`. @@ -71,7 +73,7 @@ Chinese builtins (same functions, no import): > greet who=Marqdo ## greet - - who + + `who` > print text=Hello, `who`! @@ -88,8 +90,8 @@ Chinese builtins (same functions, no import): *`x` = 1* *`y` = `x` + 2* -# add_one - - n +## add_one + + `n` **`n` + 1** ``` @@ -97,11 +99,11 @@ Chinese builtins (same functions, no import): ```markdown *`n` = 0* -+ `n` > 0 +1. `n` > 0 > print text=positive -+ `n` < 0 +2. `n` < 0 > print text=negative -+ * +3. * > print text=zero ``` @@ -141,7 +143,7 @@ Stdlib map: [reference.md](reference.md). |-------|-------| | `**Hello**` to print | `> print text=Hello` | | `# main` then prose then code with no blank line | Blank line before code | -| `if x > 0:` | `+ `x` > 0` | +| `if x > 0:` | `1. `x` > 0` | | `* > print text=hi *` | `> print text=hi` | | Forgetting `---` after nested `##` helper | Add `---` / `***` / `****` | | Import `lib/text` then call `拆分` | Match file language | diff --git a/.cursor/skills/marqdo/examples.md b/.cursor/skills/marqdo/examples.md index a4cbd17..8c1e2a4 100644 --- a/.cursor/skills/marqdo/examples.md +++ b/.cursor/skills/marqdo/examples.md @@ -26,7 +26,7 @@ Greeting via a nested function: > greet who=Marqdo ## greet - - who + + `who` > print text=Hello, `who`! @@ -43,7 +43,7 @@ Greeting via a nested function: > print text=`b` ## add_one - - n + + `n` **`n` + 1** ``` @@ -55,15 +55,29 @@ Greeting via a nested function: *`n` = 0* -+ `n` > 0 +1. `n` > 0 > print text=positive -+ `n` < 0 +2. `n` < 0 > print text=negative -+ * +3. * > print text=zero ``` -## 6. Import text stdlib +## 6. Foreach loop + +```markdown +# main + +`篮子` = +| 果 | +|----| +| 苹果 | + +- [`果`](`篮子`) + > print text=`果` +``` + +## 7. Import text stdlib ```markdown --- @@ -77,7 +91,7 @@ title: split demo > print text=`parts` ``` -## 7. Comment paragraphs (blank-line rule) +## 8. Comment paragraphs (blank-line rule) ```markdown # main @@ -91,7 +105,7 @@ After a blank line, code runs: > print text=this runs ``` -## 8. Frontmatter import only +## 9. Frontmatter import only ```markdown --- @@ -105,11 +119,11 @@ description: loads math > print text=`t` ``` -## 9. Object handle + method +## 10. Object handle + method See `tests/structure/object-handle.mq.md` and `ext/llm.mq.md`: `# Type` constructs a map with `_type`; methods use `` > `obj`.method `` and read `self` / `自`. -## 10. Agent layout (ABI) +## 11. Agent layout (ABI) ```markdown --- @@ -127,7 +141,7 @@ See `tests/structure/object-handle.mq.md` and `ext/llm.mq.md`: `# Type` construc Requires `MARQDO_AGENT_PLUGIN` pointing at the built `agent` shared library (see `doc/design/ext-agent.md`). -## 11. What not to emit +## 12. What not to emit ```markdown # BAD — bold is return, not print @@ -139,4 +153,10 @@ if x > 0: # BAD — wrapping a call in italics *> print text=hi* + +# BAD — old branch syntax (removed) ++ `x` > 0 + +# GOOD — ordered list arms +1. `x` > 0 ``` diff --git a/.cursor/skills/marqdo/reference.md b/.cursor/skills/marqdo/reference.md index ae4e74e..b5b95c2 100644 --- a/.cursor/skills/marqdo/reference.md +++ b/.cursor/skills/marqdo/reference.md @@ -18,6 +18,8 @@ marqdo ext remove llm|agent Diagnostics look like `path:line:col: message` (1-based line/col). +**v0.2 surface:** parameters `` + `name` ``; branches `` 1. `cond` `` / `` 2. * ``; loops `` - [`item`](`coll`) ``; identifiers in backticks. See `doc/design/markdown-mapping.md`. + Stdlib search order for `lib/…` imports: `MARQDO_LIB`, `./lib`, directory of the `marqdo` executable (and a few parents). Prefer the **bundle zip** (`marqdo.exe` + `lib/`) over a bare exe. 官方扩展(`ext/…`,非 stdlib):`marqdo ext add` 装到 `MARQDO_EXT` 或 `~/.marqdo/ext`;导入仍写 `> ext/llm.mq.md`。解析还含 cwd `ext/`、二进制旁 `ext/`。对象:`doc/design/objects.md`。Agent:`doc/design/ext-agent.md` · 安装器:`doc/design/ext-cli.md`。 diff --git a/README.md b/README.md index f076efc..903ab89 100644 --- a/README.md +++ b/README.md @@ -35,8 +35,8 @@ Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件, | `#` | 对象 / 类型(构造体;`# main` = 入口) | | `##` … | 函数 / 方法(按标题深度嵌套) | | `` > `obj`.method … `` | 方法调用(`obj` 为带 `_type` 的 map) | -| `+` / `1.` | 分支(臂头单独 `*` = else) | -| `-` | 循环(头下纯名则为形参) | +| `+` / `1.` … | 函数头下 `` + `名` `` = 形参;体内 `1.` `2.` … = 分支(`N. *` = else) | +| `-` | 循环(`` - `条件` `` 或 `` - [`项`](`集合`) ``) | | 表格 | 集合 | | 函数体内单独一行 `---` / `***` | **结束本函数体**(无返回值收束;见 mapping §11) | | 文件开头成对 `---` … `---` | Frontmatter(元信息 / 导入),与函数结束符消歧 | @@ -47,14 +47,14 @@ Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件, > 问候 谁=World ## 问候 - - 谁 + + `谁` > print text=Hello `谁`! --- ## 加一 - - n + + `n` **`n` + 1** ``` diff --git a/doc/design/code-vs-comment.md b/doc/design/code-vs-comment.md index 1d3c0ee..ce0c25a 100644 --- a/doc/design/code-vs-comment.md +++ b/doc/design/code-vs-comment.md @@ -21,7 +21,8 @@ - 以**空行**划分段落。 - 段首行:首字符非标记 → 注释。 -- 段内续行:一律注释(即使以 `` ` `` / `-` 等开头)。 +- 段内续行:一律注释(即使以 `` ` `` / `-` / `**` 等开头)。 +- **例外**:整行仅为 `**expr**`(或 `****`)→ Marqdo **返回**;`**强调**` 后还有文字 → 仍是叙述注释。 - 叙述段与可执行代码之间**必须空一行**,否则 `> print` 等会被吞进注释段。 --- diff --git a/doc/design/examples-and-tests.md b/doc/design/examples-and-tests.md index 9503639..162fdfe 100644 --- a/doc/design/examples-and-tests.md +++ b/doc/design/examples-and-tests.md @@ -42,7 +42,7 @@ tests/ | 类别 | 测什么 | 不测什么 | |------|--------|----------| -| **structure** | `#`/`##`、形参、`>` 调用、`*`/`**`、`+`/`-`、表、导入、位置/具名实参 | 关键字边角 | +| **structure** | `#`/`##`、形参 `+`、`1.` 分支、`-` 循环、表、导入、位置/具名实参 | 关键字边角 | | **keywords** | `True`/`False`/`None`、`and`/`or`/`not`、`print`/`input` 约定 | 复杂控制流(可极简) | | **errors** | 未定义名、实参错误、语法错误的诊断 | 成功路径 | diff --git a/doc/design/keywords-i18n.md b/doc/design/keywords-i18n.md index aea629d..c852572 100644 --- a/doc/design/keywords-i18n.md +++ b/doc/design/keywords-i18n.md @@ -36,7 +36,7 @@ L0 **不做** `lang:`、不做「当前语言模式」;写英文名就用英 ### 3.1 字面量 / 逻辑关键字(词法保留) -控制流仍靠 Markdown(`#` `+` `-` `*` `**`),**不**为 `if`/`while`/`def` 做中英关键字。 +控制流仍靠 Markdown(`#` `1.` `-` `*` `**`),**不**为 `if`/`while`/`def` 做中英关键字。形参用 `+`。 | 英文 | 中文(提案) | 备注 | |------|--------------|------| @@ -107,7 +107,7 @@ L0 **不做** `lang:`、不做「当前语言模式」;写英文名就用英 - 旧文「中文 `print` 废弃、统一为 `print`」:**废止**;改为正式双名 `print` / `打印`。 - [keywords.md](keywords.md) 原则条「英文标识」改为「**内核双名;标准库分文件**」——实现阶段改正文。 -- 不引入中文控制流关键字(`如果`/`循环` 等);分支循环仍用 `+` / `-`。 +- 不引入中文控制流关键字(`如果`/`循环` 等);分支用 `1.` …,循环用 `-`。 --- diff --git a/doc/design/keywords.md b/doc/design/keywords.md index 1c6c4db..8f0ec95 100644 --- a/doc/design/keywords.md +++ b/doc/design/keywords.md @@ -11,7 +11,7 @@ ## 1. 设计原则 -1. **标记承担架构**:函数=`#`,分支=`+`,循环=`-`,返回=`**…**`,语句=`*…*`。因此 **不**把 `def`/`if`/`else`/`while`/`for`/`return` 做成关键字。 +1. **标记承担架构**:函数=`#`,**形参=`+`**,**分支=`1.`…**,循环=`-`,返回=`**…**`,语句=`*…*`。因此 **不**把 `def`/`if`/`else`/`while`/`for`/`return` 做成关键字。 2. **内核双名**:字面量 / 逻辑词 / 五个核心内置函数均有中英别名,**无需导入**,可混用。 3. **学 Python 的边界**:区分 **关键字** vs **内置函数名**。 4. **宁少勿多**:扩展能力进可导入标准库(中英分文件,见 [stdlib-i18n.md](stdlib-i18n.md))。 @@ -43,6 +43,8 @@ | `str` | `文本` | 转为显示文本 | | `int` | `整数` | 转为整数 | +**文本**:裸 token 按字面量;需 `\n` 等转义时用 `"..."`(见 [markdown-mapping.md](markdown-mapping.md) §7)。 + 形参别名: | 英文 | 中文 | 用于 | @@ -71,9 +73,9 @@ *`n` = 1* -+ `n` > 0 +1. `n` > 0 > print text=positive -+ * +2. * > 打印 内容=other ``` diff --git a/doc/design/markdown-mapping.md b/doc/design/markdown-mapping.md index e386b8e..cb464d3 100644 --- a/doc/design/markdown-mapping.md +++ b/doc/design/markdown-mapping.md @@ -1,10 +1,10 @@ -# Marqdo 语法映射 v0.1(Markup-as-Syntax) +# Marqdo 语法映射 v0.2(Markup-as-Syntax) | | | |---|---| -| 状态 | 已定论(修订:语句 / 返回 / 输出职责分离;`#` = 对象) | +| 状态 | 已定论(修订:形参 `+`、分支 `1.`、标识符反引号、`-` 专用于循环) | | 日期 | 2026-08-06 | -| 取代 | v0 中「`**`=输出、`*`=返回」 | +| 取代 | v0.1 中「函数头 `-` 形参 / 裸名形参与遍历变量 / `+` 分支」 | | 相关 | [objects.md](objects.md) · [code-vs-comment.md](code-vs-comment.md) · [return-hr-and-code-surface.md](return-hr-and-code-surface.md) | Markdown **标记即语法**。输出**不是**语言架构原语,而是内置函数 **`print`**(英文;见 [keywords.md](keywords.md))。 @@ -15,8 +15,9 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 1. `.mq.md`:打开即文档,运行即程序。 2. **叙述注释**以空行分段:段首无标记 → 注释;段内续行一律注释(见 §2)。 -3. **可执行**靠标记:结构标记(`#` `>` `+` `-` 表…)与 **斜体语句** / **粗体返回**。 +3. **可执行**靠标记:结构标记(`#` `>` `+` `-` `1.` 表…)与 **斜体语句** / **粗体返回**。 4. **`#` = 对象/类型**,**`##`+ = 函数/方法**(嵌套按标题深度);入口优先 `# main`(见 [objects.md](objects.md))。函数体可用 `---` / `***` 或空返回收束(见 §11)。 +5. **标识符一律反引号**:凡表示变量槽位(形参、绑定、引用、遍历项、集合名)均写作 `` `名` ``,与 Markdown 无序列表/链接脱钩。 --- @@ -29,21 +30,21 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 | 普通文字 / 空 | **注释** | | 标记字符 | **代码** | -标记含:`#` `*` `>` `+` `-` `` ` `` `|`、有序数字、围栏 `` ` ``、以及函数体内的结束分割线 `---` / `***`(见 §11)。 +标记含:`#` `*` `>` `+` `-` `` ` `` `|`、有序数字 `1.`、围栏 `` ` ``、以及函数体内的结束分割线 `---` / `***`(见 §11)。 **成段注释(空行分段)**:段首一旦判定为注释,则直至下一空行之前的所有非空行一律为注释——即使续行以 `` ` `` / `-` / `*` 等开头也不升级为代码。叙述与可执行代码之间**必须空一行**。例外:单独一行的 `---` / `***` / `****`(函数结束或 frontmatter 闭合)始终为代码,并打断注释段。 --- -## 3. 映射总表(v0.1) +## 3. 映射总表(v0.2) | 标记 | 语义 | |------|------| | `#` … `######` | **`#` = 对象/类型**;**`##`+ = 函数/方法**(层差=嵌套)。见 [objects.md](objects.md) | -| 函数头下 `-` 纯名 | 形参 / 构造参数 | -| 体内 `-` | 循环 | -| 体内 `+` 或 `1.` | 分支 | -| 分支臂头整行恰为 `*` | else | +| 函数头下 `+ `` `名` `` ` | 形参 / 构造参数(可选 `` `名`=默认值 ``) | +| 体内 `1.` `2.` … | **分支**(有序列表臂;条件行或 else) | +| 体内 `-` | **循环**(`while` 条件,或 `` [`项`](`集合`) `` 遍历) | +| 分支臂头整行恰为 `*`(在 `N.` 后) | else,如 `2. *` | | `> 函数 形参=实参` 或 `> 函数 实参` | 调用(具名 / 位置,见 [call-arguments.md](call-arguments.md)) | | `` > `对象`.方法 … `` | 方法调用(实例 map 须含 `_type`) | | frontmatter `> path.mq.md` | 跨文件导入 | @@ -56,13 +57,23 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 | ` ```lang ` | 外联异种代码 | | 函数体内 `---` / `***` | **结束本函数体**(无返回值函数的收束;见 §11) | +### `+` / `-` / `1.` 消歧 + +| 位置 | `+` | `1.` … | `-` | +|------|-----|--------|-----| +| 函数标题后、**首条体语句前** | 形参:`` + `名` `` / `` + `名`=默认 `` | (非法) | (非法作形参) | +| 函数体内 | (非法作分支) | 分支臂:`1. `条件`` / `2. *` | 循环 | + +**分支从未使用 `+`。** 自 v0 起即采用 GFM 有序列表;`+` 在 v0.2 专用于形参,与 `-` 循环彻底分离。 + ### 输出不是架构 -| 错误(旧) | 正确(v0.1) | +| 错误(旧) | 正确(v0.2) | |------------|--------------| | `**Hello**` 表示打印 | `> print text=Hello` | -| 中文名 `输出`(已废弃) | 统一英文内置 `print` | -| 输出与返回抢粗体 | 粗体只表示 **返回** | +| `+ `x` > 0` 作分支 | `1. `x` > 0` | +| `- 谁` 作形参 | `` + `谁` `` | +| `[果](篮子)` 裸名遍历 | `` [`果`](`篮子`) `` | `print` / `input` 为内置函数,完整表见 [keywords.md](keywords.md)。 @@ -78,13 +89,13 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 *`y` = `x` + 2* ``` -行首已是结构标记的构造(`#` `>` `+` `-` `|`)**不必**再包一层斜体;斜体用于「一般语句」槽位。 +行首已是结构标记的构造(`#` `>` `+` `-` `|`、`1.`)**不必**再包一层斜体;斜体用于「一般语句」槽位。 ### 返回值(粗体) ```markdown -# 加一 - - n +## 加一 + + `n` **`n` + 1** ``` @@ -99,7 +110,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 ### else 与斜体消歧 -- 分支臂**第一行整行只有一个** `*` → else。 +- 分支臂有序行 `N. *`(或 `N.` 后仅 `*`)→ else。 - `*中间有内容*` → 程序语句。 - `**…**` → 返回(与 else 无关)。 @@ -112,7 +123,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 --- -## 6. 对象、函数、作用域 +## 6. 对象、函数、形参 - `# Name`:对象(构造体);`# main` 为入口对象。 - `##` / `###` …:函数或方法;挂在对象下则为方法。 @@ -124,48 +135,90 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置 > print text=Hello World! ## 加问候 - - 谁 + + `谁` **你好,`谁`** ``` -(需要打印时对返回值再 `> print`,或直接 `> print`。) +可选形参: -形参 `- 名` → 体内 `` `名` ``。方法体内自动绑定 `自` / `self`。 +```markdown +## 问候 + + `谁` + + `礼貌`=False +``` + +方法体内自动绑定 `` `自` `` / `` `self` ``。 --- -## 7. 绑定与比较 +## 7. 绑定、比较与字符串 | 写法 | 含义 | |------|------| -| `*`x` = 1*` 或行首 `` `x` = 1 `` | 绑定(两种均允许;实现应统一) | +| `*`x` = 1*` 或行首 `` `x` = 1 `` | 绑定 | | `` `x` == 1 `` | 相等比较 | +| `"text"` | **双引号字符串**(复杂文本;见下) | +| `hello` / `路径` | **裸 token**(无转义,按字面量) | -v0.1 **推荐**绑定写在斜体语句内,以保持「语句=斜体」一致;行首 `` ` `` 仍合法以便表格右值绑定。 +### 双引号字符串(复杂文本) + +需要转义或嵌入变量时用 `"..."`;**裸 token 不转义**,保持文档简洁: + +```markdown +> input prompt="你叫什么名字\n" +*`msg` = "Hello, `name`!\n"* +``` + +| 转义 | 含义 | +|------|------| +| `\n` | 换行 | +| `\t` | 制表 | +| `\r` | 回车 | +| `\\` | `\` | +| `\"` | `"` | + +引号内仍可用 `` `变量` `` 插值。字面反斜杠+n 写 `\\n`(裸 token `\\n` 则就是两个字符)。 --- ## 8. 分支与循环 -分支(`+` / 有序),循环(`-`),语义同 v0。臂体内打印改为调用 `print`: +分支(**有序列表** `1.` `2.` …),循环(`-`): ```markdown *`x` = 0* -+ `x` > 0 +1. `x` > 0 > print text=正数 -+ `x` < 0 +2. `x` < 0 > print text=负数 -+ * +3. * > print text=零 ``` ```markdown -- [果](篮子) +*`bool_value` = True* + +1. `bool_value` == True + > print text=True +2. * + > print text=False +``` + +```markdown +- [`果`](`篮子`) > print text=今天吃`果` ``` +`while`: + +```markdown +- `n` > 0 + > print text=`n` + *`n` = `n` - 1* +``` + --- ## 9. 集合(表格) @@ -179,21 +232,19 @@ v0.1 **推荐**绑定写在斜体语句内,以保持「语句=斜体」一致 1. 加载 `index.mq.md` + 导入。 2. Pass1 收集定义。 3. Pass2 执行 `# main`。 -4. `*` 语句、`**` 返回、`>` 调用、`+`/`-` 控制流、表绑定按语义执行;`> print` 写 stdout。 +4. `*` 语句、`**` 返回、`>` 调用、`1.` 分支、`-` 循环、表绑定按语义执行;`> print` 写 stdout。 --- ## 11. 函数体结束(`---` / `***` / 空返回) -无返回值(或已写完副作用)的函数,在体末用分割线收束,避免后续同级语句被吞进嵌套函数: - ```markdown # main > 问候 谁=World ## 问候 - - 谁 + + `谁` > print text=Hello `谁`! @@ -202,20 +253,16 @@ v0.1 **推荐**绑定写在斜体语句内,以保持「语句=斜体」一致 | 约定 | 说明 | |------|------| -| `---` 或 `***` | 函数体**顶层**单独一行(长度 ≥ 3 且全为 `-` 或全为 `*`)→ **结束本函数**;后续语句属于外层 | -| `****` / 空粗体 | 空返回(值为 `None`),并同样结束本函数体 | -| 有值 `**expr**` | 普通返回;**不**自动截断后续兄弟句(仍可用分割线或下一同级/更浅标题收束) | -| Frontmatter | 仅**文件开头**成对 `---` = 元信息;与函数体内结束符消歧 | -| 分支/循环臂内 | 分割线仍可忽略(噪声),不截断外层函数 | - -曾设想的「可选框住分支/循环」废止,分割线专用于函数收束。 +| `---` 或 `***` | 函数体**顶层**单独一行 → **结束本函数** | +| `****` / 空粗体 | 空返回(`None`),并结束本函数体 | +| Frontmatter | 仅**文件开头**成对 `---` = 元信息 | --- -## 12. v0.1 非目标 +## 12. v0.2 非目标 - break/continue、完整错误模型、静态类型、完整 FFI -- 用 `*` 作无序列表符 +- `+` 作分支、`+`/`-` 作形参(**不保留**) --- diff --git a/doc/design/objects.md b/doc/design/objects.md index 6e52b6d..e465c95 100644 --- a/doc/design/objects.md +++ b/doc/design/objects.md @@ -31,13 +31,13 @@ ```markdown # 大模型 - - 模型名 + + `模型名` *`自` = …配置 map…* **`自`** ## 运行 - - 提示 + + `提示` …使用 `自` … **`内容`** diff --git a/doc/design/stdlib-modules.md b/doc/design/stdlib-modules.md index 26eb30c..8e85b2d 100644 --- a/doc/design/stdlib-modules.md +++ b/doc/design/stdlib-modules.md @@ -25,9 +25,13 @@ | 数学 | `lib/math.mq.md` | `lib/数学.mq.md` | 已有 | | 外联 | `lib/foreign.mq.md` | `lib/外联.mq.md` | 已有 | | **插件** | `lib/plugin.mq.md` | `lib/插件.mq.md` | **已有**(加载 C ABI 共享库) | +| **自写回** | `lib/writeback.mq.md` | `lib/自写回.mq.md` | **已有**(Jupyter 式输出写回) | +| **子任务** | `lib/subtask.mq.md` | `lib/子任务.mq.md` | **已有**(OS 子进程 + KillOnDrop) | 官方可选扩展(**非** stdlib):`ext/llm` · `ext/agent` — 见 [ext-llm.md](ext-llm.md) / [ext-agent.md](ext-agent.md)。 +设计细节:[stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md)。 + --- ## 2. 分层与实现分工 diff --git a/doc/design/stdlib-subtask.md b/doc/design/stdlib-subtask.md new file mode 100644 index 0000000..50b6335 --- /dev/null +++ b/doc/design/stdlib-subtask.md @@ -0,0 +1,24 @@ +# 子任务标准库(subtask) + +| | | +|---|---| +| 状态 | v1 已落地 | +| 库 | `lib/subtask.mq.md` · `lib/子任务.mq.md` | + +## 定位 + +OS 进程式并发:`spawn` 另起 `marqdo run ` 子进程;**父进程结束(含 panic)时 KillOnDrop 终止所有未 join 的子进程**。 + +v1 不共享 Marqdo 堆;子任务通过 stdout / 文件 / 环境通信。 + +## API + +| EN | ZH | 说明 | +|----|-----|------| +| `spawn` | `启动` | `path=`(`.mq.md`) | +| `poll` | `探测` | `id=` → status map | +| `wait` | `等待` | `id=` → exit code(避免与内置 `join` 冲突) | +| `kill` | `终止` | `id=` | +| `wait_all` | `等待全部` | 所有子进程 exit codes | + +Host:`host_subtask_*`(`src/host/subtask.rs`)。 diff --git a/doc/design/stdlib-writeback.md b/doc/design/stdlib-writeback.md new file mode 100644 index 0000000..f55e0b0 --- /dev/null +++ b/doc/design/stdlib-writeback.md @@ -0,0 +1,36 @@ +# 自写回标准库(writeback) + +| | | +|---|---| +| 状态 | v1 已落地 | +| 库 | `lib/writeback.mq.md` · `lib/自写回.mq.md` | + +## 定位 + +**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` 的 `` → `marqdo view` 在对应语句下显示 **output-card**。普通 Markdown 预览不显示该区域。 + +## 存储格式 + +```markdown +*`n` = > len value=`xs` * + +``` + +- 注释内仅保留 `marqdo-out` 标识,**不存行号**(避免写回后行号漂移) +- 默认在**调用行下方**插入或替换紧邻块(中间可有空行) +- `at_end=true` / `末尾=true`:在文件末尾保留单块(替换已有末尾块) + +## API + +| EN | ZH | 说明 | +|----|-----|------| +| `record` | `写回` | `value=`,可选 `at_end=false` | +| `get` | `取` | 可选 `at_end=false` | +| `clear` | `清除` | 可选 `at_end=false` | +| `list` | `列出` | 全文所有输出块(含推断锚点行) | + +可选参数语法:`` + `参数名`=默认值 ``(与现有参数列表兼容)。 + +Host:`host_writeback_*`(`src/host/writeback.rs`)。 diff --git a/doc/design/stdlib.md b/doc/design/stdlib.md index d8bed1d..3048f67 100644 --- a/doc/design/stdlib.md +++ b/doc/design/stdlib.md @@ -70,6 +70,8 @@ Frontmatter: | `lib/math.mq.md` / `lib/数学.mq.md` | 数值 / 随机 / 公式 / 绘图 | | `lib/foreign.mq.md` / `lib/外联.mq.md` | 具名围栏外联 | | `lib/plugin.mq.md` / `lib/插件.mq.md` | `load` / `unload` / `list`(原生 ABI) | +| `lib/writeback.mq.md` / `lib/自写回.mq.md` | `record` `get` `clear` `list` | +| `lib/subtask.mq.md` / `lib/子任务.mq.md` | `spawn` `poll` `wait` `kill` `wait_all` | | `lib/text.mq.md` | `str_trim` `str_split` `str_join` | | `lib/文本.mq.md` | `去空白` `拆分` `拼接` | | `lib/table.mq.md` | `rows` `row_at` | diff --git a/ext/ai/agent.mq.md b/ext/ai/agent.mq.md index 365b1ea..70c89d2 100644 --- a/ext/ai/agent.mq.md +++ b/ext/ai/agent.mq.md @@ -5,15 +5,15 @@ description: Thin agent framework — ctor, run, clear_history only. --- ## build_agent_context - - agent - - extra + + `agent` + + `extra` Internal: assemble prompt (user prompt, extra, tool list, source, call site, history, Marqdo skill). *`user_prompt` = > get value=`agent` key=user_prompt * -+ `user_prompt` +1. `user_prompt` *`up` = `user_prompt`* -+ * +2. * *`up` = None* *`tools` = > get value=`agent` key=tools * @@ -43,9 +43,9 @@ Internal: assemble prompt (user prompt, extra, tool list, source, call site, his **`p`** # agent - - model - - tools - - user_prompt + + `model` + + `tools` + + `user_prompt` *`id` = > host_agent_alloc * *`h` = > parse text={"_type":"agent"} * @@ -53,9 +53,9 @@ Internal: assemble prompt (user prompt, extra, tool list, source, call site, his *`h` = > map_set map=`h` key=model value=`model` * *`h` = > map_set map=`h` key=tools value=`tools` * -+ `user_prompt` +1. `user_prompt` *`h` = > map_set map=`h` key=user_prompt value=`user_prompt` * -+ * +2. * *`_` = 1* **`h`** @@ -67,7 +67,7 @@ Internal: assemble prompt (user prompt, extra, tool list, source, call site, his **** ## run - - extra + + `extra` *`ctx` = > build_agent_context agent=`self` extra=`extra` * *`id` = > get value=`self` key=id * @@ -86,9 +86,9 @@ Internal: assemble prompt (user prompt, extra, tool list, source, call site, his *`tool_name` = > at value=`parts` index=1 * *`tool_name` = > trim value=`tool_name` * -+ `head` == TOOL +1. `head` == TOOL *`allowed` = > host_tool_allowed tools=`tools` name=`tool_name` * - + `allowed` + 1. `allowed` *`tool_out` = > call_fn name=`tool_name` * *`tool_s` = > stringify value=`tool_out` * *`extra_s` = > stringify value=`extra` * @@ -100,9 +100,9 @@ Internal: assemble prompt (user prompt, extra, tool list, source, call site, his *`fp` = `fp` + `tool_s` * *`fp` = `fp` + . Reply to the user in one brief sentence. * *`reply` = > `model`.complete prompt=`fp` * - + * + 2. * *`reply` = Tool not allowed: `tool_name` * -+ * +2. * *`_` = 1* *`as_turn` = > parse text={"role":"assistant"} * diff --git a/ext/ai/llm.mq.md b/ext/ai/llm.mq.md index a360e68..b277e11 100644 --- a/ext/ai/llm.mq.md +++ b/ext/ai/llm.mq.md @@ -19,34 +19,34 @@ Construct an LLM handle from `OPENAI_*` / `MARQDO_LLM_*` (default base OpenAI v1 *`d` = > parse text={"base":"https://api.openai.com/v1","model":"gpt-4o-mini","suffix":"/chat/completions","bearer":"Bearer ","p1":"{\"model\":","p2":",\"messages\":[{\"role\":\"user\",\"content\":","p3":"}]}","h1":"{\"Authorization\":","h2":"}","a1":"{\"api_key\":","a2":",\"base_url\":","a3":",\"model\":","a4":",\"suffix\":","a5":",\"bearer\":","a6":",\"p1\":","a7":",\"p2\":","a8":",\"p3\":","a9":",\"h1\":","a10":",\"h2\":","a11":"}"} * *`api_key` = > env_get name=OPENAI_API_KEY * -+ `api_key` +1. `api_key` *`_k` = 1* -+ * +2. * *`api_key` = > env_get name=MARQDO_LLM_API_KEY * -+ `api_key` +3. `api_key` *`_k` = 1* -+ * +4. * > print text=ext/ai/llm: set OPENAI_API_KEY or MARQDO_LLM_API_KEY > exit code=1 *`base_url` = > env_get name=OPENAI_BASE_URL * -+ `base_url` +1. `base_url` *`_k` = 1* -+ * +2. * *`base_url` = > env_get name=MARQDO_LLM_BASE_URL * -+ `base_url` +3. `base_url` *`_k` = 1* -+ * +4. * *`base_url` = > get value=`d` key=base * *`model` = > env_get name=OPENAI_MODEL * -+ `model` +1. `model` *`_k` = 1* -+ * +2. * *`model` = > env_get name=MARQDO_LLM_MODEL * -+ `model` +3. `model` *`_k` = 1* -+ * +4. * *`model` = > get value=`d` key=model * *`q_key` = > quote text=`api_key` * @@ -81,7 +81,7 @@ Construct an LLM handle from `OPENAI_*` / `MARQDO_LLM_*` (default base OpenAI v1 **> parse text=`raw`** ## complete - - prompt + + `prompt` Chat completion using `self` / `自` handle fields. @@ -107,14 +107,14 @@ Chat completion using `self` / `自` handle fields. *`status` = > get value=`resp` key=status * *`raw` = > get value=`resp` key=body * -+ `status` == 200 +1. `status` == 200 *`data` = > parse text=`raw` * *`choices` = > get value=`data` key=choices * *`first` = > at value=`choices` index=0 * *`message` = > get value=`first` key=message * *`content` = > get value=`message` key=content * **`content`** -+ * +2. * > print text=ext/ai/llm: HTTP error > print text=`status` > print text=`raw` @@ -123,7 +123,7 @@ Chat completion using `self` / `自` handle fields. --- ## chat - - prompt + + `prompt` Alias for `complete`. diff --git a/ext/ai/大模型.mq.md b/ext/ai/大模型.mq.md index 2482415..a1e93f6 100644 --- a/ext/ai/大模型.mq.md +++ b/ext/ai/大模型.mq.md @@ -19,34 +19,34 @@ description: OpenAI 兼容大模型对象(中文)。导入 ext/ai/大模型. *`d` = > parse text={"base":"https://api.openai.com/v1","model":"gpt-4o-mini","suffix":"/chat/completions","bearer":"Bearer ","p1":"{\"model\":","p2":",\"messages\":[{\"role\":\"user\",\"content\":","p3":"}]}","h1":"{\"Authorization\":","h2":"}","a1":"{\"api_key\":","a2":",\"base_url\":","a3":",\"model\":","a4":",\"suffix\":","a5":",\"bearer\":","a6":",\"p1\":","a7":",\"p2\":","a8":",\"p3\":","a9":",\"h1\":","a10":",\"h2\":","a11":"}"} * *`api_key` = > 取环境 名=OPENAI_API_KEY * -+ `api_key` +1. `api_key` *`_k` = 1* -+ * +2. * *`api_key` = > 取环境 名=MARQDO_LLM_API_KEY * -+ `api_key` +3. `api_key` *`_k` = 1* -+ * +4. * > 打印 内容=ext/ai/大模型: 请设置 OPENAI_API_KEY 或 MARQDO_LLM_API_KEY > 退出 码=1 *`base_url` = > 取环境 名=OPENAI_BASE_URL * -+ `base_url` +1. `base_url` *`_k` = 1* -+ * +2. * *`base_url` = > 取环境 名=MARQDO_LLM_BASE_URL * -+ `base_url` +3. `base_url` *`_k` = 1* -+ * +4. * *`base_url` = > get value=`d` key=base * *`model` = > 取环境 名=OPENAI_MODEL * -+ `model` +1. `model` *`_k` = 1* -+ * +2. * *`model` = > 取环境 名=MARQDO_LLM_MODEL * -+ `model` +3. `model` *`_k` = 1* -+ * +4. * *`model` = > get value=`d` key=model * *`q_key` = > quote text=`api_key` * @@ -81,7 +81,7 @@ description: OpenAI 兼容大模型对象(中文)。导入 ext/ai/大模型. **> parse text=`raw`** ## 运行 - - 提示 + + `提示` 使用 `自` / `self` 句柄字段做聊天补全。 @@ -107,14 +107,14 @@ description: OpenAI 兼容大模型对象(中文)。导入 ext/ai/大模型. *`status` = > get value=`resp` key=status * *`raw` = > get value=`resp` key=body * -+ `status` == 200 +1. `status` == 200 *`data` = > parse text=`raw` * *`choices` = > get value=`data` key=choices * *`first` = > at value=`choices` index=0 * *`message` = > get value=`first` key=message * *`content` = > get value=`message` key=content * **`content`** -+ * +2. * > 打印 内容=ext/ai/大模型: HTTP 错误 > 打印 内容=`status` > 打印 内容=`raw` @@ -123,7 +123,7 @@ description: OpenAI 兼容大模型对象(中文)。导入 ext/ai/大模型. --- ## 聊天 - - 提示 + + `提示` `运行` 的别名。 diff --git a/ext/ai/智能体.mq.md b/ext/ai/智能体.mq.md index a31a8dc..5c430cf 100644 --- a/ext/ai/智能体.mq.md +++ b/ext/ai/智能体.mq.md @@ -5,15 +5,15 @@ description: 薄智能体框架 — 仅构造、执行、清空历史。 --- ## 构建上下文 - - 智能体 - - 额外信息 + + `智能体` + + `额外信息` 内部:组装提示(用户提示、额外信息、工具列表、源码、位置、历史、Marqdo skill)。 *`user_prompt` = > get value=`智能体` key=user_prompt * -+ `user_prompt` +1. `user_prompt` *`up` = `user_prompt`* -+ * +2. * *`up` = 空* *`tools` = > get value=`智能体` key=tools * @@ -43,9 +43,9 @@ description: 薄智能体框架 — 仅构造、执行、清空历史。 **`p`** # 智能体 - - 大模型 - - 工具 - - 用户提示信息 + + `大模型` + + `工具` + + `用户提示信息` *`id` = > host_agent_alloc * *`h` = > parse text={"_type":"智能体"} * @@ -53,9 +53,9 @@ description: 薄智能体框架 — 仅构造、执行、清空历史。 *`h` = > map_set map=`h` key=model value=`大模型` * *`h` = > map_set map=`h` key=tools value=`工具` * -+ `用户提示信息` +1. `用户提示信息` *`h` = > map_set map=`h` key=user_prompt value=`用户提示信息` * -+ * +2. * *`_` = 1* **`h`** @@ -67,7 +67,7 @@ description: 薄智能体框架 — 仅构造、执行、清空历史。 **** ## 执行 - - 额外信息 + + `额外信息` *`ctx` = > 构建上下文 智能体=`自` 额外信息=`额外信息` * *`id` = > get value=`自` key=id * @@ -86,9 +86,9 @@ description: 薄智能体框架 — 仅构造、执行、清空历史。 *`tool_name` = > at value=`parts` index=1 * *`tool_name` = > trim value=`tool_name` * -+ `head` == TOOL +1. `head` == TOOL *`allowed` = > host_tool_allowed tools=`tools` name=`tool_name` * - + `allowed` + 1. `allowed` *`tool_out` = > 调用 名=`tool_name` * *`tool_s` = > stringify value=`tool_out` * *`extra_s` = > stringify value=`额外信息` * @@ -100,9 +100,9 @@ description: 薄智能体框架 — 仅构造、执行、清空历史。 *`fp` = `fp` + `tool_s` * *`fp` = `fp` + . Reply to the user in one brief sentence. * *`reply` = > `model`.运行 提示=`fp` * - + * + 2. * *`reply` = Tool not allowed: `tool_name` * -+ * +2. * *`_` = 1* *`as_turn` = > parse text={"role":"assistant"} * diff --git a/lib/foreign.mq.md b/lib/foreign.mq.md index dc80693..9a1f5a9 100644 --- a/lib/foreign.mq.md +++ b/lib/foreign.mq.md @@ -4,19 +4,19 @@ description: Run bound code fences and inline sources via local interpreters --- ## set_cmd - - lang - - cmd + + `lang` + + `cmd` **> host_foreign_set_cmd lang=`lang` cmd=`cmd`** ## run - - code + + `code` **> host_foreign_run code=`code`** ## run_lang - - lang - - source + + `lang` + + `source` **> host_foreign_run_lang lang=`lang` source=`source`** diff --git a/lib/fs.mq.md b/lib/fs.mq.md index 883e6c0..78aca38 100644 --- a/lib/fs.mq.md +++ b/lib/fs.mq.md @@ -4,38 +4,38 @@ description: English filesystem wrappers --- ## read_text - - path + + `path` **> host_read_text path=`path`** ## write_text - - path - - text + + `path` + + `text` **> host_write_text path=`path` text=`text`** ## append_text - - path - - text + + `path` + + `text` **> host_append_text path=`path` text=`text`** ## exists - - path + + `path` **> host_exists path=`path`** ## list_dir - - path + + `path` **> host_list_dir path=`path`** ## make_dir - - path + + `path` **> host_make_dir path=`path`** ## remove - - path + + `path` **> host_remove path=`path`** diff --git a/lib/json.mq.md b/lib/json.mq.md index 93a9d49..e6d410e 100644 --- a/lib/json.mq.md +++ b/lib/json.mq.md @@ -4,40 +4,40 @@ description: JSON parse/stringify (shared EN/ZH import) --- ## parse - - text + + `text` **> host_json_parse text=`text`** ## stringify - - value + + `value` **> host_json_stringify value=`value`** ## get - - value - - key + + `value` + + `key` **> host_json_get value=`value` key=`key`** ## keys - - value + + `value` **> host_json_keys value=`value`** ## quote - - text + + `text` **> host_json_quote text=`text`** ## set - - map - - key - - value + + `map` + + `key` + + `value` **> host_map_set map=`map` key=`key` value=`value`** ## append - - list - - item + + `list` + + `item` **> host_list_append list=`list` item=`item`** diff --git a/lib/math.mq.md b/lib/math.mq.md index 977073c..e3fb91f 100644 --- a/lib/math.mq.md +++ b/lib/math.mq.md @@ -12,114 +12,114 @@ description: High-school math — num, random, formula, plot **> host_e** ## num - - value + + `value` **> host_num value=`value`** ## add - - a - - b + + `a` + + `b` **> host_math_add a=`a` b=`b`** ## sub - - a - - b + + `a` + + `b` **> host_math_sub a=`a` b=`b`** ## mul - - a - - b + + `a` + + `b` **> host_math_mul a=`a` b=`b`** ## div - - a - - b + + `a` + + `b` **> host_math_div a=`a` b=`b`** ## pow - - a - - b + + `a` + + `b` **> host_math_pow a=`a` b=`b`** ## neg - - value + + `value` **> host_math_neg value=`value`** ## sin - - value + + `value` **> host_math_sin value=`value`** ## cos - - value + + `value` **> host_math_cos value=`value`** ## tan - - value + + `value` **> host_math_tan value=`value`** ## asin - - value + + `value` **> host_math_asin value=`value`** ## acos - - value + + `value` **> host_math_acos value=`value`** ## atan - - value + + `value` **> host_math_atan value=`value`** ## sqrt - - value + + `value` **> host_math_sqrt value=`value`** ## abs - - value + + `value` **> host_math_abs value=`value`** ## ln - - value + + `value` **> host_math_ln value=`value`** ## exp - - value + + `value` **> host_math_exp value=`value`** ## floor - - value + + `value` **> host_math_floor value=`value`** ## ceil - - value + + `value` **> host_math_ceil value=`value`** ## min - - a - - b + + `a` + + `b` **> host_math_min a=`a` b=`b`** ## max - - a - - b + + `a` + + `b` **> host_math_max a=`a` b=`b`** @@ -128,73 +128,73 @@ description: High-school math — num, random, formula, plot **> host_random** ## random_int - - min - - max + + `min` + + `max` **> host_random_int min=`min` max=`max`** ## seed - - value + + `value` **> host_seed value=`value`** ## formula - - text + + `text` **> host_formula value=`text`** ## simplify - - formula + + `formula` **> host_simplify value=`formula`** ## expand - - formula + + `formula` **> host_expand value=`formula`** ## diff - - formula - - var + + `formula` + + `var` **> host_diff formula=`formula` var=`var`** ## subs - - formula - - var - - value + + `formula` + + `var` + + `value` **> host_subs formula=`formula` var=`var` value=`value`** ## eval - - formula - - var - - value + + `formula` + + `var` + + `value` **> host_eval formula=`formula` var=`var` value=`value`** ## solve - - formula - - var + + `formula` + + `var` **> host_solve formula=`formula` var=`var`** ## plot - - formula - - var - - min - - max + + `formula` + + `var` + + `min` + + `max` **> host_plot formula=`formula` var=`var` min=`min` max=`max`** ## plot_points - - xs - - ys + + `xs` + + `ys` **> host_plot_points xs=`xs` ys=`ys`** ## plot_conic - - kind - - a + + `kind` + + `a` **> host_plot_conic kind=`kind` a=`a`** diff --git a/lib/net.mq.md b/lib/net.mq.md index d022f8b..e1fa6b3 100644 --- a/lib/net.mq.md +++ b/lib/net.mq.md @@ -4,29 +4,29 @@ description: English HTTP(S) wrappers. Optional headers / content_type via host --- ## http_get - - url + + `url` HTTPS supported. Optional named arg `headers=` (map). **> host_http_get url=`url`** ## http_post - - url - - body + + `url` + + `body` Default content type is JSON. Optional `content_type=` / `headers=` (map). **> host_http_post url=`url` body=`body`** ## http_request - - method - - url + + `method` + + `url` Optional `body=` / `content_type=` / `headers=`. **> host_http_request method=`method` url=`url`** ## url_encode - - text + + `text` **> host_url_encode text=`text`** diff --git a/lib/plugin.mq.md b/lib/plugin.mq.md index 755445b..b0bd0f1 100644 --- a/lib/plugin.mq.md +++ b/lib/plugin.mq.md @@ -4,7 +4,7 @@ description: Load optional native ABI plugins (.dll / .so / .dylib) --- ## load - - path + + `path` **> host_plugin_load path=`path`** diff --git a/lib/subtask.mq.md b/lib/subtask.mq.md new file mode 100644 index 0000000..9120452 --- /dev/null +++ b/lib/subtask.mq.md @@ -0,0 +1,28 @@ +--- +title: lib/subtask +description: OS subprocess subtasks (parent exit kills children) +--- + +## spawn + + `path` + +**> host_subtask_spawn path=`path`** + +## poll + + `id` + +**> host_subtask_poll id=`id`** + +## wait + + `id` + +**> host_subtask_join id=`id`** + +## kill + + `id` + +**> host_subtask_kill id=`id`** + +## wait_all + +**> host_subtask_wait_all** diff --git a/lib/sys.mq.md b/lib/sys.mq.md index f0c6df4..dd60ec7 100644 --- a/lib/sys.mq.md +++ b/lib/sys.mq.md @@ -4,13 +4,13 @@ description: English system wrappers (load_dotenv accepts optional path via host --- ## env_get - - name + + `name` **> host_env_get name=`name`** ## env_set - - name - - value + + `name` + + `value` **> host_env_set name=`name` value=`value`** @@ -29,11 +29,11 @@ Load `.env` (optional named arg `path=`). Existing process env is not overridden **> host_cwd** ## exit - - code + + `code` **> host_exit code=`code`** ## exec - - cmd + + `cmd` **> host_exec cmd=`cmd`** diff --git a/lib/table.mq.md b/lib/table.mq.md index dddadb6..a24f3a0 100644 --- a/lib/table.mq.md +++ b/lib/table.mq.md @@ -4,12 +4,12 @@ description: English table helpers over len / at --- ## rows - - xs + + `xs` **> len `xs`** ## row_at - - xs - - i + + `xs` + + `i` **> at value=`xs` index=`i`** diff --git a/lib/text.mq.md b/lib/text.mq.md index 8f4386e..760194a 100644 --- a/lib/text.mq.md +++ b/lib/text.mq.md @@ -4,18 +4,18 @@ description: English text helpers over trim / split / join --- ## str_trim - - s + + `s` **> trim `s`** ## str_split - - s - - sep + + `s` + + `sep` **> split value=`s` sep=`sep`** ## str_join - - xs - - sep + + `xs` + + `sep` **> join value=`xs` sep=`sep`** diff --git a/lib/time.mq.md b/lib/time.mq.md index 200e6c7..9507403 100644 --- a/lib/time.mq.md +++ b/lib/time.mq.md @@ -12,18 +12,18 @@ description: English time wrappers **> host_now_ms** ## format - - unix - - pattern + + `unix` + + `pattern` **> host_format_time unix=`unix` pattern=`pattern`** ## sleep_ms - - ms + + `ms` **> host_sleep_ms ms=`ms`** ## parse - - text - - pattern + + `text` + + `pattern` **> host_parse_time text=`text` pattern=`pattern`** diff --git a/lib/writeback.mq.md b/lib/writeback.mq.md new file mode 100644 index 0000000..446f5f2 --- /dev/null +++ b/lib/writeback.mq.md @@ -0,0 +1,32 @@ +--- +title: lib/writeback +description: Persist run output in .mq.md (Jupyter-style writeback) +--- + +## record + + `value` + + `at_end`=False + +Write `value` to `` in the entry file. Default: insert or replace the block immediately below the call; `at_end=true` appends a single block at EOF. + +**> host_writeback_record value=`value` at_end=`at_end`** + +## get + + `at_end`=False + +Read persisted output for the current call site (adjacent block), or the EOF block when `at_end=true`. + +**> host_writeback_get at_end=`at_end`** + +## clear + + `at_end`=False + +Remove the adjacent or EOF output block. + +**> host_writeback_clear at_end=`at_end`** + +## list + +List all output blocks in the entry file. + +**> host_writeback_list** diff --git a/lib/外联.mq.md b/lib/外联.mq.md index 8aec62a..fd1ac5e 100644 --- a/lib/外联.mq.md +++ b/lib/外联.mq.md @@ -4,19 +4,19 @@ description: 通过本机解释器运行绑定的代码围栏与内联源码 --- ## 设置命令 - - 语言 - - 命令 + + `语言` + + `命令` **> host_foreign_set_cmd lang=`语言` cmd=`命令`** ## 运行 - - 代码 + + `代码` **> host_foreign_run code=`代码`** ## 按语言运行 - - 语言 - - 源码 + + `语言` + + `源码` **> host_foreign_run_lang lang=`语言` source=`源码`** diff --git a/lib/子任务.mq.md b/lib/子任务.mq.md new file mode 100644 index 0000000..7a336d8 --- /dev/null +++ b/lib/子任务.mq.md @@ -0,0 +1,28 @@ +--- +title: lib/子任务 +description: OS 子进程子任务(父进程结束则子进程结束) +--- + +## 启动 + + `路径` + +**> host_subtask_spawn path=`路径`** + +## 探测 + + `id` + +**> host_subtask_poll id=`id`** + +## 等待 + + `id` + +**> host_subtask_join id=`id`** + +## 终止 + + `id` + +**> host_subtask_kill id=`id`** + +## 等待全部 + +**> host_subtask_wait_all** diff --git a/lib/插件.mq.md b/lib/插件.mq.md index 92146a0..d7a5695 100644 --- a/lib/插件.mq.md +++ b/lib/插件.mq.md @@ -4,7 +4,7 @@ description: 加载可选原生 ABI 插件(.dll / .so / .dylib) --- ## 加载 - - 路径 + + `路径` **> host_plugin_load path=`路径`** diff --git a/lib/数学.mq.md b/lib/数学.mq.md index 1ff4e8e..979f587 100644 --- a/lib/数学.mq.md +++ b/lib/数学.mq.md @@ -12,114 +12,114 @@ description: 高中数学 — 数值、随机、公式、作图 **> host_e** ## 数 - - value + + `value` **> host_num value=`value`** ## 加 - - a - - b + + `a` + + `b` **> host_math_add a=`a` b=`b`** ## 减 - - a - - b + + `a` + + `b` **> host_math_sub a=`a` b=`b`** ## 乘 - - a - - b + + `a` + + `b` **> host_math_mul a=`a` b=`b`** ## 除 - - a - - b + + `a` + + `b` **> host_math_div a=`a` b=`b`** ## 幂 - - a - - b + + `a` + + `b` **> host_math_pow a=`a` b=`b`** ## 负 - - value + + `value` **> host_math_neg value=`value`** ## 正弦 - - value + + `value` **> host_math_sin value=`value`** ## 余弦 - - value + + `value` **> host_math_cos value=`value`** ## 正切 - - value + + `value` **> host_math_tan value=`value`** ## 反正弦 - - value + + `value` **> host_math_asin value=`value`** ## 反余弦 - - value + + `value` **> host_math_acos value=`value`** ## 反正切 - - value + + `value` **> host_math_atan value=`value`** ## 平方根 - - value + + `value` **> host_math_sqrt value=`value`** ## 绝对值 - - value + + `value` **> host_math_abs value=`value`** ## 对数 - - value + + `value` **> host_math_ln value=`value`** ## 指数 - - value + + `value` **> host_math_exp value=`value`** ## 向下取整 - - value + + `value` **> host_math_floor value=`value`** ## 向上取整 - - value + + `value` **> host_math_ceil value=`value`** ## 最小 - - a - - b + + `a` + + `b` **> host_math_min a=`a` b=`b`** ## 最大 - - a - - b + + `a` + + `b` **> host_math_max a=`a` b=`b`** @@ -128,73 +128,73 @@ description: 高中数学 — 数值、随机、公式、作图 **> host_random** ## 随机整数 - - min - - max + + `min` + + `max` **> host_random_int min=`min` max=`max`** ## 设种子 - - value + + `value` **> host_seed value=`value`** ## 公式 - - text + + `text` **> host_formula value=`text`** ## 化简 - - formula + + `formula` **> host_simplify value=`formula`** ## 展开 - - formula + + `formula` **> host_expand value=`formula`** ## 求导 - - formula - - var + + `formula` + + `var` **> host_diff formula=`formula` var=`var`** ## 代入 - - formula - - var - - value + + `formula` + + `var` + + `value` **> host_subs formula=`formula` var=`var` value=`value`** ## 求值 - - formula - - var - - value + + `formula` + + `var` + + `value` **> host_eval formula=`formula` var=`var` value=`value`** ## 求解 - - formula - - var + + `formula` + + `var` **> host_solve formula=`formula` var=`var`** ## 绘图 - - formula - - var - - min - - max + + `formula` + + `var` + + `min` + + `max` **> host_plot formula=`formula` var=`var` min=`min` max=`max`** ## 绘点列 - - xs - - ys + + `xs` + + `ys` **> host_plot_points xs=`xs` ys=`ys`** ## 绘圆锥 - - kind - - a + + `kind` + + `a` **> host_plot_conic kind=`kind` a=`a`** diff --git a/lib/文件.mq.md b/lib/文件.mq.md index 109f2a5..1505148 100644 --- a/lib/文件.mq.md +++ b/lib/文件.mq.md @@ -4,38 +4,38 @@ description: 中文文件系统包装 --- ## 读文本 - - 路径 + + `路径` **> host_read_text path=`路径`** ## 写文本 - - 路径 - - 内容 + + `路径` + + `内容` **> host_write_text path=`路径` text=`内容`** ## 追加文本 - - 路径 - - 内容 + + `路径` + + `内容` **> host_append_text path=`路径` text=`内容`** ## 存在 - - 路径 + + `路径` **> host_exists path=`路径`** ## 列目录 - - 路径 + + `路径` **> host_list_dir path=`路径`** ## 建目录 - - 路径 + + `路径` **> host_make_dir path=`路径`** ## 删除 - - 路径 + + `路径` **> host_remove path=`路径`** diff --git a/lib/文本.mq.md b/lib/文本.mq.md index 3a4c9fd..8e3e482 100644 --- a/lib/文本.mq.md +++ b/lib/文本.mq.md @@ -4,18 +4,18 @@ description: 中文文本库:去空白 / 拆分 / 拼接 --- ## 去空白 - - s + + `s` **> trim `s`** ## 拆分 - - s - - sep + + `s` + + `sep` **> split value=`s` sep=`sep`** ## 拼接 - - xs - - sep + + `xs` + + `sep` **> join value=`xs` sep=`sep`** diff --git a/lib/时间.mq.md b/lib/时间.mq.md index 7047d19..c75ddf3 100644 --- a/lib/时间.mq.md +++ b/lib/时间.mq.md @@ -12,18 +12,18 @@ description: 中文时间包装 **> host_now_ms** ## 格式化 - - 秒 - - 格式 + + `秒` + + `格式` **> host_format_time unix=`秒` pattern=`格式`** ## 睡眠毫秒 - - 毫秒 + + `毫秒` **> host_sleep_ms ms=`毫秒`** ## 解析时间 - - 内容 - - 格式 + + `内容` + + `格式` **> host_parse_time text=`内容` pattern=`格式`** diff --git a/lib/系统.mq.md b/lib/系统.mq.md index d75a562..2ba7a41 100644 --- a/lib/系统.mq.md +++ b/lib/系统.mq.md @@ -4,13 +4,13 @@ description: 中文系统包装(加载环境 可选 路径=) --- ## 取环境 - - 名 + + `名` **> host_env_get name=`名`** ## 设环境 - - 名 - - 值 + + `名` + + `值` **> host_env_set name=`名` value=`值`** @@ -29,11 +29,11 @@ description: 中文系统包装(加载环境 可选 路径=) **> host_cwd** ## 退出 - - 码 + + `码` **> host_exit code=`码`** ## 执行 - - 命令 + + `命令` **> host_exec cmd=`命令`** diff --git a/lib/网络.mq.md b/lib/网络.mq.md index 4cd9952..b501a95 100644 --- a/lib/网络.mq.md +++ b/lib/网络.mq.md @@ -4,29 +4,29 @@ description: 中文 HTTP(S) 包装。可选 headers / content_type 经宿主别 --- ## 获取 - - 地址 + + `地址` 支持 HTTPS。可选具名实参 `headers=`(映射)。 **> host_http_get url=`地址`** ## 提交 - - 地址 - - 内容 + + `地址` + + `内容` 默认 Content-Type 为 JSON。可选 `content_type=` / `headers=`。 **> host_http_post url=`地址` body=`内容`** ## 请求 - - 方法 - - 地址 + + `方法` + + `地址` 可选 `body=` / `content_type=` / `headers=`。 **> host_http_request method=`方法` url=`地址`** ## 编码地址 - - 内容 + + `内容` **> host_url_encode text=`内容`** diff --git a/lib/自写回.mq.md b/lib/自写回.mq.md new file mode 100644 index 0000000..039f4ae --- /dev/null +++ b/lib/自写回.mq.md @@ -0,0 +1,30 @@ +--- +title: lib/自写回 +description: 将运行结果写回 .mq.md(Jupyter 式自写回) +--- + +## 写回 + + `值` + + `末尾`=False + +在入口文件中写入 ``。默认在调用行下方插入或替换;`末尾=true` 时在文件末尾保留单块。 + +**> host_writeback_record value=`值` at_end=`末尾`** + +## 取 + + `末尾`=False + +读取当前调用处紧邻块,或 `末尾=true` 时读取文件末尾块。 + +**> host_writeback_get at_end=`末尾`** + +## 清除 + + `末尾`=False + +删除紧邻块或末尾块。 + +**> host_writeback_clear at_end=`末尾`** + +## 列出 + +**> host_writeback_list** diff --git a/lib/表.mq.md b/lib/表.mq.md index fa743be..9623e30 100644 --- a/lib/表.mq.md +++ b/lib/表.mq.md @@ -4,12 +4,12 @@ description: 中文表库:行数 / 取行 --- ## 行数 - - xs + + `xs` **> len `xs`** ## 取行 - - xs - - i + + `xs` + + `i` **> at value=`xs` index=`i`** diff --git a/man-doc/README.md b/man-doc/README.md new file mode 100644 index 0000000..e092ae5 --- /dev/null +++ b/man-doc/README.md @@ -0,0 +1,39 @@ +--- +title: 人工文档 +description: 这是人工写的文档,禁止机器修改 +--- + +对于marqdo这个项目,详细的语法定义为: +--- + +#标识对象,#main不算特殊这是一个项目的传统入口可以视为是一个对象。 +--- +##、### 、####等标识函数,不同数目表示从属关系,例如###是##函数的子函数,作用域不超过 +这个函数,使用-表示函数的变量名 +**** 空返回(None),并结束本函数体 +--- +无标记行表示注释信息,对于无标记行应该这么约定不是说开头没有符合不然就会出现: + +**强调信息**是什么什么 + +上面应该是一个注释 +--- +程序语言使用*程序*也就是斜体表示 +--- +`变量名`表示变量 +--- +> 表示引用函数 +--- +有序列表表示分支语句 +--- +无序列表表示循环语句 +--- +公式由数学库渲染 +--- +代码片段由外联库渲染 +--- +添加一个新的标准库,自写回标准库,自写回的内容必须使用包裹,这个不会被md识别, +但是这个可以被marqdo识别,当作提示信息或生成结果的一律表示,markdo view要能渲染,以某种方式 +--- +添加一个新的标准库,子任务库,能够自由的运行子任务,现在的调用还是顺序化的,但是子任务允许多个 +进程式的调用,子任务库将成为marqdo的护城河项目,子任务要依赖于父任务,父任务结束子任务一定结束,防止出现问题 diff --git a/man-test/index.mq.md b/man-test/index.mq.md new file mode 100644 index 0000000..be1bd54 --- /dev/null +++ b/man-test/index.mq.md @@ -0,0 +1,20 @@ +--- +title: 手工构造的测试样例 +description: AI禁止更改 +--- + +# main + +这是人工构建的用于测试的样例 + +`测试目录` = +|测试文件夹| +|-----| +|structure| +|keyword| +|lib| + + +- [`测试文件夹`](`测试目录`) + > 打印 `测试文件夹` + diff --git a/man-test/keyword/bool.mq.md b/man-test/keyword/bool.mq.md new file mode 100644 index 0000000..fdbb9b0 --- /dev/null +++ b/man-test/keyword/bool.mq.md @@ -0,0 +1,14 @@ +--- +title: 手工构造的测试样例 +description: AI禁止更改 +--- + +# main + +*`a` = True* +*`b` = False* + +1. `a` and not `b` + > print text=ok +2. * + > print text=fail \ No newline at end of file diff --git a/man-test/keyword/input.mq.md b/man-test/keyword/input.mq.md new file mode 100644 index 0000000..4bafdb0 --- /dev/null +++ b/man-test/keyword/input.mq.md @@ -0,0 +1,12 @@ +--- +title: 手工构造的测试样例 +description: AI禁止更改 +--- + +# main + +测试输入 + +*`name`=> input "你叫什么名字\n"* + +> print `name` \ No newline at end of file diff --git a/man-test/keyword/print.mq.md b/man-test/keyword/print.mq.md new file mode 100644 index 0000000..ae899e8 --- /dev/null +++ b/man-test/keyword/print.mq.md @@ -0,0 +1,10 @@ +--- +title: 手工构造的测试样例 +description: AI禁止更改 +--- + +# main + +测试输出 + +> print 欢迎你 \ No newline at end of file diff --git a/man-test/lib/math.mq.md b/man-test/lib/math.mq.md new file mode 100644 index 0000000..e81b3c7 --- /dev/null +++ b/man-test/lib/math.mq.md @@ -0,0 +1,33 @@ +--- +title: 手工构造的测试样例 +description: AI禁止更改 +> lib/math.mq.md +--- + +# main + +`f` = +$$ +x^2 + 2 +$$ + +`f` = +$$ +x^2 - 2 +$$ + +*`ty` = > type `f` * + +> print text=`ty` + +*`df` = > diff formula=`f` var=x * + +> print text=`df` + +*`roots` = > solve formula=`f` var=x * + +> print text=`roots` + +*`y` = > eval formula=`f` var=x value=3 * + +> print text=`y` \ No newline at end of file diff --git a/man-test/lib/writeback.mq.md b/man-test/lib/writeback.mq.md new file mode 100644 index 0000000..3bbc370 --- /dev/null +++ b/man-test/lib/writeback.mq.md @@ -0,0 +1,23 @@ +--- +title: 手工构造的测试样例 +description: AI禁止更改 +> lib/writeback.mq.md +--- + +# main + +测试写回库 + +*`name`=>input "你叫什么名字?\n"* + +> record `name` + + + + + + + + diff --git a/man-test/structure/branch.mq.md b/man-test/structure/branch.mq.md new file mode 100644 index 0000000..c8db2e3 --- /dev/null +++ b/man-test/structure/branch.mq.md @@ -0,0 +1,15 @@ +--- +title: 手工构造的测试样例 +description: AI禁止更改 +--- + +# main + +测试分支语句 + +* `bool_value` = True * + +1. `bool_value` == True + > print True +2. * + > print False \ No newline at end of file diff --git a/man-test/structure/loop.mq.md b/man-test/structure/loop.mq.md new file mode 100644 index 0000000..933f1ef --- /dev/null +++ b/man-test/structure/loop.mq.md @@ -0,0 +1,15 @@ +--- +title: 手工构造的测试样例 +description: AI禁止更改 +--- + +# main + +测试循环语句语句 + +*`n`=0* + +- `n` < 42 + `n`=`n`+1 + +> print `n` \ No newline at end of file diff --git a/public/00-welcome.mq.md b/public/00-welcome.mq.md index 5447b42..1a3a621 100644 --- a/public/00-welcome.mq.md +++ b/public/00-welcome.mq.md @@ -24,7 +24,7 @@ Named args can include spaces: > greet who=marqdo user ## greet - - who + + `who` > print text=Welcome, `who`! diff --git a/public/00-欢迎.mq.md b/public/00-欢迎.mq.md index 01f1fdb..d7ed997 100644 --- a/public/00-欢迎.mq.md +++ b/public/00-欢迎.mq.md @@ -24,7 +24,7 @@ English docs: [`00-welcome.mq.md`](00-welcome.mq.md) (English prose and English > 问候 谁=marqdo user ## 问候 - - 谁 + + `谁` > 打印 内容=欢迎,`谁`! diff --git a/public/keywords/bool-logic.mq.md b/public/keywords/bool-logic.mq.md index 276a126..e19c9fb 100644 --- a/public/keywords/bool-logic.mq.md +++ b/public/keywords/bool-logic.mq.md @@ -10,14 +10,14 @@ Keywords: `True`, `False`, `None`, and `and` / `or` / `not`. *`a` = True* *`b` = False* -+ `a` and not `b` +1. `a` and not `b` > print text=ok -+ * +2. * > print text=fail *`probe` = 1* -+ None +1. None > print text=none-truthy -+ * +2. * > print text=none-falsy diff --git a/public/keywords/布尔逻辑.mq.md b/public/keywords/布尔逻辑.mq.md index 9211cc2..751e36e 100644 --- a/public/keywords/布尔逻辑.mq.md +++ b/public/keywords/布尔逻辑.mq.md @@ -10,14 +10,14 @@ description: 真 / 假 / 空 与 且 / 或 / 非 *`a` = 真* *`b` = 假* -+ `a` 且 非 `b` +1. `a` 且 非 `b` > 打印 内容=通过 -+ * +2. * > 打印 内容=失败 *`probe` = 1* -+ 空 +1. 空 > 打印 内容=空为真 -+ * +2. * > 打印 内容=空为假 diff --git a/public/stdlib/fs.mq.md b/public/stdlib/fs.mq.md index f9ad20d..89fa3ef 100644 --- a/public/stdlib/fs.mq.md +++ b/public/stdlib/fs.mq.md @@ -12,7 +12,7 @@ Bare path words must not contain a slash character (parsed as division). Prefer *`ok` = > exists path=demo.txt * -+ `ok` +1. `ok` > print text=demo-present -+ * +2. * > print text=demo-missing diff --git a/public/stdlib/plugin.mq.md b/public/stdlib/plugin.mq.md index 9c0145c..c7c31ae 100644 --- a/public/stdlib/plugin.mq.md +++ b/public/stdlib/plugin.mq.md @@ -12,7 +12,7 @@ Import lib/plugin.mq.md. Functions: load(path), unload(), list(). After load, re *`n` = > len `names` * -+ `n` >= 0 +1. `n` >= 0 > print text=plugin-ok -+ * +2. * > print text=plugin-bad diff --git a/public/stdlib/sys.mq.md b/public/stdlib/sys.mq.md index 84c8386..2e28057 100644 --- a/public/stdlib/sys.mq.md +++ b/public/stdlib/sys.mq.md @@ -12,7 +12,7 @@ Import lib/sys.mq.md. Functions: env_get, env_set, load_dotenv(optional path), a *`n` = > len `d` * -+ `n` > 0 +1. `n` > 0 > print text=cwd-ok -+ * +2. * > print text=cwd-empty diff --git a/public/stdlib/插件.mq.md b/public/stdlib/插件.mq.md index c18b091..1dbbbaa 100644 --- a/public/stdlib/插件.mq.md +++ b/public/stdlib/插件.mq.md @@ -12,7 +12,7 @@ description: 加载可选共享库(.dll / .so / .dylib) *`n` = > 长度 值=`names` * -+ `n` >= 0 +1. `n` >= 0 > 打印 内容=插件就绪 -+ * +2. * > 打印 内容=插件异常 diff --git a/public/stdlib/文件.mq.md b/public/stdlib/文件.mq.md index bb529e1..fbc2615 100644 --- a/public/stdlib/文件.mq.md +++ b/public/stdlib/文件.mq.md @@ -12,7 +12,7 @@ description: 沙箱内读写文本 *`ok` = > 存在 路径=demo.txt * -+ `ok` +1. `ok` > 打印 内容=有演示文件 -+ * +2. * > 打印 内容=无演示文件 diff --git a/public/stdlib/系统.mq.md b/public/stdlib/系统.mq.md index c9e398e..0d99b2e 100644 --- a/public/stdlib/系统.mq.md +++ b/public/stdlib/系统.mq.md @@ -12,7 +12,7 @@ description: 环境变量、dotenv、工作目录、参数、退出、执行 *`n` = > 长度 值=`d` * -+ `n` > 0 +1. `n` > 0 > 打印 内容=工作目录就绪 -+ * +2. * > 打印 内容=工作目录空 diff --git a/public/structure/02-function.mq.md b/public/structure/02-function.mq.md index 9188bc6..07b933a 100644 --- a/public/structure/02-function.mq.md +++ b/public/structure/02-function.mq.md @@ -12,6 +12,6 @@ Call with `>` and named args `param=value`: > greet who=World ## greet - - who + + `who` > print text=Hello `who`! diff --git a/public/structure/02-函数.mq.md b/public/structure/02-函数.mq.md index 973a605..6020840 100644 --- a/public/structure/02-函数.mq.md +++ b/public/structure/02-函数.mq.md @@ -12,6 +12,6 @@ description: `#` 定义函数;`>` 调用;`-` 列出参数名 > 问候 谁=世界 ## 问候 - - 谁 + + `谁` > 打印 内容=你好 `谁`! diff --git a/public/structure/03-positional-call.mq.md b/public/structure/03-positional-call.mq.md index 77bec9c..84493c3 100644 --- a/public/structure/03-positional-call.mq.md +++ b/public/structure/03-positional-call.mq.md @@ -14,6 +14,6 @@ Named form still works: > greet who=World ## greet - - who + + `who` > print text=Hello `who`! diff --git a/public/structure/03-位置调用.mq.md b/public/structure/03-位置调用.mq.md index 4cb94ff..cf41d96 100644 --- a/public/structure/03-位置调用.mq.md +++ b/public/structure/03-位置调用.mq.md @@ -14,6 +14,6 @@ description: 按参数声明顺序绑定;具名写法仍然可用 > 问候 谁=世界 ## 问候 - - 谁 + + `谁` > 打印 内容=你好 `谁`! diff --git a/public/structure/04-branch.mq.md b/public/structure/04-branch.mq.md index 4f5d797..d2f906e 100644 --- a/public/structure/04-branch.mq.md +++ b/public/structure/04-branch.mq.md @@ -9,9 +9,9 @@ Italic lines are statements. Branches use `+`; a head that is only `*` is the el *`x` = 0* -+ `x` > 0 +1. `x` > 0 > print text=positive -+ `x` < 0 +2. `x` < 0 > print text=negative -+ * +3. * > print text=zero diff --git a/public/structure/04-分支.mq.md b/public/structure/04-分支.mq.md index d1504fa..6c14b31 100644 --- a/public/structure/04-分支.mq.md +++ b/public/structure/04-分支.mq.md @@ -9,9 +9,9 @@ description: `+` 各臂;单独的 `*` 臂为否则 *`x` = 0* -+ `x` > 0 +1. `x` > 0 > 打印 内容=正数 -+ `x` < 0 +2. `x` < 0 > 打印 内容=负数 -+ * +3. * > 打印 内容=零 diff --git a/public/structure/05-loop.mq.md b/public/structure/05-loop.mq.md index 5541d9a..498394e 100644 --- a/public/structure/05-loop.mq.md +++ b/public/structure/05-loop.mq.md @@ -24,5 +24,5 @@ Walk a table (tables are collections): | apple | | pear | -- [fruit](basket) +- [`fruit`](`basket`) > print text=today `fruit` diff --git a/public/structure/05-循环.mq.md b/public/structure/05-循环.mq.md index c8fac8a..af0b6fc 100644 --- a/public/structure/05-循环.mq.md +++ b/public/structure/05-循环.mq.md @@ -24,5 +24,5 @@ description: 条件循环与表遍历 | 苹果 | | 梨 | -- [水果](篮子) +- [`水果`](`篮子`) > 打印 内容=今天 `水果` diff --git a/public/structure/06-collection.mq.md b/public/structure/06-collection.mq.md index d732be2..39f32a0 100644 --- a/public/structure/06-collection.mq.md +++ b/public/structure/06-collection.mq.md @@ -15,5 +15,5 @@ A Markdown table is a collection; loop to read each row. | pear | | peach | -- [fruit](basket) +- [`fruit`](`basket`) > print text=`fruit` diff --git a/public/structure/06-集合.mq.md b/public/structure/06-集合.mq.md index 5686d81..07f9864 100644 --- a/public/structure/06-集合.mq.md +++ b/public/structure/06-集合.mq.md @@ -15,5 +15,5 @@ Markdown 表是集合;用循环读每一行。 | 梨 | | 桃 | -- [水果](篮子) +- [`水果`](`篮子`) > 打印 内容=`水果` diff --git a/public/structure/import/utils.mq.md b/public/structure/import/utils.mq.md index f9e5226..a25423c 100644 --- a/public/structure/import/utils.mq.md +++ b/public/structure/import/utils.mq.md @@ -4,11 +4,11 @@ description: Imported by main; bold is a return value --- ## add_one - - n + + `n` **`n` + 1** ## greet - - who + + `who` > print text=Hello, `who`! diff --git a/public/structure/import/工具.mq.md b/public/structure/import/工具.mq.md index deb6091..2cda1b4 100644 --- a/public/structure/import/工具.mq.md +++ b/public/structure/import/工具.mq.md @@ -4,11 +4,11 @@ description: 被 main 导入;粗体为返回值 --- ## 加一 - - n + + `n` **`n` + 1** ## 问候 - - 谁 + + `谁` > 打印 内容=你好,`谁`! diff --git a/scripts/migrate-branch-ordered.py b/scripts/migrate-branch-ordered.py new file mode 100644 index 0000000..9633305 --- /dev/null +++ b/scripts/migrate-branch-ordered.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Migrate branch arms: + cond -> N. cond (params + `name` unchanged).""" +from __future__ import annotations + +import re +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SKIP_DIRS = {"target", ".git", "node_modules"} + +PARAM_LINE = re.compile(r"^(\s{4,})\+ `([^`]+)`(=.*)?\s*$") +ORDERED = re.compile(r"^(\s*)(\d+)\.\s+(.*)$") +PLUS_BRANCH = re.compile(r"^(\s*)\+ (.+)$") + + +def migrate_text(text: str) -> str: + lines = text.splitlines(keepends=True) + out: list[str] = [] + arm = 0 + for line in lines: + raw = line.rstrip("\n\r") + end = line[len(raw) :] + if not raw.strip(): + arm = 0 + out.append(line) + continue + if PARAM_LINE.match(raw): + arm = 0 + out.append(line) + continue + m = PLUS_BRANCH.match(raw) + if m: + arm += 1 + indent, rest = m.groups() + out.append(f"{indent}{arm}. {rest}{end}") + continue + om = ORDERED.match(raw) + if om: + arm = int(om.group(2)) + out.append(line) + continue + stripped = raw.lstrip() + indent = raw[: len(raw) - len(stripped)] + if indent == 0 and ( + stripped.startswith("#") + or stripped.startswith(">") + or (stripped.startswith("*") and stripped.endswith("*")) + or stripped.startswith("`") + or stripped.startswith("|") + or stripped.startswith("---") + ): + arm = 0 + out.append(line) + return "".join(out) + + +def should_skip(path: Path) -> bool: + return any(part in SKIP_DIRS for part in path.parts) + + +def main() -> int: + changed = 0 + for path in sorted(ROOT.rglob("*.mq.md")): + if should_skip(path): + continue + text = path.read_text(encoding="utf-8") + new_text = migrate_text(text) + if new_text != text: + path.write_text(new_text, encoding="utf-8") + print(path.relative_to(ROOT)) + changed += 1 + print(f"migrated {changed} files") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/migrate-v02-syntax.py b/scripts/migrate-v02-syntax.py new file mode 100644 index 0000000..d56380f --- /dev/null +++ b/scripts/migrate-v02-syntax.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""One-shot migrate v0.2: params + `name`, foreach [`i`](`xs`).""" +from __future__ import annotations + +import re +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SKIP_DIRS = {"man-test", "target", ".git", "node_modules"} + +PARAM_RE = re.compile( + r"^(\s+)- ([A-Za-z_\u4e00-\u9fff][A-Za-z0-9_\u4e00-\u9fff]*)(=(.*))?\s*$" +) +FOREACH_RE = re.compile(r"^(\s*)- \[([^\]]+)\]\(([^)]+)\)\s*$") + + +def wrap_id(name: str) -> str: + name = name.strip() + if name.startswith("`") and name.endswith("`"): + return name + return f"`{name}`" + + +def migrate_line(line: str) -> str: + m = FOREACH_RE.match(line) + if m: + indent, item, coll = m.groups() + return f"{indent}- [{wrap_id(item)}]({wrap_id(coll)})\n" + m = PARAM_RE.match(line) + if m: + indent, name, _, default = m.groups() + if default is not None: + return f"{indent}+ {wrap_id(name)}={default.rstrip()}\n" + return f"{indent}+ {wrap_id(name)}\n" + return line + + +def should_skip(path: Path) -> bool: + return any(part in SKIP_DIRS for part in path.parts) + + +def main() -> int: + changed = 0 + for path in sorted(ROOT.rglob("*.mq.md")): + if should_skip(path): + continue + text = path.read_text(encoding="utf-8") + lines = text.splitlines(keepends=True) + out = [migrate_line(ln) for ln in lines] + new_text = "".join(out) + if new_text != text: + path.write_text(new_text, encoding="utf-8") + print(path.relative_to(ROOT)) + changed += 1 + print(f"migrated {changed} files") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/marqdo/SKILL.md b/skills/marqdo/SKILL.md index 079ae57..8b1f108 100644 --- a/skills/marqdo/SKILL.md +++ b/skills/marqdo/SKILL.md @@ -19,21 +19,22 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. 1. **File suffix** must be `.mq.md` (never plain `.md` for executable sources). 2. **Output is not `**bold**`.** Print with `> print text=…` (or `> 打印 内容=…`). Bold `**…**` is **return value only**. 3. **Prose vs code:** after a blank line, an unmarked first line starts a **comment paragraph**; every following non-blank line stays comment until the next blank line. Put a **blank line** between narration and executable lines. -4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: `+` branch, `-` loop, arm-head lone `*` = else, `#` = **object/type**, `##`+ = **function/method**, `**…**` = return. -5. **Structure lines are not wrapped in italics.** `#` `>` `+` `-` `|` lines stand alone; use `*…*` only for general statements (bindings / expressions). -6. **Paths in bare expressions:** `/` is division. Prefer `` `path` `` vars, same-dir names, or call args — not raw `a/b` in expressions. -7. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed. +4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`+` params** (under heading), **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**, `**…**` = return. +5. **Identifiers use backticks** — params `` + `name` ``, bindings `` `x` ``, foreach `` [`item`](`coll`) ``. **Complex text** uses `"..."` with escapes; bare tokens stay literal (no `\n` magic). +6. **Structure lines are not wrapped in italics.** `#` `>` `+` `-` `|` lines stand alone; use `*…*` only for general statements (bindings / expressions). +7. **Paths in bare expressions:** `/` is division. Prefer `` `path` `` vars, same-dir names, or call args — not raw `a/b` in expressions. +8. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed. -## Markup → meaning (v0.1) +## Markup → meaning (v0.2) | Marker | Meaning | |--------|---------| | `#` | **Object / type** (constructor body). `# main` = entry object. | | `##` … `######` | **Function / method** (nesting by heading depth). | -| `- name` under a heading | Parameter | -| `- …` inside body | Loop | -| `+ …` or `1.` | Branch arm (condition) | -| Line that is only `*` | Else arm | +| `` + `name` `` under heading | Parameter (optional `` `name`=default ``) | +| `1.` `2.` … in body | Branch arm (condition or `N. *` else) | +| `- …` inside body | Loop (`while` or `` [`item`](`coll`) ``) | +| Line `N. *` | Else arm | | `> fn args` | Call (named `k=v` or positional) | | `` > `obj`.method args `` | Method call (`obj` must be a map with `_type`) | | Frontmatter `> path.mq.md` | Import | @@ -43,6 +44,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords. | Lone `---` / `***` in function body | End function body (no value) | | GFM table after empty RHS bind | Collection | | `` ```lang `` | Foreign code block (via `lib/foreign`) | +| `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped | | Unmarked prose | Comment | Entry: load file (often `index.mq.md`) → collect defs → run `# main`. @@ -71,7 +73,7 @@ Chinese builtins (same functions, no import): > greet who=Marqdo ## greet - - who + + `who` > print text=Hello, `who`! @@ -88,8 +90,8 @@ Chinese builtins (same functions, no import): *`x` = 1* *`y` = `x` + 2* -# add_one - - n +## add_one + + `n` **`n` + 1** ``` @@ -97,11 +99,11 @@ Chinese builtins (same functions, no import): ```markdown *`n` = 0* -+ `n` > 0 +1. `n` > 0 > print text=positive -+ `n` < 0 +2. `n` < 0 > print text=negative -+ * +3. * > print text=zero ``` @@ -141,7 +143,7 @@ Stdlib map: [reference.md](reference.md). |-------|-------| | `**Hello**` to print | `> print text=Hello` | | `# main` then prose then code with no blank line | Blank line before code | -| `if x > 0:` | `+ `x` > 0` | +| `if x > 0:` | `1. `x` > 0` | | `* > print text=hi *` | `> print text=hi` | | Forgetting `---` after nested `##` helper | Add `---` / `***` / `****` | | Import `lib/text` then call `拆分` | Match file language | diff --git a/skills/marqdo/examples.md b/skills/marqdo/examples.md index a4cbd17..8c1e2a4 100644 --- a/skills/marqdo/examples.md +++ b/skills/marqdo/examples.md @@ -26,7 +26,7 @@ Greeting via a nested function: > greet who=Marqdo ## greet - - who + + `who` > print text=Hello, `who`! @@ -43,7 +43,7 @@ Greeting via a nested function: > print text=`b` ## add_one - - n + + `n` **`n` + 1** ``` @@ -55,15 +55,29 @@ Greeting via a nested function: *`n` = 0* -+ `n` > 0 +1. `n` > 0 > print text=positive -+ `n` < 0 +2. `n` < 0 > print text=negative -+ * +3. * > print text=zero ``` -## 6. Import text stdlib +## 6. Foreach loop + +```markdown +# main + +`篮子` = +| 果 | +|----| +| 苹果 | + +- [`果`](`篮子`) + > print text=`果` +``` + +## 7. Import text stdlib ```markdown --- @@ -77,7 +91,7 @@ title: split demo > print text=`parts` ``` -## 7. Comment paragraphs (blank-line rule) +## 8. Comment paragraphs (blank-line rule) ```markdown # main @@ -91,7 +105,7 @@ After a blank line, code runs: > print text=this runs ``` -## 8. Frontmatter import only +## 9. Frontmatter import only ```markdown --- @@ -105,11 +119,11 @@ description: loads math > print text=`t` ``` -## 9. Object handle + method +## 10. Object handle + method See `tests/structure/object-handle.mq.md` and `ext/llm.mq.md`: `# Type` constructs a map with `_type`; methods use `` > `obj`.method `` and read `self` / `自`. -## 10. Agent layout (ABI) +## 11. Agent layout (ABI) ```markdown --- @@ -127,7 +141,7 @@ See `tests/structure/object-handle.mq.md` and `ext/llm.mq.md`: `# Type` construc Requires `MARQDO_AGENT_PLUGIN` pointing at the built `agent` shared library (see `doc/design/ext-agent.md`). -## 11. What not to emit +## 12. What not to emit ```markdown # BAD — bold is return, not print @@ -139,4 +153,10 @@ if x > 0: # BAD — wrapping a call in italics *> print text=hi* + +# BAD — old branch syntax (removed) ++ `x` > 0 + +# GOOD — ordered list arms +1. `x` > 0 ``` diff --git a/skills/marqdo/reference.md b/skills/marqdo/reference.md index b4d1cea..b5b95c2 100644 --- a/skills/marqdo/reference.md +++ b/skills/marqdo/reference.md @@ -18,9 +18,11 @@ marqdo ext remove llm|agent Diagnostics look like `path:line:col: message` (1-based line/col). +**v0.2 surface:** parameters `` + `name` ``; branches `` 1. `cond` `` / `` 2. * ``; loops `` - [`item`](`coll`) ``; identifiers in backticks. See `doc/design/markdown-mapping.md`. + Stdlib search order for `lib/…` imports: `MARQDO_LIB`, `./lib`, directory of the `marqdo` executable (and a few parents). Prefer the **bundle zip** (`marqdo.exe` + `lib/`) over a bare exe. -官方扩展(`ext/ai/…`):`marqdo ext add` 装到 `MARQDO_EXT`;导入写 `> ext/ai/llm.mq.md`。 +官方扩展(`ext/…`,非 stdlib):`marqdo ext add` 装到 `MARQDO_EXT` 或 `~/.marqdo/ext`;导入仍写 `> ext/llm.mq.md`。解析还含 cwd `ext/`、二进制旁 `ext/`。对象:`doc/design/objects.md`。Agent:`doc/design/ext-agent.md` · 安装器:`doc/design/ext-cli.md`。 ## Builtins (no import) @@ -50,8 +52,8 @@ Import one file; use **that** file’s function names. | `lib/json.mq.md` | (see design) | JSON (+ `quote`) | | `lib/math.mq.md` | `lib/数学.mq.md` | num, trig, random, formula, plot | | `lib/foreign.mq.md` | `lib/外联.mq.md` | run foreign fenced blocks | -| `ext/ai/llm.mq.md` | `ext/ai/大模型.mq.md` | `# llm` / `# 大模型` | -| `ext/ai/agent.mq.md` | `ext/ai/智能体.mq.md` | agent framework: `# 智能体` + `## 执行` + `## 清空历史` | +| `ext/llm.mq.md` | `ext/大模型.mq.md` | `# llm` / `# 大模型` object + chat methods | +| `ext/agent.mq.md` | `ext/智能体.mq.md` | agent **framework** (layout now; LLM orchestration roadmap in `ext-agent.md`) | Open the imported `.mq.md` under `lib/` or `ext/` to see exact `##` / `#` names and parameters. Gold tests: `tests/lib/`, `tests/structure/`, `tests/ext/`. @@ -128,6 +130,6 @@ See `doc/design/call-arguments.md`. | `doc/design/stdlib-modules.md` | L1 modules including plugin | | `doc/design/ext-abi.md` | Native C ABI v1 | | `doc/design/ext-llm.md` | `ext/llm` | -| `doc/design/ext-agent.md` | `ext/agent` agent **framework** (ctor + run + clear_history; no bundled domain tools) | +| `doc/design/ext-agent.md` | `ext/agent` agent **framework** (layout shipped; LLM orchestration roadmap) | | `doc/design/ext-cli.md` | `marqdo ext list/add/remove` | | `doc/design/view-debug.md` | view / debug hosts | diff --git a/src/ast.rs b/src/ast.rs index 918d0e5..c512ff4 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -10,13 +10,19 @@ pub struct Module { pub functions: Vec, } +#[derive(Debug, Clone)] +pub struct Param { + pub name: String, + pub default: Option, +} + #[derive(Debug, Clone)] pub struct Function { pub name: String, /// Heading depth 1–6. Level 1 = object/type; level ≥ 2 = function/method. pub level: u8, pub span: Span, - pub params: Vec, + pub params: Vec, pub body: Vec, pub children: Vec, } diff --git a/src/bytecode/compile.rs b/src/bytecode/compile.rs index 3d5a82c..069c877 100644 --- a/src/bytecode/compile.rs +++ b/src/bytecode/compile.rs @@ -5,7 +5,7 @@ use std::collections::HashMap; use std::path::Path; use crate::ast::{ - Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp, + Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Param, Stmt, UnaryOp, }; use crate::bytecode::{FnChunk, Op, Program}; use crate::diagnostics::{bail_at, Span}; @@ -15,7 +15,7 @@ struct FlatFun { name: String, level: u8, parent: Option, - params: Vec, + params: Vec, body: Vec, children: Vec, span: Span, @@ -110,7 +110,7 @@ fn compile_function(fn_id: usize, flat: &[FlatFun], path: Option<&Path>) -> Resu let fun = &flat[fn_id]; let mut locals = HashMap::new(); for (i, p) in fun.params.iter().enumerate() { - locals.insert(p.clone(), i as u8); + locals.insert(p.name.clone(), i as u8); } let is_method = fun .parent @@ -130,11 +130,11 @@ fn compile_function(fn_id: usize, flat: &[FlatFun], path: Option<&Path>) -> Resu fn_id, chunk: FnChunk { name: fun.name.clone(), - params: fun.params.clone(), + params: fun.params.iter().map(|p| p.name.clone()).collect(), code: Vec::new(), spans: Vec::new(), constants: Vec::new(), - locals: fun.params.clone(), + locals: fun.params.iter().map(|p| p.name.clone()).collect(), }, locals, stmt_span: fun.span, @@ -530,7 +530,7 @@ impl<'a> FnCompiler<'a> { match self.resolve_call(&call.callee) { Ok(fid) => { - let params = self.flat[fid].params.clone(); + let params = &self.flat[fid].params; let mut named: HashMap = HashMap::new(); let mut positionals = Vec::new(); for a in &call.args { @@ -542,14 +542,16 @@ impl<'a> FnCompiler<'a> { } } let mut pos_i = 0; - for p in ¶ms { - if let Some(e) = named.get(p) { + for p in params { + if let Some(e) = named.get(&p.name) { self.compile_expr(e)?; } else if pos_i < positionals.len() { self.compile_expr(positionals[pos_i])?; pos_i += 1; + } else if let Some(def) = &p.default { + self.compile_expr(def)?; } else { - return Err(self.err(format!("missing argument for parameter `{p}`"))); + return Err(self.err(format!("missing argument for parameter `{}`", p.name))); } } if pos_i < positionals.len() { @@ -647,13 +649,15 @@ impl<'a> FnCompiler<'a> { } let mut pos_i = 0; for p in ¶ms { - if let Some(e) = named.get(p) { + if let Some(e) = named.get(&p.name) { self.compile_expr(e)?; } else if pos_i < positionals.len() { self.compile_expr(positionals[pos_i])?; pos_i += 1; + } else if let Some(def) = &p.default { + self.compile_expr(def)?; } else { - return Err(self.err(format!("missing argument for parameter `{p}`"))); + return Err(self.err(format!("missing argument for parameter `{}`", p.name))); } } if pos_i < positionals.len() { diff --git a/src/bytecode/vm.rs b/src/bytecode/vm.rs index ac7b434..9cd33b8 100644 --- a/src/bytecode/vm.rs +++ b/src/bytecode/vm.rs @@ -357,6 +357,7 @@ impl Vm { slots, }); self.host.push_call_frame(&fname); + self.host.push_call_site_line(span.line); } Op::TagInstance(idx) => { let type_name = match fun.constants.get(idx as usize) { @@ -422,6 +423,7 @@ impl Vm { slots, }); self.host.push_call_frame(&fname); + self.host.push_call_site_line(span.line); } Op::PluginCall(name_idx, argc) => { let argc = argc as usize; @@ -509,11 +511,13 @@ impl Vm { slots, }); self.host.push_call_frame(&fname); + self.host.push_call_site_line(span.line); } Op::Return => { let ret = pop(&mut stack).unwrap_or(Value::None); frames.pop(); self.host.pop_call_frame(); + self.host.pop_call_site_line(); if frames.is_empty() { return Ok(ret); } diff --git a/src/host/dispatch.rs b/src/host/dispatch.rs index 0dbd8e2..e341e07 100644 --- a/src/host/dispatch.rs +++ b/src/host/dispatch.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; -use crate::host::{agent_rt, foreign, fs, json, math, net, plugin, sys, time, HostContext}; +use crate::host::{agent_rt, foreign, fs, json, math, net, plugin, subtask, sys, time, writeback, HostContext}; use crate::value::Value; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -92,6 +92,15 @@ pub enum HostFn { AgentHistoryAppend = 81, FormatToolsForLlm = 82, ToolAllowed = 83, + WritebackRecord = 84, + WritebackGet = 85, + WritebackClear = 86, + WritebackList = 87, + SubtaskSpawn = 88, + SubtaskPoll = 89, + SubtaskJoin = 90, + SubtaskKill = 91, + SubtaskWaitAll = 92, } impl HostFn { @@ -180,6 +189,15 @@ impl HostFn { 81 => Self::AgentHistoryAppend, 82 => Self::FormatToolsForLlm, 83 => Self::ToolAllowed, + 84 => Self::WritebackRecord, + 85 => Self::WritebackGet, + 86 => Self::WritebackClear, + 87 => Self::WritebackList, + 88 => Self::SubtaskSpawn, + 89 => Self::SubtaskPoll, + 90 => Self::SubtaskJoin, + 91 => Self::SubtaskKill, + 92 => Self::SubtaskWaitAll, _ => return None, }) } @@ -272,6 +290,15 @@ impl HostFn { "host_agent_history_append" | "agent_history_append" => Self::AgentHistoryAppend, "host_format_tools_for_llm" | "format_tools_for_llm" => Self::FormatToolsForLlm, "host_tool_allowed" | "tool_allowed" => Self::ToolAllowed, + "host_writeback_record" | "writeback_record" => Self::WritebackRecord, + "host_writeback_get" | "writeback_get" => Self::WritebackGet, + "host_writeback_clear" | "writeback_clear" => Self::WritebackClear, + "host_writeback_list" | "writeback_list" => Self::WritebackList, + "host_subtask_spawn" | "subtask_spawn" => Self::SubtaskSpawn, + "host_subtask_poll" | "subtask_poll" => Self::SubtaskPoll, + "host_subtask_join" | "subtask_join" => Self::SubtaskJoin, + "host_subtask_kill" | "subtask_kill" => Self::SubtaskKill, + "host_subtask_wait_all" | "subtask_wait_all" => Self::SubtaskWaitAll, _ => return None, }) } @@ -365,6 +392,15 @@ impl HostFn { Self::AgentHistoryAppend => "host_agent_history_append", Self::FormatToolsForLlm => "host_format_tools_for_llm", Self::ToolAllowed => "host_tool_allowed", + Self::WritebackRecord => "host_writeback_record", + Self::WritebackGet => "host_writeback_get", + Self::WritebackClear => "host_writeback_clear", + Self::WritebackList => "host_writeback_list", + Self::SubtaskSpawn => "host_subtask_spawn", + Self::SubtaskPoll => "host_subtask_poll", + Self::SubtaskJoin => "host_subtask_join", + Self::SubtaskKill => "host_subtask_kill", + Self::SubtaskWaitAll => "host_subtask_wait_all", } } @@ -417,6 +453,12 @@ impl HostFn { Self::AgentHistoryAppend => &["id", "item"], Self::FormatToolsForLlm => &["tools"], Self::ToolAllowed => &["tools", "name"], + Self::WritebackRecord => &["value"], + Self::WritebackGet | Self::WritebackClear => &[], + Self::WritebackList => &[], + Self::SubtaskSpawn => &["path"], + Self::SubtaskPoll | Self::SubtaskJoin | Self::SubtaskKill => &["id"], + Self::SubtaskWaitAll => &[], } } @@ -434,6 +476,8 @@ impl HostFn { Self::PlotConic => &["b", "h", "k", "path", "grid"], Self::ForeignSetCmd => &["args"], Self::ForeignRun | Self::ForeignRunLang => &["stdin"], + Self::WritebackRecord | Self::WritebackGet | Self::WritebackClear => &["at_end"], + Self::SubtaskSpawn => &["args"], _ => &[], } } @@ -632,6 +676,23 @@ pub fn call_host( require(bound, "tools")?, require(bound, "name")?, ), + HostFn::WritebackRecord => writeback::record( + ctx, + require(bound, "value")?, + bound.get("at_end"), + ), + HostFn::WritebackGet => writeback::get(ctx, bound.get("at_end")), + HostFn::WritebackClear => writeback::clear(ctx, bound.get("at_end")), + HostFn::WritebackList => writeback::list(ctx), + HostFn::SubtaskSpawn => subtask::spawn( + ctx, + require(bound, "path")?, + bound.get("args"), + ), + HostFn::SubtaskPoll => subtask::poll(ctx, require(bound, "id")?), + HostFn::SubtaskJoin => subtask::join(ctx, require(bound, "id")?), + HostFn::SubtaskKill => subtask::kill(ctx, require(bound, "id")?), + HostFn::SubtaskWaitAll => subtask::wait_all(ctx), } } diff --git a/src/host/mod.rs b/src/host/mod.rs index 56ec361..9fcd235 100644 --- a/src/host/mod.rs +++ b/src/host/mod.rs @@ -12,8 +12,10 @@ mod json; pub mod math; mod net; pub mod plugin; +pub mod subtask; mod sys; mod time; +pub mod writeback; pub use dispatch::{call_host, HostFn}; pub use fs::path_under_root; @@ -21,6 +23,7 @@ pub use plugin::PluginState; use std::collections::HashMap; use std::path::{Path, PathBuf}; +use std::process::Child; use crate::value::Value; @@ -52,7 +55,7 @@ pub struct PlotArtifact { pub svg: String, } -#[derive(Debug, Clone)] +#[derive(Debug)] pub struct HostContext { pub caps: HostCaps, pub fs_root: Option, @@ -78,6 +81,11 @@ pub struct HostContext { pub agent_seq: u64, /// Last statement line (updated by interpreters for `host_call_site`). pub current_line: u32, + /// Entry-file line of each active user call (for writeback anchoring). + pub call_site_lines: Vec, + /// OS subprocess subtasks (`lib/subtask`). + pub subtasks: HashMap, + pub subtask_seq: u64, } impl Default for HostContext { @@ -99,10 +107,19 @@ impl Default for HostContext { agent_histories: HashMap::new(), agent_seq: 0, current_line: 1, + call_site_lines: Vec::new(), + subtasks: HashMap::new(), + subtask_seq: 0, } } } +impl Drop for HostContext { + fn drop(&mut self) { + subtask::kill_all(self); + } +} + impl HostContext { pub fn for_run(path: Option<&Path>, caps: HostCaps, argv: Vec) -> Self { let mut ctx = Self::default(); @@ -142,6 +159,14 @@ impl HostContext { self.caps.net } + pub fn push_call_site_line(&mut self, line: u32) { + self.call_site_lines.push(line); + } + + pub fn pop_call_site_line(&mut self) { + self.call_site_lines.pop(); + } + pub fn allow_plugin(&self) -> bool { self.caps.plugin } diff --git a/src/host/subtask.rs b/src/host/subtask.rs new file mode 100644 index 0000000..5976b34 --- /dev/null +++ b/src/host/subtask.rs @@ -0,0 +1,116 @@ +//! OS subprocess subtasks (`marqdo run` children); parent exit kills all children. + +use std::process::{Command, Stdio}; + +use crate::host::HostContext; +use crate::value::Value; + +fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> { + match v { + Value::Text(s) => Ok(s.as_str()), + _ => Err(format!("{label} must be text")), + } +} + +fn child_id(_ctx: &HostContext, id: &Value) -> Result { + match id { + Value::Int(n) if *n > 0 => Ok(*n as u64), + _ => Err("subtask id must be positive int".into()), + } +} + +pub fn kill_all(ctx: &mut HostContext) { + for (_, mut child) in ctx.subtasks.drain() { + let _ = child.kill(); + let _ = child.wait(); + } +} + +pub fn spawn( + ctx: &mut HostContext, + path: &Value, + args: Option<&Value>, +) -> Result { + if !ctx.caps.exec { + return Err("subtask spawn disabled (exec capability off)".into()); + } + let rel = as_text(path, "path")?; + let file = if std::path::Path::new(rel).is_absolute() { + std::path::PathBuf::from(rel) + } else { + ctx.cwd.join(rel) + }; + let exe = std::env::current_exe().map_err(|e| format!("subtask: current_exe: {e}"))?; + let mut cmd = Command::new(&exe); + cmd.arg("run").arg(&file); + cmd.current_dir(&ctx.cwd); + cmd.stdin(Stdio::null()); + if let Some(Value::List(items)) = args { + for item in items { + cmd.arg(as_text(item, "arg")?); + } + } + let child = cmd + .spawn() + .map_err(|e| format!("subtask spawn {}: {e}", file.display()))?; + ctx.subtask_seq = ctx.subtask_seq.wrapping_add(1); + let id = ctx.subtask_seq; + ctx.subtasks.insert(id, child); + Ok(Value::Int(id as i64)) +} + +pub fn poll(ctx: &mut HostContext, id: &Value) -> Result { + let id = child_id(ctx, id)?; + let child = ctx + .subtasks + .get_mut(&id) + .ok_or_else(|| format!("subtask: unknown id {id}"))?; + match child.try_wait().map_err(|e| format!("subtask poll: {e}"))? { + None => Ok(Value::Map(vec![("status".into(), Value::Text("running".into()))])), + Some(status) => { + let code = status.code().unwrap_or(-1); + let st = if status.success() { + "done" + } else { + "failed" + }; + Ok(Value::Map(vec![ + ("status".into(), Value::Text(st.into())), + ("code".into(), Value::Int(code as i64)), + ])) + } + } +} + +pub fn join(ctx: &mut HostContext, id: &Value) -> Result { + let id = child_id(ctx, id)?; + let mut child = ctx + .subtasks + .remove(&id) + .ok_or_else(|| format!("subtask: unknown id {id}"))?; + let status = child + .wait() + .map_err(|e| format!("subtask join: {e}"))?; + Ok(Value::Int(status.code().unwrap_or(-1) as i64)) +} + +pub fn kill(ctx: &mut HostContext, id: &Value) -> Result { + let id = child_id(ctx, id)?; + let mut child = ctx + .subtasks + .remove(&id) + .ok_or_else(|| format!("subtask: unknown id {id}"))?; + child.kill().map_err(|e| format!("subtask kill: {e}"))?; + let _ = child.wait(); + Ok(Value::None) +} + +pub fn wait_all(ctx: &mut HostContext) -> Result { + let ids: Vec = ctx.subtasks.keys().copied().collect(); + let mut codes = Vec::new(); + for id in ids { + let code = join(ctx, &Value::Int(id as i64))?; + codes.push(code); + } + Ok(Value::List(codes)) +} diff --git a/src/host/writeback.rs b/src/host/writeback.rs new file mode 100644 index 0000000..622eaa1 --- /dev/null +++ b/src/host/writeback.rs @@ -0,0 +1,345 @@ +//! Jupyter-style output persistence in `.mq.md` (``). + +use std::collections::HashMap; + +use crate::host::HostContext; +use crate::value::Value; + +const MAGIC: &str = "marqdo-out"; + +#[derive(Debug, Clone, PartialEq, Eq)] +struct BlockSpan { + start: usize, + end: usize, + body: String, + start_line: u32, +} + +fn display_value(v: &Value) -> String { + match v { + Value::Text(s) => s.clone(), + other => other.as_display(), + } +} + +fn is_truthy(v: Option<&Value>) -> bool { + match v { + None | Some(Value::None) => false, + Some(Value::Bool(b)) => *b, + Some(Value::Int(n)) => *n != 0, + _ => false, + } +} + +fn call_line(ctx: &HostContext) -> Result { + ctx.call_site_lines + .last() + .copied() + .ok_or_else(|| "writeback: no call site line".into()) +} + +fn line_number_at(source: &str, byte: usize) -> u32 { + source[..byte.min(source.len())] + .bytes() + .filter(|b| *b == b'\n') + .count() as u32 + + 1 +} + +fn format_block(body: &str) -> String { + format!("") +} + +fn parse_one_block(block: &str, start_byte: usize, source: &str) -> Option { + let inner = block + .strip_prefix("")? + .trim(); + if !inner.contains(MAGIC) { + return None; + } + let mut lines: Vec<&str> = inner.lines().collect(); + if lines.is_empty() { + return None; + } + let header = lines.remove(0).trim(); + if !header.split_whitespace().any(|t| t == MAGIC) { + return None; + } + let body = lines.join("\n"); + let end = start_byte + block.len(); + Some(BlockSpan { + start: start_byte, + end, + body, + start_line: line_number_at(source, start_byte), + }) +} + +fn scan_blocks(source: &str) -> Vec { + let mut out = Vec::new(); + let mut i = 0usize; + while i < source.len() { + let rest = &source[i..]; + let Some(start) = rest.find("") else { + break; + }; + let block = &after[..end_rel + 3]; + if let Some(b) = parse_one_block(block, abs, source) { + out.push(b); + } + i = abs + end_rel + 3; + } + out +} + +fn strip_span(source: &str, start: usize, end: usize) -> String { + let mut out = String::with_capacity(source.len()); + out.push_str(&source[..start]); + out.push_str(&source[end..]); + out +} + +fn line_start_byte(source: &str, line_no: u32) -> Option { + if line_no == 0 { + return None; + } + let mut cur = 1u32; + for (i, b) in source.bytes().enumerate() { + if cur == line_no { + return Some(i); + } + if b == b'\n' { + cur += 1; + } + } + if cur == line_no { + Some(source.len()) + } else { + None + } +} + +fn line_end_byte(source: &str, line_no: u32) -> Option { + let start = line_start_byte(source, line_no)?; + let rest = &source[start..]; + match rest.find('\n') { + Some(off) => Some(start + off + 1), + None => Some(source.len()), + } +} + +fn is_blank_line(source: &str, line_no: u32) -> bool { + let start = match line_start_byte(source, line_no) { + Some(s) => s, + None => return true, + }; + let end = line_end_byte(source, line_no).unwrap_or(source.len()); + source[start..end].trim().is_empty() +} + +fn find_adjacent_block(source: &str, after_line: u32) -> Option { + let mut line = after_line.saturating_add(1); + let total = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1; + while line <= total && is_blank_line(source, line) { + line += 1; + } + for b in scan_blocks(source) { + if b.start_line == line { + return Some(b); + } + } + None +} + +fn is_eof_block(source: &str, block: &BlockSpan) -> bool { + source[block.end..].trim().is_empty() +} + +fn find_eof_block(source: &str) -> Option { + scan_blocks(source) + .into_iter() + .rev() + .find(|b| is_eof_block(source, b)) +} + +fn insert_after_line(source: &str, line_no: u32, block: &str) -> Result { + let insert_at = line_end_byte(source, line_no) + .ok_or_else(|| format!("writeback: line {line_no} out of range"))?; + let mut out = String::with_capacity(source.len() + block.len() + 2); + out.push_str(&source[..insert_at]); + if !block.starts_with('\n') && !source[..insert_at].ends_with('\n') { + out.push('\n'); + } + out.push_str(block); + if !block.ends_with('\n') { + out.push('\n'); + } + out.push_str(&source[insert_at..]); + Ok(out) +} + +fn append_eof(source: &str, block: &str) -> String { + let mut trimmed = source.trim_end().to_string(); + if !trimmed.is_empty() { + trimmed.push('\n'); + } + trimmed.push_str(block); + if !block.ends_with('\n') { + trimmed.push('\n'); + } + trimmed +} + +fn persist(ctx: &mut HostContext, source: &str) -> Result<(), String> { + if !ctx.allow_fs_write() { + return Err("writeback disabled (fs_write capability off)".into()); + } + let path = ctx + .entry_path + .as_ref() + .ok_or_else(|| "writeback: no entry file".to_string())?; + std::fs::write(path, source).map_err(|e| format!("writeback write {}: {e}", path.display()))?; + ctx.entry_source = Some(source.to_string()); + Ok(()) +} + +fn anchor_line_above(source: &str, block_start_line: u32) -> u32 { + let mut line = block_start_line.saturating_sub(1); + while line > 0 && is_blank_line(source, line) { + line -= 1; + } + line.max(1) +} + +pub fn record( + ctx: &mut HostContext, + value: &Value, + at_end: Option<&Value>, +) -> Result { + let body = display_value(value); + let source = ctx + .entry_source + .as_deref() + .ok_or_else(|| "writeback: no entry source".to_string())?; + let next = if is_truthy(at_end) { + let stripped = find_eof_block(source) + .map(|b| strip_span(source, b.start, b.end)) + .unwrap_or_else(|| source.to_string()); + append_eof(&stripped, &format_block(&body)) + } else { + let line = call_line(ctx)?; + let stripped = find_adjacent_block(source, line) + .map(|b| strip_span(source, b.start, b.end)) + .unwrap_or_else(|| source.to_string()); + insert_after_line(&stripped, line, &format_block(&body))? + }; + persist(ctx, &next)?; + Ok(Value::Text(body)) +} + +pub fn get(ctx: &HostContext, at_end: Option<&Value>) -> Result { + let source = ctx + .entry_source + .as_deref() + .ok_or_else(|| "writeback: no entry source".to_string())?; + let body = if is_truthy(at_end) { + find_eof_block(source).map(|b| b.body) + } else { + let line = call_line(ctx)?; + find_adjacent_block(source, line).map(|b| b.body) + }; + Ok(match body { + Some(s) => Value::Text(s), + None => Value::None, + }) +} + +pub fn clear(ctx: &mut HostContext, at_end: Option<&Value>) -> Result { + let source = ctx + .entry_source + .as_deref() + .ok_or_else(|| "writeback: no entry source".to_string())?; + let next = if is_truthy(at_end) { + find_eof_block(source) + .map(|b| strip_span(source, b.start, b.end)) + .unwrap_or_else(|| source.to_string()) + } else { + let line = call_line(ctx)?; + find_adjacent_block(source, line) + .map(|b| strip_span(source, b.start, b.end)) + .unwrap_or_else(|| source.to_string()) + }; + if next != source { + persist(ctx, &next)?; + } + Ok(Value::None) +} + +pub fn list(ctx: &HostContext) -> Result { + let source = ctx + .entry_source + .as_deref() + .ok_or_else(|| "writeback: no entry source".to_string())?; + let items: Vec = scan_blocks(source) + .into_iter() + .map(|b| { + let anchor = anchor_line_above(source, b.start_line); + let at_eof = is_eof_block(source, &b); + Value::Map(vec![ + ("line".into(), Value::Int(anchor as i64)), + ("body".into(), Value::Text(b.body)), + ("at_end".into(), Value::Bool(at_eof)), + ]) + }) + .collect(); + Ok(Value::List(items)) +} + +/// Map statement line → body for adjacent blocks; EOF blocks use key `0`. +pub fn writeback_map(source: &str) -> HashMap { + let mut map = HashMap::new(); + for b in scan_blocks(source) { + if is_eof_block(source, &b) { + map.insert(0, b.body); + } else { + map.insert(anchor_line_above(source, b.start_line), b.body); + } + } + map +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_and_insert_adjacent() { + let src = "# main\n\n*`x` = 1*\n"; + let block = format_block("1"); + let next = insert_after_line(src, 3, &block).unwrap(); + assert!(next.contains("marqdo-out")); + assert!(!next.contains("@line")); + let blocks = scan_blocks(&next); + assert_eq!(blocks.len(), 1); + assert_eq!(blocks[0].body, "1"); + let replaced = strip_span(&next, blocks[0].start, blocks[0].end); + assert!(!replaced.contains("marqdo-out")); + } + + #[test] + fn writeback_map_uses_line_above() { + let src = "# main\n\n*`x` = 1*\n\n\n> print text=tail\n"; + let map = writeback_map(src); + assert_eq!(map.get(&3), Some(&"42".to_string())); + } +} diff --git a/src/interp.rs b/src/interp.rs index ab61129..6b0671b 100644 --- a/src/interp.rs +++ b/src/interp.rs @@ -5,7 +5,7 @@ use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use crate::ast::{ - Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp, + 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, @@ -161,8 +161,8 @@ impl Interpreter { env.set(k.clone(), v.clone()); } for p in &fun.params { - if env.get(p).is_none() { - env.set(p.clone(), Value::None); + if env.get(&p.name).is_none() { + env.set(p.name.clone(), Value::None); } } @@ -456,7 +456,7 @@ impl Interpreter { } if let Some(recv_name) = &call.receiver { - return self.eval_method_call(module, env, recv_name, &call.callee, &ev_args); + return self.eval_method_call(module, fun, env, recv_name, &call.callee, &ev_args); } match call.callee.as_str() { @@ -607,13 +607,17 @@ impl Interpreter { let target = lookup_function(module, fun, &call.callee) .ok_or_else(|| self.err(format!("unknown function `{}`", call.callee)))?; - let bound = bind_args(&target.params, &ev_args, false).map_err(|m| self.err(m))?; + let bound = bind_function_args(self, module, fun, env, &target.params, &ev_args, false) + .map_err(|m| self.err(m))?; let mut call_env = Env::new(); for (k, v) in bound { call_env.set(k, v); } - let result = self.run_function(module, target, call_env, &[])?; + self.host.push_call_site_line(self.host.current_line); + let result = self.run_function(module, target, call_env, &[]); + self.host.pop_call_site_line(); + let result = result?; if target.is_object() { Ok(tag_instance(&target.name, result)) } else { @@ -624,6 +628,7 @@ impl Interpreter { fn eval_method_call( &mut self, module: &Module, + fun: &Function, env: &mut Env, recv_name: &str, method: &str, @@ -642,14 +647,18 @@ impl Interpreter { .iter() .find(|c| c.name == method) .ok_or_else(|| self.err(format!("unknown method `{type_name}.{method}`")))?; - let bound = bind_args(&target.params, ev_args, false).map_err(|m| self.err(m))?; + let bound = bind_function_args(self, module, fun, env, &target.params, ev_args, false) + .map_err(|m| self.err(m))?; let mut call_env = Env::new(); for (k, v) in bound { call_env.set(k, v); } call_env.set("自".into(), recv.clone()); call_env.set("self".into(), recv); - self.run_function(module, target, call_env, &[]) + self.host.push_call_site_line(self.host.current_line); + let result = self.run_function(module, target, call_env, &[]); + self.host.pop_call_site_line(); + result } } @@ -684,6 +693,67 @@ fn tag_instance(type_name: &str, value: Value) -> Value { } /// Bind evaluated args onto parameter names. Err is a plain message (caller adds span/path). +fn bind_function_args( + interp: &mut Interpreter, + module: &Module, + caller: &Function, + caller_env: &mut Env, + params: &[Param], + args: &[EvArg], + allow_missing: bool, +) -> std::result::Result, String> { + let mut named: HashMap = HashMap::new(); + let mut positionals = Vec::new(); + for a in args { + match a { + EvArg::Positional(v) => positionals.push(v.clone()), + EvArg::Named(k, v) => { + if named.contains_key(k) { + return Err(format!("duplicate named argument `{k}`")); + } + named.insert(k.clone(), v.clone()); + } + } + } + + let mut out: HashMap = HashMap::new(); + let mut used_named = HashSet::new(); + let mut pos_i = 0usize; + + for p in params { + if let Some(v) = named.get(&p.name) { + out.insert(p.name.clone(), v.clone()); + used_named.insert(p.name.clone()); + } else if pos_i < positionals.len() { + out.insert(p.name.clone(), positionals[pos_i].clone()); + pos_i += 1; + } else if let Some(def) = &p.default { + let v = interp + .eval_expr(module, caller, caller_env, def) + .map_err(|e| e.to_string())?; + out.insert(p.name.clone(), v); + } else if !allow_missing { + return Err(format!("missing argument for parameter `{}`", p.name)); + } + } + + if pos_i < positionals.len() { + return Err(format!( + "too many positional arguments ({} extra)", + positionals.len() - pos_i + )); + } + + for (k, v) in named { + if !used_named.contains(&k) && !out.contains_key(&k) { + out.insert(k, v); + } + } + + Ok(out) +} + +/// Bind evaluated args onto parameter names (host / plugin functions). fn bind_args( params: &[String], args: &[EvArg], diff --git a/src/lex/mod.rs b/src/lex/mod.rs index 9d843ba..9a89201 100644 --- a/src/lex/mod.rs +++ b/src/lex/mod.rs @@ -11,6 +11,8 @@ use std::fmt; pub enum LineKind { Blank, Comment, + /// Jupyter-style persisted output (``). + Writeback, Code, } @@ -19,6 +21,7 @@ impl fmt::Display for LineKind { match self { LineKind::Blank => write!(f, "Blank"), LineKind::Comment => write!(f, "Comment"), + LineKind::Writeback => write!(f, "Writeback"), LineKind::Code => write!(f, "Code"), } } @@ -40,6 +43,25 @@ fn is_code_starter(c: char) -> bool { ) || c.is_ascii_digit() } +/// `*` / `**` lines that are Marqdo executable (statement / return / else), not narrative Markdown. +fn is_marqdo_star_line(trimmed: &str) -> bool { + if trimmed == "*" || trimmed == "****" { + return true; + } + if trimmed.starts_with("**") { + if trimmed.trim() == "** **" { + return true; + } + if let Some(rest) = trimmed.strip_prefix("**") { + if let Some(pos) = rest.find("**") { + return rest[pos + 2..].trim().is_empty(); + } + } + return false; + } + trimmed.starts_with('*') && trimmed.ends_with('*') && trimmed.len() >= 2 +} + /// Classify a single logical line (no trailing newline required). /// /// This is the **paragraph-start** rule only. Prefer [`classify_source`] for @@ -49,9 +71,11 @@ pub fn classify_line(text: &str) -> LineKind { if trimmed.chars().all(|c| c.is_whitespace()) { return LineKind::Blank; } + let trimmed = text.trim(); let first = trimmed.chars().find(|c| !c.is_whitespace()); match first { None => LineKind::Blank, + Some('*') if !is_marqdo_star_line(trimmed) => LineKind::Comment, Some(c) if is_code_starter(c) => LineKind::Code, Some(_) => LineKind::Comment, } @@ -74,12 +98,18 @@ pub fn classify_source(source: &str) -> Vec { let mut in_comment_paragraph = false; let mut in_math_fence = false; let mut in_md_fence = false; + let mut in_writeback = false; for (i, text) in lines.into_iter().enumerate() { let base = classify_line(text); let trimmed = text.trim(); let structural = is_structural_code_line(trimmed); - let kind = if in_math_fence { + let kind = if in_writeback { + if trimmed.contains("-->") { + in_writeback = false; + } + LineKind::Writeback + } else if in_math_fence { if trimmed == "$$" { in_math_fence = false; } @@ -94,6 +124,13 @@ pub fn classify_source(source: &str) -> Vec { in_md_fence = true; in_comment_paragraph = false; LineKind::Comment + } else if trimmed.starts_with("") { + in_writeback = false; + } + LineKind::Writeback } else { match base { LineKind::Blank => { @@ -109,6 +146,7 @@ pub fn classify_source(source: &str) -> Vec { LineKind::Code } LineKind::Code if in_comment_paragraph => LineKind::Comment, + LineKind::Writeback => LineKind::Writeback, LineKind::Code => { // Multi-line math fence opener (not same-line `$$…$$`). if trimmed == "$$" { @@ -196,6 +234,27 @@ mod tests { assert_eq!(classify_line("`x` = 1"), LineKind::Code); } + #[test] + fn narrative_bold_in_comment_paragraph() { + let src = "说明如下:\n\n**强调信息**是什么什么\n\n> print text=ok\n"; + let lines = classify_source(src); + assert_eq!(lines[0].kind, LineKind::Comment); + assert_eq!(lines[1].kind, LineKind::Blank); + assert_eq!(lines[2].kind, LineKind::Comment, "bold prose is comment"); + assert_eq!(lines[3].kind, LineKind::Blank); + assert_eq!(lines[4].kind, LineKind::Code); + } + + #[test] + fn writeback_block_classified() { + let src = "*`x` = 1*\n\n"; + let lines = classify_source(src); + assert_eq!(lines[0].kind, LineKind::Code); + assert_eq!(lines[1].kind, LineKind::Writeback); + assert_eq!(lines[2].kind, LineKind::Writeback); + assert_eq!(lines[3].kind, LineKind::Writeback); + } + #[test] fn paragraph_comment_keeps_backtick_continuation() { let src = "采用了\n`.mq.md`的双层后缀\n\n> print text=ok\n"; diff --git a/src/parse/expr.rs b/src/parse/expr.rs index 83cbb27..75e4b93 100644 --- a/src/parse/expr.rs +++ b/src/parse/expr.rs @@ -286,6 +286,9 @@ impl<'a> Parser<'a> { } return Ok(e); } + if self.eat("\"") { + return self.parse_quoted_string(); + } if self.eat("`") { let start = self.i; while let Some(c) = self.peek_char() { @@ -345,7 +348,7 @@ impl<'a> Parser<'a> { { let start = self.i; while let Some(c) = self.peek_char() { - if c.is_whitespace() || matches!(c, '=' | '+' | '-' | '*' | '/' | '<' | '>' | '(' | ')' | '`' | '|' | ',') + if c.is_whitespace() || matches!(c, '=' | '+' | '-' | '*' | '/' | '<' | '>' | '(' | ')' | '`' | '|' | ',' | '"') { break; } @@ -356,6 +359,70 @@ impl<'a> Parser<'a> { } bail!("unexpected expression input: {:?}", self.rest()); } + + /// `"..."` string with `\n` `\t` `\r` `\\` `\"` and `` `var` `` interpolation. + fn parse_quoted_string(&mut self) -> Result { + use crate::ast::InterpPart; + let mut parts: Vec = Vec::new(); + let mut lit = String::new(); + loop { + let Some(c) = self.peek_char() else { + bail!("unterminated \" string"); + }; + if c == '"' { + self.bump_char(); + break; + } + if c == '\\' { + self.bump_char(); + let esc = self.peek_char().ok_or_else(|| anyhow::anyhow!("dangling \\ in string"))?; + self.bump_char(); + lit.push(match esc { + 'n' => '\n', + 't' => '\t', + 'r' => '\r', + '\\' => '\\', + '"' => '"', + other => bail!("unknown escape \\{other} in string"), + }); + continue; + } + if c == '`' { + if !lit.is_empty() { + parts.push(InterpPart::Lit(std::mem::take(&mut lit))); + } + self.bump_char(); + let start = self.i; + while let Some(ch) = self.peek_char() { + if ch == '`' { + break; + } + self.bump_char(); + } + let name = self.src[start..self.i].to_string(); + if !self.eat("`") { + bail!("unterminated `name` in string"); + } + parts.push(InterpPart::Var(name)); + continue; + } + lit.push(c); + self.bump_char(); + } + if !lit.is_empty() { + parts.push(InterpPart::Lit(lit)); + } + if parts.is_empty() { + return Ok(Expr::Literal(Literal::Text(String::new()))); + } + if parts.len() == 1 { + return Ok(match parts.remove(0) { + InterpPart::Lit(t) => Expr::Literal(Literal::Text(t)), + InterpPart::Var(n) => Expr::Var(n), + }); + } + Ok(Expr::Interp(parts)) + } } fn is_word_end(s: &str, len: usize) -> bool { @@ -468,6 +535,11 @@ fn try_named_arg(s: &str) -> Option<(String, &str)> { fn split_first_token(s: &str) -> (&str, &str) { let s = s.trim_start(); + if s.starts_with('"') { + if let Some(end) = end_of_quoted_string(s) { + return (&s[..end], &s[end..]); + } + } if s.starts_with('`') { // `` `name` `` as one token if let Some(end) = s[1..].find('`') { @@ -482,14 +554,36 @@ fn split_first_token(s: &str) -> (&str, &str) { } fn find_next_arg_boundary(after_eq: &str) -> usize { - // Look for ` =` pattern not inside backticks (UTF-8 safe). + // Look for ` =` pattern not inside backticks or quoted strings. let mut in_bt = false; - for (i, c) in after_eq.char_indices() { - if c == '`' { - in_bt = !in_bt; + let mut in_str = false; + let mut chars = after_eq.char_indices().peekable(); + while let Some((i, c)) = chars.next() { + if in_str { + if c == '\\' { + chars.next(); + continue; + } + if c == '"' { + in_str = false; + } continue; } - if !in_bt && c.is_whitespace() { + if in_bt { + if c == '`' { + in_bt = false; + } + continue; + } + if c == '`' { + in_bt = true; + continue; + } + if c == '"' { + in_str = true; + continue; + } + if c.is_whitespace() { let rest = &after_eq[i..]; let trimmed = rest.trim_start(); let skipped = rest.len() - trimmed.len(); @@ -509,6 +603,28 @@ fn find_next_arg_boundary(after_eq: &str) -> usize { after_eq.len() } +/// Byte index after a leading `"..."` token (opening quote included in slice). +fn end_of_quoted_string(s: &str) -> Option { + if !s.starts_with('"') { + return None; + } + let mut escaped = false; + for (i, c) in s.char_indices().skip(1) { + if escaped { + escaped = false; + continue; + } + if c == '\\' { + escaped = true; + continue; + } + if c == '"' { + return Some(i + c.len_utf8()); + } + } + None +} + /// Parse `> callee args` call expression/statement text (without leading `>`). pub fn parse_call_after_gt(after_gt: &str) -> Result { let (call, _) = parse_call_tail(after_gt.trim())?; @@ -527,6 +643,26 @@ mod tests { assert!(matches!(e, Expr::Binary { op: BinaryOp::Add, .. })); } + #[test] + fn quoted_string_escapes() { + let e = parse_expr("\"a\\nb\"").unwrap(); + assert!(matches!( + e, + Expr::Literal(Literal::Text(ref s)) if s == "a\nb" + )); + let e = parse_expr("\"hi `x`!\"").unwrap(); + assert!(matches!(e, Expr::Interp(_))); + } + + #[test] + fn bare_token_no_escape() { + let e = parse_expr("a\\nb").unwrap(); + assert!(matches!( + e, + Expr::Literal(Literal::Text(ref s)) if s == "a\\nb" + )); + } + #[test] fn chinese_logic_and_literals() { let e = parse_expr("`a` 且 非 `b`").unwrap(); diff --git a/src/parse/mod.rs b/src/parse/mod.rs index 3411e6e..1cc362b 100644 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -63,7 +63,7 @@ impl<'a> Cursor<'a> { fn skip_noise(&mut self) -> bool { while let Some(l) = self.peek() { match l.kind { - LineKind::Blank | LineKind::Comment => { + LineKind::Blank | LineKind::Comment | LineKind::Writeback => { self.i += 1; } LineKind::Code => return true, @@ -179,7 +179,7 @@ impl<'a> Cursor<'a> { } // Nested params mid-body shouldn't happen; treat `-` as control flow. - if trimmed.starts_with('+') || is_ordered_branch(trimmed) { + if is_ordered_branch(trimmed) { fun.body.push(self.parse_branch()?); continue; } @@ -495,9 +495,7 @@ impl<'a> Cursor<'a> { break; } let trimmed = l.text.trim(); - let cond_src = if let Some(rest) = trimmed.strip_prefix('+') { - rest.trim() - } else if let Some(rest) = strip_ordered(trimmed) { + let cond_src = if let Some(rest) = strip_ordered(trimmed) { rest } else { break; @@ -571,7 +569,7 @@ impl<'a> Cursor<'a> { if is_heading(trimmed) { break; } - if trimmed.starts_with('+') || is_ordered_branch(trimmed) { + if is_ordered_branch(trimmed) { // Nested branch inside body body.push(self.parse_branch()?); continue; @@ -618,34 +616,59 @@ fn try_parse_inline_formula(rhs: &str) -> Result> { bail!("incomplete inline formula (expected `$$…$$` on one line)"); } -fn parse_param_line(trimmed: &str) -> Option { - let rest = trimmed.strip_prefix('-')?.trim(); - if rest.is_empty() || rest.contains('`') || rest.contains('[') || rest.contains('=') { +fn parse_backtick_ident(s: &str) -> Option { + let s = s.trim(); + if !s.starts_with('`') { return None; } - if rest.split_whitespace().count() != 1 { + let inner = &s[1..]; + let end = inner.find('`')?; + let name = &inner[..end]; + if name.is_empty() || s.len() != end + 2 { return None; } - // Reject if looks like comparison / operator expr - if rest.contains('>') || rest.contains('<') || rest.contains('+') || rest.contains('*') { + Some(name.to_string()) +} + +fn parse_param_line(trimmed: &str) -> Option { + use crate::ast::Param; + let rest = trimmed.strip_prefix('+')?.trim(); + if rest.is_empty() || !rest.starts_with('`') { return None; } - Some(rest.to_string()) + let end_tick = rest[1..].find('`')?; + let name = rest[1..end_tick + 1].to_string(); + if name.is_empty() { + return None; + } + let after = rest[end_tick + 2..].trim(); + let default = if let Some(def_s) = after.strip_prefix('=') { + let def_s = def_s.trim(); + if def_s.is_empty() { + return None; + } + Some(parse_value_or_interp(def_s).ok()?) + } else if after.is_empty() { + None + } else { + return None; + }; + Some(Param { name, default }) } fn parse_foreach_header(rest: &str) -> Option<(String, String)> { - // [item](collection) + // [`item`](`collection`) let rest = rest.trim(); if !rest.starts_with('[') { return None; } let end_item = rest.find(']')?; - let item = rest[1..end_item].to_string(); + let item = parse_backtick_ident(&rest[1..end_item])?; let after = rest[end_item + 1..].trim_start(); if !after.starts_with('(') || !after.ends_with(')') { return None; } - let coll = after[1..after.len() - 1].to_string(); + let coll = parse_backtick_ident(&after[1..after.len() - 1])?; Some((item, coll)) } @@ -762,7 +785,45 @@ mod tests { let main = m.functions.iter().find(|f| f.name == "main").unwrap(); assert_eq!(main.children.len(), 1); assert_eq!(main.children[0].name, "问候"); - assert_eq!(main.children[0].params, vec!["谁".to_string()]); + assert_eq!(main.children[0].params[0].name, "谁"); + } + + #[test] + fn parse_optional_param_default() { + let src = "# main\n\n## f\n + `a`\n + `b`=Hi\n\n> print text=`a`\n"; + let m = parse_source(src).unwrap(); + let f = &m.functions[0].children[0]; + assert_eq!(f.params.len(), 2); + assert_eq!(f.params[0].name, "a"); + assert_eq!(f.params[1].name, "b"); + assert!(matches!( + f.params[1].default, + Some(Expr::Literal(Literal::Text(ref s))) if s == "Hi" + )); + } + + #[test] + fn parse_foreach_backtick_ids() { + let src = "# main\n\n- [`x`](`xs`)\n > print text=`x`\n"; + let m = parse_source(src).unwrap(); + match &m.functions[0].body[0] { + Stmt::ForEach { item, collection, .. } => { + assert_eq!(item, "x"); + assert_eq!(collection, "xs"); + } + other => panic!("expected foreach, got {other:?}"), + } + } + + #[test] + fn parse_branch_rejects_plus_arm() { + let src = "# main\n\n+ `x` > 0\n > print text=ok\n"; + let err = parse_source(src).unwrap_err(); + let msg = format!("{err}"); + assert!( + msg.contains("unrecognized") || msg.contains("empty branch"), + "{msg}" + ); } #[test] diff --git a/src/view/html.rs b/src/view/html.rs index 68a9720..0bd5fd4 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -250,6 +250,7 @@ h1.page { vertical-align: middle; } .status-pill.ok { background: var(--surface); color: var(--muted); } +.status-pill.pending { background: var(--surface); color: var(--ink); border-color: var(--ink); } .status-pill.fail { background: var(--ink); color: #fff; border-color: var(--ink); } section.block { margin: 2rem 0; } section.block > h2 { @@ -469,6 +470,17 @@ section.block > h2 { padding: 0; overflow: hidden; } +.output-card { + border-left: 3px solid #2563eb; + background: #f8fafc; +} +.output-card .output-body { + margin: 0.35rem 0 0; + padding: 0.5rem 0.65rem; + font: 0.85rem/1.45 var(--mono); + white-space: pre-wrap; + color: #0f172a; +} .code-head { display: flex; flex-wrap: wrap; @@ -968,18 +980,26 @@ pub fn page_index(files: &[PathBuf], only: Option<&Path>, links: &LinkMode) -> S pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkMode) -> String { let nav = nav_html(files, Some(rel), links); - let status = if vm.ok { "ok" } else { "fail" }; - let status_label = if vm.ok { "ok" } else { "fail" }; - let out_text = if vm.ok { - if vm.stdout.is_empty() { - "(no stdout)".into() - } else { - escape(&vm.stdout) - } + let (status, status_label, out_text) = if vm.awaiting_input { + ( + "pending", + "input", + "Fill preset input below, then click Run with input.".to_string(), + ) + } else if vm.ok { + ( + "ok", + "ok", + if vm.stdout.is_empty() { + "(no stdout)".into() + } else { + escape(&vm.stdout) + }, + ) } else if vm.stderr.is_empty() { - "(skipped)".into() + ("fail", "fail", "(skipped)".into()) } else { - escape(&vm.stderr) + ("fail", "fail", escape(&vm.stderr)) }; let stdin_panel = if vm.input_prompts.is_empty() { String::new() diff --git a/src/view/mod.rs b/src/view/mod.rs index 2f0fcc4..f18aa71 100644 --- a/src/view/mod.rs +++ b/src/view/mod.rs @@ -17,7 +17,7 @@ use std::process::Command; use anyhow::{bail, Context, Result}; use tiny_http::{Header, Method, Request, Response, Server, StatusCode}; -use crate::input_feed::{effective_stdin, split_stdin_text}; +use crate::input_feed::{effective_stdin, extract_frontmatter_stdin, split_stdin_text}; use crate::view::debug_page::{build_debug_model, page_debug}; use crate::view::html::{escape, page_file, page_index, LinkMode}; use crate::view::render::{collect_input_prompts, render_module_structure, FileViewModel}; @@ -309,25 +309,30 @@ pub(crate) fn build_file_view( ), }; let effective = effective_stdin(&source, stdin_lines); + let awaiting_input = awaiting_preset_input(&input_prompts, stdin_lines, &source); // Same host caps as `marqdo run`. Soft exit + sleep clamp only. let mut opts = RunOptions::default(); opts.stdin_lines = effective.clone(); opts.sleep_limit_ms = if live { Some(30_000) } else { Some(0) }; // Optional: sandbox to the whole view tree so sibling folders are reachable. opts.fs_root = Some(root.root.clone()); - let (stdout, stderr, ok, plots) = match run_file_capture(abs, &opts) { - Ok(cap) => ( - cap.stdout, - String::new(), - true, - cap.plots.into_iter().map(|p| p.svg).collect(), - ), - Err(e) => ( - String::new(), - tidy_user_error(&format!("{e:#}"), abs, rel), - false, - Vec::new(), - ), + let (stdout, stderr, ok, plots) = if awaiting_input { + (String::new(), String::new(), true, Vec::new()) + } else { + match run_file_capture(abs, &opts) { + Ok(cap) => ( + cap.stdout, + String::new(), + true, + cap.plots.into_iter().map(|p| p.svg).collect(), + ), + Err(e) => ( + String::new(), + tidy_user_error(&format!("{e:#}"), abs, rel), + false, + Vec::new(), + ), + } }; Ok(FileViewModel { rel_path: rel.to_string(), @@ -339,10 +344,22 @@ pub(crate) fn build_file_view( ok, preset_stdin: effective.join("\n"), input_prompts, + awaiting_input, plots, }) } +/// Defer execution until the view preset-input form supplies lines (no query stdin, no FM stdin). +pub(crate) fn awaiting_preset_input( + input_prompts: &[String], + stdin_lines: &[String], + source: &str, +) -> bool { + !input_prompts.is_empty() + && stdin_lines.is_empty() + && extract_frontmatter_stdin(source).is_empty() +} + /// Prefer view-relative paths and strip Windows `\\?\` noise in error text. fn tidy_user_error(msg: &str, abs: &Path, rel: &str) -> String { use crate::diagnostics::display_path; @@ -544,3 +561,21 @@ fn open_url(url: &str) -> Result<()> { } Ok(()) } + +#[cfg(test)] +mod tests { + use super::awaiting_preset_input; + + #[test] + fn awaiting_input_when_no_stdin_source() { + let src = include_str!("../../tests/keywords/input.mq.md"); + assert!(awaiting_preset_input(&["Name: ".into()], &[], src)); + assert!(!awaiting_preset_input(&["Name: ".into()], &["Ada".into()], src)); + } + + #[test] + fn not_awaiting_when_frontmatter_stdin() { + let src = "---\nstdin: Ada\n---\n\n# main\n\n*`n` = > input*\n"; + assert!(!awaiting_preset_input(&["p".into()], &[], src)); + } +} diff --git a/src/view/render.rs b/src/view/render.rs index 67cb832..5011e47 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -3,9 +3,12 @@ //! Comments are not in the AST; they are interleaved from classified source lines. //! Expressions are shown in surface syntax, never Rust `Debug`. +use std::collections::HashMap; + use crate::ast::{ Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp, }; +use crate::host::writeback; use crate::lex::{classify_source, ClassifiedLine, LineKind}; use crate::view::html::escape; use pulldown_cmark::{html, Options, Parser}; @@ -32,6 +35,8 @@ pub struct FileViewModel { /// One entry per `input` / `输入` call (prompt text; may be empty). /// Empty vec → page does not use input; hide the preset form. pub input_prompts: Vec, + /// Live view: program uses `input` but no stdin yet — execution deferred until form submit. + pub awaiting_input: bool, /// SVG plots from math lib (embedded in Execution). pub plots: Vec, } @@ -163,6 +168,7 @@ pub fn render_module_structure_mode( mode: StructureMode, ) -> String { let lines = classify_source(source); + let writebacks = writeback::writeback_map(source); let mut out = String::new(); if !module.imports.is_empty() { @@ -193,7 +199,7 @@ pub fn render_module_structure_mode( if i > 0 { out.push_str(&emit_comments(&lines, cursor, fun.span.line)); } - let (html, next) = render_fun(fun, &lines, 0, "", mode); + let (html, next) = render_fun(fun, &lines, 0, "", mode, &writebacks); out.push_str(&html); cursor = next; } @@ -294,8 +300,7 @@ fn emit_comments(lines: &[ClassifiedLine], from_line: u32, before_line: u32) -> paragraph.push(text.to_string()); } } - LineKind::Blank => flush(&mut paragraph, &mut s), - LineKind::Code => flush(&mut paragraph, &mut s), + LineKind::Blank | LineKind::Writeback | LineKind::Code => flush(&mut paragraph, &mut s), } } flush(&mut paragraph, &mut s); @@ -320,6 +325,7 @@ fn render_fun( depth: usize, parent_path: &str, mode: StructureMode, + writebacks: &HashMap, ) -> (String, u32) { let fn_path = fn_path(parent_path, &fun.name); let mut s = String::new(); @@ -338,7 +344,7 @@ fn render_fun( if !fun.params.is_empty() { s.push_str("
"); for p in &fun.params { - s.push_str(&format!("{}", escape(p))); + s.push_str(&format!("{}", escape(&p.name))); } s.push_str("
"); } @@ -375,14 +381,14 @@ fn render_fun( let stmt = &fun.body[bi]; let start = stmt_start(stmt); s.push_str(&emit_comments(lines, cursor, start)); - let (html, end) = render_stmt(stmt, lines, mode); + let (html, end) = render_stmt(stmt, lines, mode, writebacks); s.push_str(&html); cursor = end; bi += 1; } else { let child = &fun.children[ci]; s.push_str(&emit_comments(lines, cursor, child.span.line)); - let (html, end) = render_fun(child, lines, depth + 1, &fn_path, mode); + let (html, end) = render_fun(child, lines, depth + 1, &fn_path, mode, writebacks); s.push_str(&format!("
{html}
")); cursor = end; ci += 1; @@ -427,7 +433,22 @@ fn stmt_end_line(stmt: &Stmt) -> u32 { } } -fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine], mode: StructureMode) -> (String, u32) { +fn output_card(line: u32, writebacks: &HashMap) -> String { + match writebacks.get(&line) { + Some(body) => format!( + r#"
output
{}
"#, + escape(body) + ), + None => String::new(), + } +} + +fn render_stmt( + stmt: &Stmt, + lines: &[ClassifiedLine], + mode: StructureMode, + writebacks: &HashMap, +) -> (String, u32) { let end = stmt_end_line(stmt); let line = stmt_start(stmt); let inner = match stmt { @@ -509,7 +530,7 @@ fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine], mode: StructureMode) -> (S for st in &arm.body { let start = stmt_start(st); body.push_str(&emit_comments(lines, arm_cursor, start)); - let (h, e) = render_stmt(st, lines, mode); + let (h, e) = render_stmt(st, lines, mode, writebacks); body.push_str(&h); arm_cursor = e; } @@ -529,7 +550,7 @@ fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine], mode: StructureMode) -> (S for st in body { let start = stmt_start(st); body_html.push_str(&emit_comments(lines, cursor, start)); - let (h, e) = render_stmt(st, lines, mode); + let (h, e) = render_stmt(st, lines, mode, writebacks); body_html.push_str(&h); cursor = e; } @@ -551,7 +572,7 @@ fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine], mode: StructureMode) -> (S for st in body { let start = stmt_start(st); body_html.push_str(&emit_comments(lines, cursor, start)); - let (h, e) = render_stmt(st, lines, mode); + let (h, e) = render_stmt(st, lines, mode, writebacks); body_html.push_str(&h); cursor = e; } @@ -559,6 +580,7 @@ fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine], mode: StructureMode) -> (S body_html } }; + let inner = format!("{}{}", inner, output_card(line, writebacks)); (stmt_shell(line, &inner, mode), end) } diff --git a/tests/errors/bad-arity.mq.md b/tests/errors/bad-arity.mq.md index 74c74c4..0fad187 100644 --- a/tests/errors/bad-arity.mq.md +++ b/tests/errors/bad-arity.mq.md @@ -7,6 +7,6 @@ title: bad arity > needs_one ## needs_one - - x + + `x` > print text=`x` diff --git a/tests/ext/agent-run-live.mq.md b/tests/ext/agent-run-live.mq.md deleted file mode 100644 index ef648b6..0000000 --- a/tests/ext/agent-run-live.mq.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -title: ext/agent run live (DeepSeek) -description: Real 执行 via tests/ext/.env (gitignored). Skipped in CI when .env missing. -> ext/ai/agent.mq.md -> lib/time.mq.md ---- - -## 获取时间 - -*`u` = > now_unix * -**> format unix=`u` pattern=%Y%m%d ** - -# main - -> load_env - -*`模型` = > llm * - -`工具表` = -| 工具 | -|------| -| 获取时间 | - -*`助手` = > agent model=`模型` tools=`工具表` user_prompt=你是测试助手。需要工具时,必须只回复一行 TOOL:函数名,不要其它文字。 * - -*`id` = > get value=`助手` key=id * - -*`回复` = > `助手`.run extra=请调用获取时间工具,并把当前日期告诉用户。 * - -> print text=`回复` - -*`历史1` = > host_agent_history_get id=`id` * -*`条数1` = > len value=`历史1` * -> print text=`条数1` - -> `助手`.clear_history - -*`历史2` = > host_agent_history_get id=`id` * -*`条数2` = > len value=`历史2` * -> print text=`条数2` diff --git a/tests/ext/agent-smoke.mq.md b/tests/ext/agent-smoke.mq.md index 77089a5..5018900 100644 --- a/tests/ext/agent-smoke.mq.md +++ b/tests/ext/agent-smoke.mq.md @@ -20,24 +20,24 @@ description: Ctor, context, clear_history — no network. Gold suite. *`has_skill` = > split value=`ctx` sep=Marqdo * *`sk_n` = > len value=`has_skill` * -+ `sk_n` > 1 +1. `sk_n` > 1 > print text=skill-ok -+ * +2. * > print text=skill-missing *`has_tools` = > split value=`ctx` sep=获取时间 * *`tool_n` = > len value=`has_tools` * -+ `tool_n` > 1 +1. `tool_n` > 1 > print text=tools-ok -+ * +2. * > print text=tools-missing *`src` = > host_module_source * *`has_src` = > split value=`src` sep=probe * *`src_n` = > len value=`has_src` * -+ `src_n` > 1 +1. `src_n` > 1 > print text=source-ok -+ * +2. * > print text=source-missing *`turn` = > parse text={"role":"user","content":"one"} * diff --git a/tests/gold.rs b/tests/gold.rs index 1eba0fc..1ceeb85 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -129,6 +129,19 @@ fn structure_paragraph_comment() { assert_out("tests/structure/paragraph-comment.mq.md", "ok"); } +#[test] +fn structure_narrative_bold() { + assert_out("tests/structure/narrative-bold.mq.md", "ok"); +} + +#[test] +fn structure_optional_param() { + assert_out( + "tests/structure/optional-param.mq.md", + "Hi, Ada!\nHello, Bob!", + ); +} + #[test] fn keywords_print() { assert_out( @@ -348,6 +361,23 @@ fn keywords_input() { ); } +#[test] +fn keywords_input_escape() { + for backend in ["tree", "bytecode"] { + assert_out_stdin( + "tests/keywords/input-escape.mq.md", + backend, + "Ada\n", + "Name:\nHello Ada!", + ); + } +} + +#[test] +fn keywords_quoted_string() { + assert_out("tests/keywords/quoted-string.mq.md", "a\nb"); +} + #[test] fn keywords_input_stdin_file() { let (code, stdout, stderr) = run(&[ @@ -557,6 +587,28 @@ fn view_output_writes_html() { assert!(dir.join("pages").join("hello.mq.md.html").exists()); } +#[test] +fn view_input_static_awaits_stdin() { + let dir = tempfile_dir("mq-input-view"); + let (code, _, stderr) = run(&[ + "view", + "output", + "tests/keywords/input.mq.md", + "-o", + dir.to_str().unwrap(), + ]); + assert_eq!(code, 0, "{stderr}"); + let page = std::fs::read_to_string(dir.join("pages").join("input.mq.md.html")).unwrap(); + assert!( + page.contains("Fill preset input") || page.contains("status-pill pending"), + "should defer execution, not fail" + ); + assert!( + !page.contains("input needs a line"), + "static export should not surface input error before stdin" + ); +} + #[test] fn lib_fs_read() { assert_out("tests/lib/fs-read.mq.md", "exists\nhello-lib"); @@ -590,6 +642,16 @@ fn lib_sys_dotenv() { assert_out("tests/lib/sys-dotenv.mq.md", "loaded"); } +#[test] +fn lib_writeback_get() { + assert_out("tests/lib/writeback-get.mq.md", "hello-writeback"); +} + +#[test] +fn lib_subtask_spawn() { + assert_out("tests/lib/subtask-spawn.mq.md", "done"); +} + #[test] fn lib_json_quote() { assert_out("tests/lib/json-quote.mq.md", "\"hi\""); diff --git a/tests/keywords/bool-logic.mq.md b/tests/keywords/bool-logic.mq.md index 154737b..0b0745c 100644 --- a/tests/keywords/bool-logic.mq.md +++ b/tests/keywords/bool-logic.mq.md @@ -7,14 +7,14 @@ title: 布尔与逻辑关键字 *`a` = True* *`b` = False* -+ `a` and not `b` +1. `a` and not `b` > print text=ok -+ * +2. * > print text=fail *`probe` = 1* -+ None +1. None > print text=none-truthy -+ * +2. * > print text=none-falsy diff --git a/tests/keywords/input-escape.mq.md b/tests/keywords/input-escape.mq.md new file mode 100644 index 0000000..37400f5 --- /dev/null +++ b/tests/keywords/input-escape.mq.md @@ -0,0 +1,10 @@ +--- +title: input quoted prompt +stdin: Ada +--- + +# main + +*`name` = > input prompt="Name:\n"* + +> print text=Hello `name`! diff --git a/tests/keywords/quoted-string.mq.md b/tests/keywords/quoted-string.mq.md new file mode 100644 index 0000000..ef79fbd --- /dev/null +++ b/tests/keywords/quoted-string.mq.md @@ -0,0 +1,9 @@ +--- +title: quoted string literal +--- + +# main + +*`s` = "a\nb"* + +> print text=`s` diff --git a/tests/keywords/zh-bool.mq.md b/tests/keywords/zh-bool.mq.md index 9631870..ef96009 100644 --- a/tests/keywords/zh-bool.mq.md +++ b/tests/keywords/zh-bool.mq.md @@ -7,14 +7,14 @@ title: 中文布尔与逻辑 *`a` = 真* *`b` = 假* -+ `a` 且 非 `b` +1. `a` 且 非 `b` > 打印 内容=ok -+ * +2. * > 打印 内容=fail *`probe` = 1* -+ 空 +1. 空 > 打印 内容=none-truthy -+ * +2. * > 打印 内容=none-falsy diff --git a/tests/lib/fs-read.mq.md b/tests/lib/fs-read.mq.md index b9bfedd..e0729d6 100644 --- a/tests/lib/fs-read.mq.md +++ b/tests/lib/fs-read.mq.md @@ -7,9 +7,9 @@ title: fs read/exists *`ok` = > exists path=hello.txt * -+ `ok` +1. `ok` > print text=exists -+ * +2. * > print text=missing *`t` = > read_text path=hello.txt * diff --git a/tests/lib/subtask-child.mq.md b/tests/lib/subtask-child.mq.md new file mode 100644 index 0000000..45247a9 --- /dev/null +++ b/tests/lib/subtask-child.mq.md @@ -0,0 +1,7 @@ +--- +title: subtask child +--- + +# main + +> print text=child-ok diff --git a/tests/lib/subtask-spawn.mq.md b/tests/lib/subtask-spawn.mq.md new file mode 100644 index 0000000..7450095 --- /dev/null +++ b/tests/lib/subtask-spawn.mq.md @@ -0,0 +1,12 @@ +--- +title: subtask spawn join +> lib/subtask.mq.md +--- + +# main + +*`id` = > spawn path=subtask-child.mq.md * + +*`code` = > wait id=`id` * + +> print text=done diff --git a/tests/lib/sys-cwd.mq.md b/tests/lib/sys-cwd.mq.md index 53606fb..bfcda48 100644 --- a/tests/lib/sys-cwd.mq.md +++ b/tests/lib/sys-cwd.mq.md @@ -9,7 +9,7 @@ title: sys cwd *`n` = > len `d` * -+ `n` > 0 +1. `n` > 0 > print text=cwd-ok -+ * +2. * > print text=cwd-empty diff --git a/tests/lib/writeback-get.mq.md b/tests/lib/writeback-get.mq.md new file mode 100644 index 0000000..41c357a --- /dev/null +++ b/tests/lib/writeback-get.mq.md @@ -0,0 +1,14 @@ +--- +title: writeback get +> lib/writeback.mq.md +--- + +# main + +*`out` = > get * + + + +> print text=`out` diff --git a/tests/lib/文件-读.mq.md b/tests/lib/文件-读.mq.md index 1634154..c718dac 100644 --- a/tests/lib/文件-读.mq.md +++ b/tests/lib/文件-读.mq.md @@ -7,9 +7,9 @@ title: 中文文件库 *`有` = > 存在 路径=hello.txt * -+ `有` +1. `有` > 打印 内容=存在 -+ * +2. * > 打印 内容=缺失 *`t` = > 读文本 路径=hello.txt * diff --git a/tests/structure/branch.mq.md b/tests/structure/branch.mq.md index 462d442..80cecfb 100644 --- a/tests/structure/branch.mq.md +++ b/tests/structure/branch.mq.md @@ -6,9 +6,9 @@ title: 分支示例 *`x` = 0* -+ `x` > 0 +1. `x` > 0 > print text=正数 -+ `x` < 0 +2. `x` < 0 > print text=负数 -+ * +3. * > print text=零 diff --git a/tests/structure/collection.mq.md b/tests/structure/collection.mq.md index 4f7f200..7604560 100644 --- a/tests/structure/collection.mq.md +++ b/tests/structure/collection.mq.md @@ -12,5 +12,5 @@ title: 集合(表格)示例 | 梨 | | 桃 | -- [果](篮子) +- [`果`](`篮子`) > print text=`果` diff --git a/tests/structure/fn-end-empty-return.mq.md b/tests/structure/fn-end-empty-return.mq.md index eaa24a8..f2c36ca 100644 --- a/tests/structure/fn-end-empty-return.mq.md +++ b/tests/structure/fn-end-empty-return.mq.md @@ -8,7 +8,7 @@ description: **** 空返回并结束函数体 > 问候 谁=Marqdo ## 问候 - - 谁 + + `谁` > print text=Hi `谁`! diff --git a/tests/structure/fn-end-hr.mq.md b/tests/structure/fn-end-hr.mq.md index c0df578..74e5423 100644 --- a/tests/structure/fn-end-hr.mq.md +++ b/tests/structure/fn-end-hr.mq.md @@ -8,7 +8,7 @@ description: --- 结束嵌套函数体,后续调用属于外层 > 问候 谁=World ## 问候 - - 谁 + + `谁` > print text=Hello `谁`! diff --git a/tests/structure/import/utils.mq.md b/tests/structure/import/utils.mq.md index b2e4eed..904363e 100644 --- a/tests/structure/import/utils.mq.md +++ b/tests/structure/import/utils.mq.md @@ -4,11 +4,11 @@ description: 供 frontmatter > 导入;返回用粗体;副作用用输出函 --- ## 加一 - - n + + `n` **`n` + 1** ## 问候 - - 谁 + + `谁` > print text=你好,`谁`! diff --git a/tests/structure/loop.mq.md b/tests/structure/loop.mq.md index 019a59b..d130d1d 100644 --- a/tests/structure/loop.mq.md +++ b/tests/structure/loop.mq.md @@ -21,5 +21,5 @@ title: 循环示例 | 苹果 | | 梨 | -- [果](篮子) +- [`果`](`篮子`) > print text=今天吃`果` diff --git a/tests/structure/narrative-bold.mq.md b/tests/structure/narrative-bold.mq.md new file mode 100644 index 0000000..47f7b50 --- /dev/null +++ b/tests/structure/narrative-bold.mq.md @@ -0,0 +1,12 @@ +--- +title: narrative bold in comment paragraph +description: **强调** mid-line must stay comment, not return syntax +--- + +# main + +说明如下 + +**强调信息**是什么什么 + +> print text=ok diff --git a/tests/structure/nested-call.mq.md b/tests/structure/nested-call.mq.md index 94026f0..20f4497 100644 --- a/tests/structure/nested-call.mq.md +++ b/tests/structure/nested-call.mq.md @@ -10,6 +10,6 @@ description: Recommended entry — nested fn; print builtin; bold return > 问候 谁=World ## 问候 - - 谁 + + `谁` > print text=Hello `谁`! diff --git a/tests/structure/object-handle.mq.md b/tests/structure/object-handle.mq.md index e4980f0..67b70eb 100644 --- a/tests/structure/object-handle.mq.md +++ b/tests/structure/object-handle.mq.md @@ -4,7 +4,7 @@ title: object handle smoke --- # counter - - n + + `n` *`t` = > parse text={"p":"{\"n\":","s":"}"} * *`qn` = > str `n` * diff --git a/tests/structure/optional-param.mq.md b/tests/structure/optional-param.mq.md new file mode 100644 index 0000000..19d611d --- /dev/null +++ b/tests/structure/optional-param.mq.md @@ -0,0 +1,15 @@ +--- +title: optional param default +--- + +# main + +> tag name=Ada + +> tag name=Bob suffix=Hello + +## tag + + `name` + + `suffix`=Hi + +> print text=`suffix`, `name`! diff --git a/tests/structure/positional-call.mq.md b/tests/structure/positional-call.mq.md index 7da7848..99f9b17 100644 --- a/tests/structure/positional-call.mq.md +++ b/tests/structure/positional-call.mq.md @@ -14,6 +14,6 @@ description: `> fn value` binds by parameter order; named form still works > 问候 谁=World ## 问候 - - 谁 + + `谁` > print text=Hello `谁`!