feat(markup): code-as-docs narration surface (G1–G4) and drop --- body end
Treat --- as Markdown HR everywhere, end side-effect helpers with empty returns, and accept soft emphasis, float literals, and dynamic footnote keys so LLM-friendly .mq.md stays runnable. Ship the weekend coffee example plus gold fixtures. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b5c07385e9
commit
5e74ff39f2
28 files changed
+799
-99
No files matched your search
@@ -88,6 +88,8 @@ Better still — call a named helper:
|
||||
3. `##` handlers: short prose OK; data as tables; return via `browser.*` / `web.*` / one `table.put`.
|
||||
4. Blank line between comment paragraphs and code.
|
||||
5. Run `marqdo run path.mq.md` from repo root.
|
||||
6. **Calls in narrative:** prefer `**结果 = 某函数 名=`x`**` (no `>` on the RHS). Use `> …` for standalone step lists. See `examples/code-as-docs/`.
|
||||
7. **Do not use `##` inside `# main` for document sectioning** — those become nested functions. Use paragraphs / `---` breaks instead.
|
||||
|
||||
Browser client programs: prefer `import browser:lib/browser.mq.md` (no native plugin). Server sites: `ext/web` + GFM page/style tables.
|
||||
|
||||
|
||||
@@ -25,12 +25,12 @@ Canonical design (repo): [`markdown-mapping-v0.3.md`](../../doc/design/markdown-
|
||||
|
||||
1. **File suffix** must be `.mq.md` (never plain `.md` for executable sources).
|
||||
2. **`**…**` = code** (assign / call). **`*…*` = return value**. Output is **not** either marker — use `> print text=…` / `**print text="…"**` / `> 打印 内容=…`.
|
||||
3. **Prose:** unmarked narrative may contain `` `名` `` (declare/ref), inline `**code**`, and `*return*`. Do **not** use `*`/`**` for Markdown emphasis in program files. Dead `` `名` `` (never read) is OK and does not become a param.
|
||||
3. **Prose:** unmarked narrative may contain `` `名` `` (declare/ref), inline `**code**`, and `*return*`. Soft Markdown emphasis that is **not** code-shaped (`**说明**`, mid-line `*only*`) is ignored — see [code-as-docs-gaps.md](../../doc/design/code-as-docs-gaps.md). Dead `` `名` `` (never read) is OK and does not become a param.
|
||||
4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**. Params: prefer prose `` `名` `` / `` `名`=默认 `` (inferred); `` + `名` `` still accepted.
|
||||
5. **Identifiers:** `` `名` `` in prose; inside `*…*` / `**…**`, bare ids are **variables**. **Text literals must be quoted** in bold/italic: `**print text="hi"**`. Standalone `>` calls: bare words = text; vars need ticks: `` > str `n` ``.
|
||||
6. **Structure lines** (`#` `>` `+` `-` `|` `1.`) need not be wrapped in bold.
|
||||
7. **Paths:** In bare expressions `/` is division. In call args / defaults / table cells, unspaced `a/b` and quoted paths are text.
|
||||
8. Prefer ending side-effect-only bodies with `---` / `***` (or `*None*` / whole-line `**` / `****`).
|
||||
8. Prefer ending side-effect-only bodies with `*None*` / `*无*` / whole-line `**` / `****` when the next lines must belong to an outer function. Lone `---` / `***` are Markdown thematic breaks (skipped everywhere), not function end.
|
||||
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
|
||||
10. **Browser (route C/D/E/F):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, canvas, file read, observers — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount. Client effects: prefer **GFM tables + `lib/browser`** ([marqdo-dev](../marqdo-dev/SKILL.md)).
|
||||
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug.
|
||||
@@ -53,7 +53,7 @@ Canonical design (repo): [`markdown-mapping-v0.3.md`](../../doc/design/markdown-
|
||||
| `**…**` | **Code** (assign / call) — closing `**` touches last token; bare ids are variables; quote text literals |
|
||||
| `*…*` | **Return value** — closing `*` touches last token; bare ids are variables |
|
||||
| `****` / whole-line `**` / `*None*` | Return `None` and end function body |
|
||||
| Lone `---` / `***` in function body | End function body (no value) |
|
||||
| Lone `---` / `***` | Markdown thematic break (skip; not function end) |
|
||||
| GFM table after empty RHS bind | Collection (1-col list / ≥2-col map / `@`·`行`·`row` → list of maps); `` `x`[^1] `` / `` `m`[^key] `` |
|
||||
| `` ```lang `` | Foreign code block (via `lib/foreign`) |
|
||||
| `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped |
|
||||
@@ -89,12 +89,13 @@ Chinese builtins (same functions, no import):
|
||||
|
||||
> print text=Hello, `who`!
|
||||
|
||||
---
|
||||
*None*
|
||||
```
|
||||
|
||||
- Call: `> name key=value` or `> name value`.
|
||||
- Nested helpers use deeper `#` (`##`, `###`, …).
|
||||
- After a helper with only side effects, end with `---` / `***`.
|
||||
- After a helper with only side effects, end with `*None*` / whole-line `**` / `****` when later lines must stay in the outer function. Lone `---` is only a thematic break (skipped).
|
||||
- In bold assigns, prefer bare calls: `**摘要 = 结账摘要 …**` (omit `>`).
|
||||
|
||||
## Statements, returns, branches
|
||||
|
||||
@@ -256,7 +257,7 @@ Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../
|
||||
| `* > print text=hi *` | `> print text=hi` |
|
||||
| `` *`a` = 1 * `` (trailing space + backticks) | `*a = 1*` — bare bind, no trailing space before `*` / `**` |
|
||||
| `*xs = > text.split value=a,b sep=,*` (bare text args) | `*xs = > text.split value="a,b" sep=","*` — quote text literals; bare words are variables |
|
||||
| Forgetting `---` after nested `##` helper | Add `---` / `***` / `****` |
|
||||
| Forgetting empty return after nested `##` helper when outer continues | Add `*None*` / `**` / `****` (not `---`) |
|
||||
| Import `lib/text` then call bare `split` | `> text.split …` (qualified) |
|
||||
| Import `lib/text` then call `拆分` | Match file language (`text.split`, not 文本) |
|
||||
| `json.set` / `json.append` to build maps or lists | GFM tables; sparse `table.put`; named helpers (`browser.*`, `web.*`) |
|
||||
@@ -276,7 +277,7 @@ Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../
|
||||
- [ ] Print via `print` / `打印`, not bold
|
||||
- [ ] Blank lines separate comment paragraphs from code
|
||||
- [ ] `# main` exists when the file is an entry program
|
||||
- [ ] Nested functions ended with `---` / `***` / `****` when needed
|
||||
- [ ] Nested side-effect helpers ended with `*None*` / `**` / `****` when the outer function continues
|
||||
- [ ] Imports and call names share the same language file
|
||||
- [ ] Data shaped as **GFM tables** (or short helpers) — no `json.set` / `json.append` glue
|
||||
- [ ] Web sites: tables + web classes only (no JSON glue); `data/` gitignored
|
||||
|
||||
@@ -38,8 +38,9 @@ Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,
|
||||
| `+` / `1.` … | 函数头下 `` + `名` `` = 形参;体内 `1.` `2.` … = 分支(`N. *` = else) |
|
||||
| `-` | 循环(`` - `条件` `` 或 `` - [项](集合) `` / `` - [`项`](`集合`) ``) |
|
||||
| 表格 | 集合 |
|
||||
| 函数体内单独一行 `---` / `***` | **结束本函数体**(无返回值收束;见 mapping §11) |
|
||||
| 文件开头成对 `---` … `---` | Frontmatter(元信息 / 导入),与函数结束符消歧 |
|
||||
| 单独一行 `---` / `***` | **叙述分隔**(跳过;不是函数收束) |
|
||||
| 空返回 `*None*` / 整行 `**` / `****` | **结束本函数体**并返回 `None` |
|
||||
| 文件开头成对 `---` … `---` | Frontmatter(元信息 / 导入) |
|
||||
|
||||
```markdown
|
||||
# main
|
||||
@@ -51,7 +52,7 @@ Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,
|
||||
|
||||
> print text=Hello `谁`!
|
||||
|
||||
---
|
||||
*None*
|
||||
|
||||
## 加一
|
||||
+ `n`
|
||||
@@ -59,7 +60,7 @@ Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,
|
||||
**`n` + 1**
|
||||
```
|
||||
|
||||
完整约定:[markdown-mapping.md](doc/design/markdown-mapping.md)。
|
||||
完整约定:[markdown-mapping-v0.3.md](doc/design/markdown-mapping-v0.3.md)。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
# 代码即文档 · 叙述面摩擦(v0.3 实测)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Done** |
|
||||
| 日期 | 2026-09-14 |
|
||||
| 触发 | `examples/code-as-docs/index.mq.md` 试跑 |
|
||||
| 宪法 | [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) |
|
||||
| 路线 | [code-as-docs-gaps.md](../roadmap/code-as-docs-gaps.md) |
|
||||
|
||||
---
|
||||
|
||||
## 0. 原则
|
||||
|
||||
修复必须同时服务:
|
||||
|
||||
1. **代码即文档**:人读 Markdown 时自然段落、分隔线、强调不应被误伤。
|
||||
2. **适配 LLM 输出**:模型习惯写 `---` 分段、`**加粗强调**`、`0.85` 小数、`` map[^`key`] `` 动态键——运行时应尽量「写出来就能跑」。
|
||||
3. **可执行标记仍清晰**:真正的赋值 / 调用 / 返回不被误判成装饰。
|
||||
|
||||
---
|
||||
|
||||
## 1. 四个问题(实测)
|
||||
|
||||
### G1 — 模块级 `---` 被当成结构错误
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 现象 | 文件标题段落后写 Markdown 分隔线 `---`,报 `expected heading … got: ---` |
|
||||
| 根因 | 词法上整行 `-`/`*` 为 Code;旧实现把函数体内 `---` 当收束,模块顶却当非法。现统一为叙述跳过 |
|
||||
| 人/LLM 期望 | 任意处 `---` = GFM thematic break = **叙述噪音** |
|
||||
| 决议 | **处处** frame 行 skip;副作用收束用 `*None*` / `**` / `****`(返回即结束函数体解析) |
|
||||
|
||||
### G2 — 叙述里的 `**强调**` / `*斜体强调*` 被当成代码/返回
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 现象 | 「本文件既是**说明**也是**程序**」→ 粗体 `说明` 不是赋值/调用,解析失败;`*only*` 类英文强调升成返回/`only` 变量 |
|
||||
| 根因 | v0.3 叙述扫描凡 `**…**` / `*…*` 一律可执行([prose.rs](../../src/parse/prose.rs));Skill 曾禁止强调,但与 LLM/Markdown 习惯冲突 |
|
||||
| 人/LLM 期望 | 装饰性强调可出现;**像代码的**粗体/斜体仍执行 |
|
||||
| 决议 | **形状启发式**(见 §2):像代码则执行,否则当作叙述装饰(不产生 Stmt,不升参) |
|
||||
|
||||
### G3 — 小数面量 `0.85` 不可用
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 现象 | `**x = 0.85**` → `trailing input: ".85"`;`28 * 0.85` 解析错乱;即便进到求值,`*` 仍只接受 int |
|
||||
| 根因 | 表达式主词只吃整数字面量(`Literal` 无 `Num`);运行时已有 `Value::Num`,二元运算未接浮点 |
|
||||
| 人/LLM 期望 | `0.85`、`3.14`、`折扣=0.85` 可写可算 |
|
||||
| 决议 | 解析 `数字.数字` → `Literal::Num`;`*` `/` `+` `-` 及比较在 `Int`/`Num` 间提升(与已有 `cmp_ord` 一致) |
|
||||
|
||||
### G4 — 动态脚注键 `` 菜单[^`名`] ``
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 现象 | `` 菜单[^`名`] `` → `missing map key ``名`` `(把字面 `` `名` `` 当键,或解析失败) |
|
||||
| 根因 | `[^label]` 的 label 仅为**静态字符串**;AST `Expr::Index { label: String }` 无变量槽 |
|
||||
| 人/LLM 期望 | 表/映射按变量取键:`` `菜单`[^`品名`] `` 或 `菜单[^`品名`]` |
|
||||
| 决议 | 支持 `` [^`ident`] `` → 运行时用变量值作键(文本化后走现有 footnote get);静态 `[^拿铁]` 不变 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 粗体/斜体「像代码」启发式
|
||||
|
||||
### 粗体 `**inner**` → 可执行,当且仅当
|
||||
|
||||
满足任一:
|
||||
|
||||
- 含 `=`(赋值 / 命名参数调用);或
|
||||
- 以 `>` 开头(显式调用);或
|
||||
- 含运算符 / 索引 / 调用形:`+ - * / ( ) [ ]`;或
|
||||
- 空白分词 ≥2 段,且其后段含数字面量、引号串、或 `=`(如 `**加一 37**`、`**print text="hi"**`)
|
||||
|
||||
否则(如 `**说明**`、`**代码即文档**`)→ **装饰,忽略**。
|
||||
|
||||
### 斜体 `*inner*` → 返回,当且仅当
|
||||
|
||||
满足任一:
|
||||
|
||||
- 空 / `None` / `无` / `空` / bool 字面;或
|
||||
- 以 `>` 开头;或
|
||||
- 含 `=` 或运算符 / 索引;或
|
||||
- **整行**仅为 `*…*`(含缩进)——整行返回 `*总额*` / `*n*`;或
|
||||
- 行内且前方紧邻「返回」二字(叙述「接着返回*n*」)
|
||||
|
||||
否则行内简单词(如 `*only*`、`*named*`)→ **装饰,忽略**。
|
||||
|
||||
> 整行 `*n*` 仍是返回;行内「返回*n*。」仍是返回。英文强调词在句中被忽略。
|
||||
|
||||
---
|
||||
|
||||
## 3. 非目标
|
||||
|
||||
- 不恢复 v0.2 双模式
|
||||
- 不引入 `if`/`return` 关键字
|
||||
- 不把任意 `**任意自然语言句子**` 都当代码(必须过 §2)
|
||||
- 动态键第一期只做 `` [^`ident`] ``,不做完整表达式 `[^a+b]`
|
||||
|
||||
---
|
||||
|
||||
## 4. 验收
|
||||
|
||||
| 用例 | 期望 |
|
||||
|------|------|
|
||||
| 顶层段落之间的 `---` | 可解析、可运行 |
|
||||
| 「既是**说明**也是**程序**」 | 可解析;无 Stmt |
|
||||
| `**应付 = 原价 * 0.85**` / `折扣`=0.85 | 数值正确(浮点) |
|
||||
| `` **价 = 菜单[^`名`]** ``(`名` 已绑定) | 取到对应价 |
|
||||
| `examples/code-as-docs/index.mq.md` | 用回浮点折扣与动态键后仍绿 |
|
||||
| 既有 `tests/markup-v03/*` 与 gold | 不回归 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 修订历史
|
||||
|
||||
| 日期 | 说明 |
|
||||
|------|------|
|
||||
| 2026-09-14 | 初稿:四缝 + 启发式 + 验收 |
|
||||
| 2026-09-14 | 落地:G1–G4 实现 + 金样;顶层 Comment 引言 skip |
|
||||
@@ -74,7 +74,7 @@ v0.2 为了「标记即语法」的清晰边界,做了这些硬隔离:
|
||||
- **`*…*` = 返回值**(架构级),与粗体代码形成对立、易读的一对:
|
||||
- 做了什么 → 粗体
|
||||
- 结果是什么 → 斜体
|
||||
- **空返回 / 无值收束**(已决议,见 §7.2):推荐 `---` / `***`;显式 `*None*` / `*无*`;整行 `**` 为空斜体;`****` 兼容。
|
||||
- **空返回 / 无值收束**(已决议,见 §7.2):推荐 `*None*` / `*无*`;整行 `**`;兼容 `****`。`---` / `***` 仅为叙述分隔(跳过),**不再**结束函数体。
|
||||
- **输出仍不是返回**:打印继续用内置 `print` / `打印`(副作用函数),不把粗体或斜体当成「打印到终端」的语法。
|
||||
|
||||
### P4 — 形参由体推断(Body-inferred params)
|
||||
@@ -212,8 +212,8 @@ v0.3:
|
||||
| `N. *` | else 臂(此处 `*` 仍是「空条件」标记,**不是**返回值;见 §7.3) |
|
||||
| GFM 表格 | 集合(不变) |
|
||||
| ` ```lang ` | 外联(不变) |
|
||||
| 函数体内 `---` / `***` | **无值收束**(对齐其它语言的「空 return」,见 §7.2) |
|
||||
| 整行恰 `**` 或 `****` / `*None*` / `*无*` | **空返回**(见 §7.2) |
|
||||
| 单独一行 `---` / `***` | **叙述分隔**(跳过;模块顶与函数体内相同) |
|
||||
| 整行恰 `**` 或 `****` / `*None*` / `*无*` | **空返回**并结束本函数体(见 §7.2) |
|
||||
|
||||
### 结构行与粗体
|
||||
|
||||
@@ -238,6 +238,7 @@ v0.3:
|
||||
|------|----------|
|
||||
| `> …` | 步骤列表、独立可执行行、与 v0.2/AI 习惯兼容 |
|
||||
| `**…**` | 嵌在句子中:「或者可以直接这么调用**加一函数 37**」 |
|
||||
| `**x = 加一 37**` | 粗体赋值右侧为调用时**可省略 `>`**(代码即文档首选;`> 加一 37` 仍合法) |
|
||||
|
||||
### 6.2 粗体内调用的判别
|
||||
|
||||
@@ -287,47 +288,47 @@ Marqdo **不引入** `return` 关键字;「无值结束」用标记表达。
|
||||
|
||||
| 语言 | 无值 / 空返回 | Marqdo v0.3 对应 |
|
||||
|------|----------------|------------------|
|
||||
| Python | `return` / `return None` | 收束线 / 显式 `*None*`·`*无*` |
|
||||
| Go | 无结果函数里的 `return` | 收束线 `---` / `***` |
|
||||
| Rust | `()` 或函数末尾隐式 unit | 收束线;或显式空值返回 |
|
||||
| JavaScript | `return;` → `undefined` | 收束线 → 运行时 `None` |
|
||||
| Marqdo v0.2 | `****`(空粗体)或 `---` | 见下「兼容」 |
|
||||
| Python | `return` / `return None` | 显式 `*None*`·`*无*` |
|
||||
| Go | 无结果函数里的 `return` | `*None*` / 整行 `**` / `****` |
|
||||
| Rust | `()` 或函数末尾隐式 unit | 同上;或下一标题 / EOF 自然结束 |
|
||||
| JavaScript | `return;` → `undefined` | 同上 → 运行时 `None` |
|
||||
| Marqdo 历史 | `---` 收束;`****` | `---` 已改为叙述跳过;`****` 仍兼容 |
|
||||
|
||||
#### 形式层级(推荐自上而下)
|
||||
|
||||
| 优先级 | 形式 | 语义 | 说明 |
|
||||
|--------|------|------|------|
|
||||
| **1. 推荐收束** | 函数体顶层**整行**仅为 `---` 或 `***` | 结束本函数体;返回槽为空,运行时得 `None` | 对齐 Go/Rust「无值 return」;Markdown 分割线,**与粗体零冲突**;副作用函数首选 |
|
||||
| **2. 显式空值** | `*None*` 或 `*无*`(整段或行内返回位) | 返回 `None` 并结束函数体 | 对齐 Python `return None`;人读最清楚 |
|
||||
| **3. 空斜体标记** | **整行** trim 后恰为两个星号:`**` | 同上:空返回 `None` 并结束体 | 词法钉死:`^\s*\*\*\s*$` → **空斜体返回**,**不得**当成粗体开闭;禁止写成 `* *`(中间空白) |
|
||||
| **4. 兼容 v0.2** | 整行 `****`(四个星号) | 同空返回 | 迁移期识别;实现可 warning:建议改为 `---` 或 `*None*` |
|
||||
| **1. 显式空值** | `*None*` 或 `*无*`(整段或行内返回位) | 返回 `None` **并结束本函数体解析** | 对齐 Python `return None`;副作用函数首选;外层续写依赖此收束 |
|
||||
| **2. 空斜体标记** | **整行** trim 后恰为两个星号:`**` | 同上 | 词法钉死:`^\s*\*\*\s*$` → **空斜体返回**,**不得**当成粗体开闭 |
|
||||
| **3. 兼容** | 整行 `****`(四个星号) | 同空返回 | 迁移期识别 |
|
||||
| **(非收束)** | 整行 `---` / `***` | **仅叙述分隔**,跳过 | 不再结束函数;见 [code-as-docs-gaps.md](code-as-docs-gaps.md) |
|
||||
|
||||
```markdown
|
||||
## 只打印
|
||||
**print text=hi**
|
||||
---
|
||||
|
||||
## 显式空
|
||||
**print text=hi**
|
||||
*None*
|
||||
|
||||
## 空斜体行(允许,次选)
|
||||
## 空斜体行
|
||||
**print text=hi**
|
||||
**
|
||||
|
||||
## 分割线不收束(下一标题才结束)
|
||||
**print text=hi**
|
||||
---
|
||||
```
|
||||
|
||||
#### 词法消歧(空斜体 vs 粗体)
|
||||
|
||||
1. **整行恰好 `**`(两个 `*`)** → 空返回(规则 3),不是未闭合粗体。
|
||||
1. **整行恰好 `**`(两个 `*`)** → 空返回(规则 2),不是未闭合粗体。
|
||||
2. **粗体代码**至少包住一个非空内容:`**x**`、`**n=1**`;不允许「空粗体代码段」作为语句。
|
||||
3. **四个星号整行 `****`** → 兼容空返回(规则 4),不解释为「空粗体代码」。
|
||||
3. **四个星号整行 `****`** → 兼容空返回(规则 3),不解释为「空粗体代码」。
|
||||
4. 行内出现的 `**…**`(两侧还有叙述文字)按正常粗体代码扫描,不走「整行空返回」。
|
||||
|
||||
#### 与「有返回值」的关系
|
||||
|
||||
- 需要把值交回调用方 → 用非空斜体:`*n*`、`*n + 1*`。
|
||||
- 只做副作用、不要值 → 优先 `---` / `***`(不必再写空斜体)。
|
||||
- 同一函数路径上:先出现非空 `*…*` 返回即结束该路径;收束线用于「无斜体返回」的路径。
|
||||
- 需要把值交回调用方 → 用非空斜体:`*n*`、`*n + 1*`(返回即结束本函数体解析)。
|
||||
- 只做副作用、不要值 → 优先 `*None*` / `*无*` / 整行 `**`。
|
||||
- 下一标题或 EOF 也可结束体;**不要**再靠 `---` 收束。
|
||||
|
||||
### 7.3 与 else 臂 `N. *` 的消歧
|
||||
|
||||
@@ -557,7 +558,7 @@ FnDef.params:
|
||||
|
||||
| # | 议题 | 状态 | 决议摘要 |
|
||||
|---|------|------|----------|
|
||||
| 1 | 空返回词法 | **已决议** | §7.2:推荐 `---`/`***`;显式 `*None*`/`*无*`;整行 `**`;兼容 `****` |
|
||||
| 1 | 空返回词法 | **已决议** | §7.2:推荐 `*None*`/`*无*`;整行 `**`;兼容 `****`;`---` 仅叙述跳过 |
|
||||
| 2 | 提及性反引号 | **已决议** | §4.4:一律视作变量;未使用不报错、不升参;不设提及前缀 |
|
||||
| 3 | 粗体内调用 vs 赋值 | 建议 | 以 `=` 左值合法性优先 |
|
||||
| 4 | `` `n`+1 `` 误声明 | 建议 | 仅完整单个 code span `` `ident` `` 触发声明 |
|
||||
@@ -606,3 +607,4 @@ FnDef.params:
|
||||
|------|------|
|
||||
| 2026-09-13 | 初稿:叙述统一、粗体代码、斜体返回、形参体推断;Proposed |
|
||||
| 2026-09-13 | 决议空返回(§7.2)与提及性反引号(§4.4);形参改为「升参」与绑定图分离(§8.2) |
|
||||
| 2026-09-14 | §7.2:`---` 不再收束;返回语句结束函数体解析;空返回首选 `*None*` |
|
||||
@@ -13,7 +13,7 @@
|
||||
1. **`*…*` = 程序语句**。
|
||||
2. **`**…**` = 返回值**(架构级);空粗体 `****` / `** **` = 空返回(`None`)并结束函数体。
|
||||
3. **输出**用内置函数 **`print`**(英文),不是粗体,不是中文名。
|
||||
4. **`---` / `***`(函数体顶层)**:结束本函数体(无返回值函数收束);**不是**分支/循环装饰框。
|
||||
4. **`---` / `***`**:Markdown 叙述分隔(跳过);**不再**结束函数体。无值收束用 `*None*` / 整行 `**` / `****`(见 [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) §7.2)。
|
||||
5. **成段注释**:空行分段;段内续行不因首字符升级为代码。
|
||||
6. **否决**:无标记行 = 默认代码。
|
||||
|
||||
@@ -29,9 +29,9 @@
|
||||
|------|------|-----------|
|
||||
| 代码段 / 语句 | `*…*` | `**…**` |
|
||||
| 返回值 | `**…**` | `*…*` |
|
||||
| 空返回 | `****` / 空粗体;或 `---` | **推荐 `---`/`***`**;`*None*`/`*无*`;整行 `**`;兼容 `****` |
|
||||
| 空返回 | `****` / 空粗体;或 `---` | **推荐 `*None*`/`*无*`**;整行 `**`;兼容 `****`;`---` 仅叙述 |
|
||||
| 输出 | 仍为 `print` / `打印` | 不变 |
|
||||
| 无标记 = 默认代码 | 否决 | **仍否决** |
|
||||
| 叙述中 `` `名` `` | 通常无绑定义 | 一律变量;未使用 OK;升参需可执行面读取 |
|
||||
|
||||
完整规则与迁移见 [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md)。**本决议文件在默认切换完成前仍描述 v0.2。**
|
||||
完整规则与迁移见 [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md)。**v0.3 已为运行时;本文件历史决议中「`---` 收束」已废止。**
|
||||
@@ -0,0 +1,66 @@
|
||||
# 路线图:代码即文档叙述面摩擦(G1–G4)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **Done**(实现已合入工作树;金样绿) |
|
||||
| 日期 | 2026-09-14 |
|
||||
| 设计 | [code-as-docs-gaps.md](../design/code-as-docs-gaps.md) |
|
||||
| 样例 | `examples/code-as-docs/index.mq.md` |
|
||||
|
||||
---
|
||||
|
||||
## 里程碑
|
||||
|
||||
### M1 — 文档与金样夹具
|
||||
|
||||
- [x] 设计文档记录 G1–G4 与启发式
|
||||
- [x] 本路线图
|
||||
- [x] `tests/markup-v03/` 四缝金样 + `gold.rs` `markup_v03_*`
|
||||
|
||||
### M2 — G1 模块级 `---`
|
||||
|
||||
- [x] `parse_classified`:顶层 frame 行 skip;顶层 Comment 引言 skip
|
||||
- [x] 函数体内 `---` / `***` 改为叙述跳过(不再收束;空返回收束)
|
||||
- [x] 金样:`module-hr.mq.md`
|
||||
|
||||
### M3 — G3 浮点面量与运算
|
||||
|
||||
- [x] `Literal::Num(f64)`
|
||||
- [x] `parse_primary` 识别 `digits.digits`(及 `.5` / `3.` 形态)
|
||||
- [x] `eval_binary` + bytecode Int/Num 提升(Int/Int `/` 仍为整除)
|
||||
- [x] 金样:`float-discount.mq.md`
|
||||
|
||||
### M4 — G2 叙述强调启发式
|
||||
|
||||
- [x] `scan_prose_line`:非代码形粗体、非返回形行内斜体 → 丢弃
|
||||
- [x] 保持 `**n=n+1**`、`**加一 37**`、整行 `*n*`、「返回*n*」
|
||||
- [x] 更新 Skill:允许装饰性强调;可执行仍看形状
|
||||
- [x] 金样:`soft-emphasis.mq.md`
|
||||
|
||||
### M5 — G4 动态脚注键
|
||||
|
||||
- [x] AST:`IndexKey::{Lit,Var}`(`` [^`ident`] ``)
|
||||
- [x] 解析、求值、bytecode
|
||||
- [x] 金样:`dynamic-footnote.mq.md`
|
||||
- [x] 回写 `examples/code-as-docs`(浮点折扣 + 动态键)
|
||||
|
||||
### M6 — 出门
|
||||
|
||||
- [x] `examples/code-as-docs` 展示四缝修复后的写法
|
||||
- [x] `cargo test --test gold` 绿
|
||||
- [x] 设计验收覆盖(见金样)
|
||||
|
||||
---
|
||||
|
||||
## 顺序建议
|
||||
|
||||
G1(小)→ G3(中,Literal/运算)→ G2(启发式,依赖金样钉行为)→ G4(AST 面)→ 回写样例。
|
||||
|
||||
---
|
||||
|
||||
## 修订历史
|
||||
|
||||
| 日期 | 说明 |
|
||||
|------|------|
|
||||
| 2026-09-14 | 初稿 |
|
||||
| 2026-09-14 | 实现完成并勾选 |
|
||||
@@ -0,0 +1,21 @@
|
||||
# 代码即文档 · 周末咖啡手账
|
||||
|
||||
可读可跑的 v0.3 样例:`.mq.md` 同时是说明文和程序。
|
||||
|
||||
```bash
|
||||
marqdo run examples/code-as-docs/index.mq.md
|
||||
```
|
||||
|
||||
## 这份样例在示范什么
|
||||
|
||||
| 习惯 | 写法 |
|
||||
|------|------|
|
||||
| 数据给人读 | GFM 表当菜单 / 订单 |
|
||||
| 步骤嵌在句子里 | `**总额 = 价 * 杯数**`、返回 `*总额*` |
|
||||
| 装饰性强调 | `**说明**` 不执行(见设计 G2) |
|
||||
| 段落分隔 | 顶层或体内的 `---` 只是分割线 |
|
||||
| 浮点 | `折扣`=0.85 |
|
||||
| 动态键 | `` 菜单[^`名`] `` |
|
||||
| 调用 | 粗体赋值右侧 **可省略 `>`**:`**摘要 = 结账摘要 …**`;输出可用 `**打印 内容=…**` |
|
||||
|
||||
相关设计:[code-as-docs-gaps.md](../../doc/design/code-as-docs-gaps.md)、[markdown-mapping-v0.3.md](../../doc/design/markdown-mapping-v0.3.md) §6。
|
||||
@@ -0,0 +1,85 @@
|
||||
---
|
||||
title: 代码即文档 · 周末咖啡手账
|
||||
description: >-
|
||||
一份可读可跑的周末手账:菜单是表,计价写在段落里,主流程像日记。
|
||||
展示叙述统一写法、装饰性强调、分隔线、浮点折扣、动态脚注键,以及粗体内免 `>` 的调用。
|
||||
---
|
||||
|
||||
本文件既是**说明**也是**程序**。人读得到段落与表格;机器执行嵌在叙述里的粗体步骤,并把斜体当作返回值。
|
||||
不必回避 Markdown 强调——不像代码的 `**说明**` 只是装饰。段落之间也可以用分隔线:
|
||||
|
||||
---
|
||||
|
||||
## 单价
|
||||
|
||||
一杯标价为`价`的饮品,默认`杯数`=1。先算**总额 = 价 * 杯数**,再返回*总额*。
|
||||
|
||||
## 会员折
|
||||
|
||||
会员单需要原价`原价`;门店默认八五折,写作`折扣`=0.85。
|
||||
先算**应付 = 原价 * 折扣**,再返回*应付*。
|
||||
|
||||
## 结账摘要
|
||||
|
||||
客人点了`品名`,单价`价`,杯数`杯数`=1;是否`会员`=False。
|
||||
|
||||
小计交给单价:**小计 = 单价 价=`价` 杯数=`杯数`**。
|
||||
|
||||
1. `会员`
|
||||
**实付 = 会员折 原价=`小计`**
|
||||
**标签 = "会员价"**
|
||||
2. *
|
||||
**实付 = 小计**
|
||||
**标签 = "原价"**
|
||||
|
||||
拼成一句给人对账的话,然后返回:
|
||||
|
||||
**文案 = 品名 + " ×" + 杯数 + " → " + 标签 + " " + 实付**
|
||||
*文案*
|
||||
|
||||
## 加一
|
||||
|
||||
对于输入`n`,执行**n=n+1**接着返回*n*。
|
||||
|
||||
# main
|
||||
|
||||
周末手账从一张菜单开始。数据用表格写——人一眼能读,程序把它当成字典:
|
||||
|
||||
`菜单` =
|
||||
|
||||
| 美式 | 拿铁 | 燕麦拿铁 |
|
||||
|------|------|----------|
|
||||
| 18 | 28 | 32 |
|
||||
|
||||
---
|
||||
|
||||
第一单:会员双杯拿铁。品名先记在变量里,再用动态键取价;粗体赋值右侧是调用时不必再写 `>`:
|
||||
|
||||
**名 = "拿铁"**
|
||||
**摘要 = 结账摘要 品名=`名` 价=菜单[^`名`] 杯数=2 会员=True**
|
||||
**打印 内容=`摘要`**
|
||||
|
||||
对照一单非会员美式——品名已知,静态键即可:
|
||||
|
||||
**对照 = 结账摘要 品名="美式" 价=菜单[^美式]**
|
||||
**打印 内容=`对照`**
|
||||
|
||||
---
|
||||
|
||||
也可以把今日订单写成行表。循环里把行字段直接传给结账,少一层临时变量:
|
||||
|
||||
`今日订单` =
|
||||
|
||||
| @ | 品名 | 单价 | 杯数 | 会员 |
|
||||
|---|------|------|------|------|
|
||||
| 1 | 燕麦拿铁 | 32 | 1 | True |
|
||||
| 2 | 美式 | 18 | 2 | False |
|
||||
|
||||
- [`行`](`今日订单`)
|
||||
**一行 = 结账摘要 品名=行[^品名] 价=行[^单价] 杯数=行[^杯数] 会员=行[^会员]**
|
||||
**打印 内容=`一行`**
|
||||
|
||||
最后用加一收个尾,确认叙述里的位置调用也通:
|
||||
|
||||
**试算 = 加一 41**
|
||||
**打印 内容=`试算`**
|
||||
@@ -28,7 +28,7 @@ Named args can include spaces:
|
||||
|
||||
> print text=Welcome, `who`!
|
||||
|
||||
---
|
||||
*None*
|
||||
|
||||
Beyond the basics above, Marqdo also ships standard libraries: table, time, text, files, system, math, foreign, and more.
|
||||
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ English docs: [`00-welcome.mq.md`](00-welcome.mq.md) (English prose and English
|
||||
|
||||
> 打印 内容=欢迎,`谁`!
|
||||
|
||||
---
|
||||
*None*
|
||||
|
||||
除了上面的一些基本内容之外,我还开发了这个语言的一些标准库,包括表、时间、文本、文件、系统、数学和外联等标准库。
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.
|
||||
5. **Identifiers use backticks** — params `` + `name` ``. **Exemptions:** foreach `` - [item](coll) ``; footnote `` name[^key] ``; **inside italic `*…*` / bold `**…**`**, bare ids are **variables** (Python-style unified namespace) and method-call receivers are bare too. **Drop the backticks on value-expression variable names and method receivers inside `*…*` / `**…**`** — they are redundant once the `*…*`/`**…**` markers mark the segment as code: `*分类 = 分类[^苹果]*`, `**n * 2**`, `*p = > page.主体装配 组件=home*`. **Text literals must be quoted**: `*a = > text.split value=src sep=","*`. Backticks **still required** where a bare word is *not* a variable in **standalone `>` calls** (bare = text there): `` > str `n` ``, `` > `obj`.method ``. **No trailing space** inside `*…*` / `**…**` wrapped code: the closing marker must touch the last token directly (`*a = 1*`, `**n**`), never `` *a = 1 * ``.
|
||||
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. In **call args / param defaults / table cells**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed. Numeric ratios that must stay text use quotes (`"1/5"`, `"16/9"`); bare `1/5` is division.
|
||||
8. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed.
|
||||
8. Prefer ending side-effect-only function bodies with `*None*` / `*无*` / whole-line `**` / `****` when later lines must belong to an outer function. Lone `---` / `***` are Markdown thematic breaks (skipped), not function end.
|
||||
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
|
||||
10. **Browser (route C/D/E/F):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, canvas, file read, observers — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount. Client effects: prefer **GFM tables + `lib/browser`** ([marqdo-dev](../marqdo-dev/SKILL.md)).
|
||||
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug.
|
||||
@@ -53,7 +53,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.
|
||||
| `*…*` | Statement (bind / expr) — closing `*` touches last token, **no trailing space**; bare ids are variables |
|
||||
| `**…**` | Return value — closing `**` touches last token, **no trailing space**; bare ids are variables |
|
||||
| `****` or `**` + spaces + `**` | Return `None` and end function body |
|
||||
| Lone `---` / `***` in function body | End function body (no value) |
|
||||
| Lone `---` / `***` | Markdown thematic break (skip; not function end) |
|
||||
| GFM table after empty RHS bind | Collection (1-col list / ≥2-col map / `@`·`行`·`row` → list of maps); `` `x`[^1] `` / `` `m`[^key] `` |
|
||||
| `` ```lang `` | Foreign code block (via `lib/foreign`) |
|
||||
| `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped |
|
||||
@@ -89,12 +89,13 @@ Chinese builtins (same functions, no import):
|
||||
|
||||
> print text=Hello, `who`!
|
||||
|
||||
---
|
||||
*None*
|
||||
```
|
||||
|
||||
- Call: `> name key=value` or `> name value`.
|
||||
- Nested helpers use deeper `#` (`##`, `###`, …).
|
||||
- After a helper with only side effects, end with `---` / `***`.
|
||||
- After a helper with only side effects, end with `*None*` / whole-line `**` / `****` when later lines must stay in the outer function. Lone `---` is only a thematic break (skipped).
|
||||
- In bold assigns, prefer bare calls: `**摘要 = 结账摘要 …**` (omit `>`).
|
||||
|
||||
## Statements, returns, branches
|
||||
|
||||
@@ -243,7 +244,7 @@ Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7
|
||||
| `* > print text=hi *` | `> print text=hi` |
|
||||
| `` *`a` = 1 * `` (trailing space + backticks) | `*a = 1*` — bare bind, no trailing space before `*` / `**` |
|
||||
| `*xs = > text.split value=a,b sep=,*` (bare text args) | `*xs = > text.split value="a,b" sep=","*` — quote text literals; bare words are variables |
|
||||
| Forgetting `---` after nested `##` helper | Add `---` / `***` / `****` |
|
||||
| Forgetting empty return after nested `##` helper when outer continues | Add `*None*` / `**` / `****` (not `---`) |
|
||||
| Import `lib/text` then call bare `split` | `> text.split …` (qualified) |
|
||||
| Import `lib/text` then call `拆分` | Match file language (`text.split`, not 文本) |
|
||||
| `json.set` / `json.append` to build maps or lists | GFM tables; sparse `table.put`; named helpers (`browser.*`, `web.*`) |
|
||||
@@ -262,7 +263,7 @@ Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7
|
||||
- [ ] Print via `print` / `打印`, not bold
|
||||
- [ ] Blank lines separate comment paragraphs from code
|
||||
- [ ] `# main` exists when the file is an entry program
|
||||
- [ ] Nested functions ended with `---` / `***` / `****` when needed
|
||||
- [ ] Nested side-effect helpers ended with `*None*` / `**` / `****` when the outer function continues
|
||||
- [ ] Imports and call names share the same language file
|
||||
- [ ] Data shaped as **GFM tables** (or short helpers) — no `json.set` / `json.append` glue
|
||||
- [ ] Web sites: tables + web classes only (no JSON glue); `data/` gitignored
|
||||
|
||||
+14
-3
@@ -145,11 +145,11 @@ pub enum Expr {
|
||||
List(Vec<Expr>),
|
||||
/// Object literal / horizontal table (`map` value).
|
||||
Map(Vec<(String, Expr)>),
|
||||
/// Footnote index: `` `xs`[^1] `` / `` `m`[^key] `` (see tables-maps-footnotes).
|
||||
/// Footnote index: `` `xs`[^1] `` / `` `m`[^key] `` / `` `m`[^`var`] `` (dynamic key).
|
||||
Index {
|
||||
base: Box<Expr>,
|
||||
/// Label inside `[^…]` (digits → 1-based list index, or map key text including digit keys).
|
||||
label: String,
|
||||
/// Label inside `[^…]` (digits → 1-based list index, or map key; see [`IndexKey`]).
|
||||
label: IndexKey,
|
||||
},
|
||||
/// Parsed `$$…$$` formula tree (from assignment RHS).
|
||||
Formula(FormulaExpr),
|
||||
@@ -166,11 +166,22 @@ pub enum InterpPart {
|
||||
Index { base: String, labels: Vec<String> },
|
||||
}
|
||||
|
||||
/// Footnote / map key after `[^…]`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum IndexKey {
|
||||
/// Static text: `[^拿铁]` / `[^1]`.
|
||||
Lit(String),
|
||||
/// Dynamic: `` [^`品名`] `` — evaluate variable, then stringify as key.
|
||||
Var(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Literal {
|
||||
None,
|
||||
Bool(bool),
|
||||
Int(i64),
|
||||
/// Decimal literal (`0.85`, `3.14`).
|
||||
Num(f64),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
|
||||
+17
-2
@@ -797,6 +797,10 @@ impl<'a> FnCompiler<'a> {
|
||||
let i = self.add_const(Value::Int(*n));
|
||||
self.emit(Op::Constant(i));
|
||||
}
|
||||
Literal::Num(n) => {
|
||||
let i = self.add_const(Value::Num(*n));
|
||||
self.emit(Op::Constant(i));
|
||||
}
|
||||
Literal::Text(t) => {
|
||||
let i = self.add_const(Value::Text(t.clone()));
|
||||
self.emit(Op::Constant(i));
|
||||
@@ -942,8 +946,19 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
Expr::Index { base, label } => {
|
||||
self.compile_expr(base)?;
|
||||
let li = self.add_const(Value::Text(label.clone()));
|
||||
self.emit(Op::Constant(li));
|
||||
match label {
|
||||
crate::ast::IndexKey::Lit(s) => {
|
||||
let li = self.add_const(Value::Text(s.clone()));
|
||||
self.emit(Op::Constant(li));
|
||||
}
|
||||
crate::ast::IndexKey::Var(name) => {
|
||||
let slot = self.locals.get(name).copied().ok_or_else(|| {
|
||||
self.err(format!("undefined variable `{name}` in footnote key"))
|
||||
})?;
|
||||
self.emit(Op::GetLocal(slot));
|
||||
self.emit(Op::Str);
|
||||
}
|
||||
}
|
||||
self.emit(Op::FootnoteGet);
|
||||
}
|
||||
Expr::Formula(e) => {
|
||||
|
||||
+39
-5
@@ -213,7 +213,14 @@ impl Vm {
|
||||
} else {
|
||||
match (a, b) {
|
||||
(Value::Int(x), Value::Int(y)) => stack.push(Value::Int(x - y)),
|
||||
_ => return Err(self.err_at(span, "`-` needs ints")),
|
||||
(Value::Num(x), Value::Num(y)) => stack.push(Value::Num(x - y)),
|
||||
(Value::Int(x), Value::Num(y)) => {
|
||||
stack.push(Value::Num(x as f64 - y))
|
||||
}
|
||||
(Value::Num(x), Value::Int(y)) => {
|
||||
stack.push(Value::Num(x - y as f64))
|
||||
}
|
||||
_ => return Err(self.err_at(span, "`-` needs ints or nums")),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -232,7 +239,14 @@ impl Vm {
|
||||
} else {
|
||||
match (a, b) {
|
||||
(Value::Int(x), Value::Int(y)) => stack.push(Value::Int(x * y)),
|
||||
_ => return Err(self.err_at(span, "`*` needs ints")),
|
||||
(Value::Num(x), Value::Num(y)) => stack.push(Value::Num(x * y)),
|
||||
(Value::Int(x), Value::Num(y)) => {
|
||||
stack.push(Value::Num(x as f64 * y))
|
||||
}
|
||||
(Value::Num(x), Value::Int(y)) => {
|
||||
stack.push(Value::Num(x * y as f64))
|
||||
}
|
||||
_ => return Err(self.err_at(span, "`*` needs ints or nums")),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -244,12 +258,29 @@ impl Vm {
|
||||
return Err(self.err_at(span, "division by zero"));
|
||||
}
|
||||
(Value::Int(x), Value::Int(y)) => stack.push(Value::Int(x / y)),
|
||||
_ => return Err(self.err_at(span, "`/` needs ints")),
|
||||
(Value::Num(_), Value::Num(y)) if y == 0.0 => {
|
||||
return Err(self.err_at(span, "division by zero"));
|
||||
}
|
||||
(Value::Int(_), Value::Num(y)) if y == 0.0 => {
|
||||
return Err(self.err_at(span, "division by zero"));
|
||||
}
|
||||
(Value::Num(_), Value::Int(0)) => {
|
||||
return Err(self.err_at(span, "division by zero"));
|
||||
}
|
||||
(Value::Num(x), Value::Num(y)) => stack.push(Value::Num(x / y)),
|
||||
(Value::Int(x), Value::Num(y)) => {
|
||||
stack.push(Value::Num(x as f64 / y))
|
||||
}
|
||||
(Value::Num(x), Value::Int(y)) => {
|
||||
stack.push(Value::Num(x / y as f64))
|
||||
}
|
||||
_ => return Err(self.err_at(span, "`/` needs ints or nums")),
|
||||
}
|
||||
}
|
||||
Op::Negate => match pop(&mut stack).map_err(|m| self.err_at(span, m))? {
|
||||
Value::Int(n) => stack.push(Value::Int(-n)),
|
||||
_ => return Err(self.err_at(span, "unary `-` needs int")),
|
||||
Value::Num(n) => stack.push(Value::Num(-n)),
|
||||
_ => return Err(self.err_at(span, "unary `-` needs int or num")),
|
||||
},
|
||||
Op::Not => {
|
||||
let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
@@ -663,12 +694,15 @@ fn pop(stack: &mut Vec<Value>) -> Result<Value, String> {
|
||||
fn add(a: Value, b: Value) -> Result<Value, String> {
|
||||
match (a, b) {
|
||||
(Value::Int(x), Value::Int(y)) => Ok(Value::Int(x + y)),
|
||||
(Value::Num(x), Value::Num(y)) => Ok(Value::Num(x + y)),
|
||||
(Value::Int(x), Value::Num(y)) => Ok(Value::Num(x as f64 + y)),
|
||||
(Value::Num(x), Value::Int(y)) => Ok(Value::Num(x + y as f64)),
|
||||
(Value::Text(x), Value::Text(y)) => Ok(Value::Text(format!("{x}{y}"))),
|
||||
(Value::Text(x), y) => Ok(Value::Text(format!("{x}{}", y.as_display()))),
|
||||
(x, Value::Text(y)) => Ok(Value::Text(format!("{}{y}", x.as_display()))),
|
||||
(Value::Int(x), y) => Ok(Value::Text(format!("{}{}", x, y.as_display()))),
|
||||
(x, Value::Int(y)) => Ok(Value::Text(format!("{}{y}", x.as_display()))),
|
||||
_ => Err("`+` needs ints or text".into()),
|
||||
_ => Err("`+` needs ints, nums, or text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+44
-7
@@ -5,7 +5,8 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::ast::{
|
||||
Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Param, Stmt, UnaryOp,
|
||||
Arg, BinaryOp, CallExpr, Expr, Function, IndexKey, InterpPart, Literal, Module, Param, Stmt,
|
||||
UnaryOp,
|
||||
};
|
||||
use crate::builtin::{
|
||||
builtin_at, builtin_footnote_get, builtin_int, builtin_iter_items, builtin_join,
|
||||
@@ -460,6 +461,24 @@ impl Interpreter {
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_index_key(
|
||||
&mut self,
|
||||
_module: &Module,
|
||||
_fun: &Function,
|
||||
env: &mut Env,
|
||||
label: &IndexKey,
|
||||
) -> Result<String> {
|
||||
match label {
|
||||
IndexKey::Lit(s) => Ok(s.clone()),
|
||||
IndexKey::Var(name) => {
|
||||
let v = env.get(name).cloned().ok_or_else(|| {
|
||||
self.err(format!("undefined variable `{name}` in footnote key"))
|
||||
})?;
|
||||
Ok(v.as_display())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_expr(
|
||||
&mut self,
|
||||
module: &Module,
|
||||
@@ -503,7 +522,8 @@ impl Interpreter {
|
||||
UnaryOp::Not => Ok(Value::Bool(!v.truthy())),
|
||||
UnaryOp::Neg => match v {
|
||||
Value::Int(n) => Ok(Value::Int(-n)),
|
||||
_ => Err(self.err("unary `-` needs int")),
|
||||
Value::Num(n) => Ok(Value::Num(-n)),
|
||||
_ => Err(self.err("unary `-` needs int or num")),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -556,7 +576,8 @@ impl Interpreter {
|
||||
}
|
||||
Expr::Index { base, label } => {
|
||||
let v = self.eval_expr(module, fun, env, base)?;
|
||||
builtin_footnote_get(&v, label).map_err(|m| self.err(m))
|
||||
let key = self.resolve_index_key(module, fun, env, label)?;
|
||||
builtin_footnote_get(&v, &key).map_err(|m| self.err(m))
|
||||
}
|
||||
Expr::Formula(e) => Ok(Value::Formula(e.clone())),
|
||||
Expr::Code(c) => Ok(Value::Code(c.clone())),
|
||||
@@ -1144,6 +1165,7 @@ fn lit_to_value(lit: &Literal) -> Value {
|
||||
Literal::None => Value::None,
|
||||
Literal::Bool(b) => Value::Bool(*b),
|
||||
Literal::Int(n) => Value::Int(*n),
|
||||
Literal::Num(n) => Value::Num(*n),
|
||||
Literal::Text(s) => Value::Text(s.clone()),
|
||||
}
|
||||
}
|
||||
@@ -1152,23 +1174,38 @@ fn eval_binary(op: BinaryOp, l: &Value, r: &Value) -> Result<Value> {
|
||||
match op {
|
||||
BinaryOp::Add => match (l, r) {
|
||||
(Value::Int(a), Value::Int(b)) => Ok(Value::Int(a + b)),
|
||||
(Value::Num(a), Value::Num(b)) => Ok(Value::Num(a + b)),
|
||||
(Value::Int(a), Value::Num(b)) => Ok(Value::Num(*a as f64 + b)),
|
||||
(Value::Num(a), Value::Int(b)) => Ok(Value::Num(a + *b as f64)),
|
||||
(Value::Text(a), Value::Text(b)) => Ok(Value::Text(format!("{a}{b}"))),
|
||||
(Value::Text(a), b) => Ok(Value::Text(format!("{a}{}", b.as_display()))),
|
||||
(a, Value::Text(b)) => Ok(Value::Text(format!("{}{b}", a.as_display()))),
|
||||
_ => bail!("`+` needs ints or text"),
|
||||
_ => bail!("`+` needs ints, nums, or text"),
|
||||
},
|
||||
BinaryOp::Sub => match (l, r) {
|
||||
(Value::Int(a), Value::Int(b)) => Ok(Value::Int(a - b)),
|
||||
_ => bail!("`-` needs ints"),
|
||||
(Value::Num(a), Value::Num(b)) => Ok(Value::Num(a - b)),
|
||||
(Value::Int(a), Value::Num(b)) => Ok(Value::Num(*a as f64 - b)),
|
||||
(Value::Num(a), Value::Int(b)) => Ok(Value::Num(a - *b as f64)),
|
||||
_ => bail!("`-` needs ints or nums"),
|
||||
},
|
||||
BinaryOp::Mul => match (l, r) {
|
||||
(Value::Int(a), Value::Int(b)) => Ok(Value::Int(a * b)),
|
||||
_ => bail!("`*` needs ints"),
|
||||
(Value::Num(a), Value::Num(b)) => Ok(Value::Num(a * b)),
|
||||
(Value::Int(a), Value::Num(b)) => Ok(Value::Num(*a as f64 * b)),
|
||||
(Value::Num(a), Value::Int(b)) => Ok(Value::Num(a * *b as f64)),
|
||||
_ => bail!("`*` needs ints or nums"),
|
||||
},
|
||||
BinaryOp::Div => match (l, r) {
|
||||
(Value::Int(_), Value::Int(0)) => bail!("division by zero"),
|
||||
(Value::Int(a), Value::Int(b)) => Ok(Value::Int(a / b)),
|
||||
_ => bail!("`/` needs ints"),
|
||||
(Value::Num(_), Value::Num(b)) if *b == 0.0 => bail!("division by zero"),
|
||||
(Value::Int(_), Value::Num(b)) if *b == 0.0 => bail!("division by zero"),
|
||||
(Value::Num(_), Value::Int(0)) => bail!("division by zero"),
|
||||
(Value::Num(a), Value::Num(b)) => Ok(Value::Num(a / b)),
|
||||
(Value::Int(a), Value::Num(b)) => Ok(Value::Num(*a as f64 / b)),
|
||||
(Value::Num(a), Value::Int(b)) => Ok(Value::Num(a / *b as f64)),
|
||||
_ => bail!("`/` needs ints or nums"),
|
||||
},
|
||||
BinaryOp::Eq => Ok(Value::Bool(l == r)),
|
||||
BinaryOp::Ne => Ok(Value::Bool(l != r)),
|
||||
|
||||
+97
-11
@@ -2,7 +2,7 @@
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
|
||||
use crate::ast::{BinaryOp, CallExpr, Expr, InterpPart, Literal, UnaryOp};
|
||||
use crate::ast::{BinaryOp, CallExpr, Expr, IndexKey, InterpPart, Literal, UnaryOp};
|
||||
|
||||
pub fn parse_expr(input: &str) -> Result<Expr> {
|
||||
parse_expr_mode(input, false)
|
||||
@@ -195,7 +195,7 @@ pub fn parse_interp(s: &str) -> Expr {
|
||||
for label in labels {
|
||||
e = Expr::Index {
|
||||
base: Box::new(e),
|
||||
label: label.clone(),
|
||||
label: IndexKey::Lit(label.clone()),
|
||||
};
|
||||
}
|
||||
return e;
|
||||
@@ -516,11 +516,36 @@ impl<'a> Parser<'a> {
|
||||
self.i += '空'.len_utf8();
|
||||
return Ok(Expr::Literal(Literal::None));
|
||||
}
|
||||
if self.peek_char().map(|c| c.is_ascii_digit()).unwrap_or(false) {
|
||||
if self.peek_char().map(|c| c.is_ascii_digit()).unwrap_or(false)
|
||||
|| (self.peek_char() == Some('.')
|
||||
&& self
|
||||
.rest()
|
||||
.chars()
|
||||
.nth(1)
|
||||
.map(|c| c.is_ascii_digit())
|
||||
.unwrap_or(false))
|
||||
{
|
||||
let start = self.i;
|
||||
while self.peek_char().map(|c| c.is_ascii_digit()).unwrap_or(false) {
|
||||
self.bump_char();
|
||||
}
|
||||
if self.peek_char() == Some('.') {
|
||||
self.bump_char();
|
||||
let frac_start = self.i;
|
||||
while self.peek_char().map(|c| c.is_ascii_digit()).unwrap_or(false) {
|
||||
self.bump_char();
|
||||
}
|
||||
// Require at least one digit on one side of the dot.
|
||||
let int_part = &self.src[start..frac_start.saturating_sub(1)];
|
||||
let frac_part = &self.src[frac_start..self.i];
|
||||
if int_part.is_empty() && frac_part.is_empty() {
|
||||
bail!("invalid number literal");
|
||||
}
|
||||
let n: f64 = self.src[start..self.i]
|
||||
.parse()
|
||||
.map_err(|e| anyhow::anyhow!("invalid float: {e}"))?;
|
||||
return Ok(Expr::Literal(Literal::Num(n)));
|
||||
}
|
||||
let n: i64 = self.src[start..self.i].parse()?;
|
||||
return Ok(Expr::Literal(Literal::Int(n)));
|
||||
}
|
||||
@@ -691,7 +716,7 @@ impl<'a> Parser<'a> {
|
||||
for label in labels {
|
||||
e = Expr::Index {
|
||||
base: Box::new(e),
|
||||
label,
|
||||
label: IndexKey::Lit(label),
|
||||
};
|
||||
}
|
||||
e
|
||||
@@ -736,11 +761,36 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse `[^label]` after a value; label is text until `]`.
|
||||
fn parse_footnote_label(&mut self) -> Result<String> {
|
||||
/// Parse `[^label]` or `` [^`ident`] `` after a value.
|
||||
fn parse_footnote_label(&mut self) -> Result<IndexKey> {
|
||||
if !self.eat("[^") {
|
||||
bail!("expected [^ footnote index");
|
||||
}
|
||||
self.skip_ws();
|
||||
if self.eat("`") {
|
||||
let start = self.i;
|
||||
while let Some(c) = self.peek_char() {
|
||||
if c == '`' {
|
||||
break;
|
||||
}
|
||||
if c == '\n' || c == '\r' || c == ']' {
|
||||
bail!("unterminated footnote var `[^`…`]`");
|
||||
}
|
||||
self.bump_char();
|
||||
}
|
||||
let name = self.src[start..self.i].trim().to_string();
|
||||
if !self.eat("`") {
|
||||
bail!("unterminated footnote var `[^`…`]`");
|
||||
}
|
||||
self.skip_ws();
|
||||
if !self.eat("]") {
|
||||
bail!("unterminated footnote index [^…]");
|
||||
}
|
||||
if name.is_empty() {
|
||||
bail!("empty footnote var `[^`]`");
|
||||
}
|
||||
return Ok(IndexKey::Var(name));
|
||||
}
|
||||
let start = self.i;
|
||||
while let Some(c) = self.peek_char() {
|
||||
if c == ']' {
|
||||
@@ -758,7 +808,7 @@ impl<'a> Parser<'a> {
|
||||
if label.is_empty() {
|
||||
bail!("empty footnote index `[^]`");
|
||||
}
|
||||
Ok(label)
|
||||
Ok(IndexKey::Lit(label))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1038,7 +1088,7 @@ mod tests {
|
||||
match e {
|
||||
Expr::Index { base, label } => {
|
||||
assert!(matches!(base.as_ref(), Expr::Var(n) if n == "ev"));
|
||||
assert_eq!(label, "result");
|
||||
assert_eq!(label, IndexKey::Lit("result".into()));
|
||||
}
|
||||
other => panic!("expected Index, got {other:?}"),
|
||||
}
|
||||
@@ -1214,13 +1264,25 @@ mod tests {
|
||||
}
|
||||
// Bare `m`[^key] with no prefix → Expr::Index
|
||||
let e = parse_interp("`m`[^苹果]");
|
||||
assert!(matches!(e, Expr::Index { label, .. } if label == "苹果"));
|
||||
assert!(matches!(
|
||||
e,
|
||||
Expr::Index {
|
||||
label: IndexKey::Lit(ref s),
|
||||
..
|
||||
} if s == "苹果"
|
||||
));
|
||||
// Chained labels fold into one Index part with multiple labels.
|
||||
let e = parse_interp("`m`[^a][^b]");
|
||||
match &e {
|
||||
Expr::Index { base, label } => {
|
||||
assert!(matches!(base.as_ref(), Expr::Index { label: l, .. } if l == "a"));
|
||||
assert_eq!(label, "b");
|
||||
assert!(matches!(
|
||||
base.as_ref(),
|
||||
Expr::Index {
|
||||
label: IndexKey::Lit(ref l),
|
||||
..
|
||||
} if l == "a"
|
||||
));
|
||||
assert_eq!(label, &IndexKey::Lit("b".into()));
|
||||
}
|
||||
other => panic!("expected chained Index, got {other:?}"),
|
||||
}
|
||||
@@ -1241,6 +1303,30 @@ mod tests {
|
||||
other => panic!("expected Interp, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_literal_and_dynamic_footnote_key() {
|
||||
let e = parse_expr("0.85").unwrap();
|
||||
assert!(matches!(e, Expr::Literal(Literal::Num(n)) if (n - 0.85).abs() < 1e-12));
|
||||
let e = parse_expr("28 * 0.85").unwrap();
|
||||
assert!(matches!(e, Expr::Binary { op: BinaryOp::Mul, .. }));
|
||||
let e = parse_expr_prefer_var("菜单[^`名`]").unwrap();
|
||||
match e {
|
||||
Expr::Index { base, label } => {
|
||||
assert!(matches!(base.as_ref(), Expr::Var(n) if n == "菜单"));
|
||||
assert_eq!(label, IndexKey::Var("名".into()));
|
||||
}
|
||||
other => panic!("expected dynamic Index, got {other:?}"),
|
||||
}
|
||||
let e = parse_expr("m[^拿铁]").unwrap();
|
||||
assert!(matches!(
|
||||
e,
|
||||
Expr::Index {
|
||||
label: IndexKey::Lit(ref s),
|
||||
..
|
||||
} if s == "拿铁"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+48
-8
@@ -12,7 +12,7 @@ pub use prose::{scan_prose_line, ProseBit};
|
||||
use anyhow::{bail, Result};
|
||||
|
||||
use crate::ast::{
|
||||
BranchArm, Expr, Function, Import, Literal, Module, Param, Stmt, Use,
|
||||
BranchArm, Expr, Function, Import, IndexKey, Literal, Module, Param, Stmt, Use,
|
||||
};
|
||||
use crate::diagnostics::{bail_at, Diagnostic, Span};
|
||||
use crate::lex::{classify_source, ClassifiedLine, LineKind};
|
||||
@@ -33,8 +33,18 @@ pub fn parse_classified(lines: &[ClassifiedLine]) -> Result<Module> {
|
||||
while cur.skip_noise() {
|
||||
let Some(line) = cur.peek() else { break };
|
||||
let trimmed = line.text.trim();
|
||||
// Module-level Markdown thematic breaks (`---` / `***`) are narrative skip.
|
||||
if is_frame(trimmed) {
|
||||
cur.bump();
|
||||
continue;
|
||||
}
|
||||
if is_heading(trimmed) {
|
||||
functions.push(cur.parse_function(1)?);
|
||||
} else if line.kind == LineKind::Comment {
|
||||
// Intro paragraphs may still contain return-shaped italics (`返回*值*`)
|
||||
// or leftover soft emphasis; executable prose belongs inside functions.
|
||||
cur.bump();
|
||||
continue;
|
||||
} else {
|
||||
bail!(
|
||||
"{}:1: expected heading (`#` object or `##` function), got: {trimmed}",
|
||||
@@ -246,13 +256,19 @@ impl<'a> Cursor<'a> {
|
||||
value: Expr::Literal(Literal::None),
|
||||
span,
|
||||
});
|
||||
break;
|
||||
// Objects (`#`) may still declare `##` methods after the constructor return.
|
||||
if level >= 2 {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- / *** at function body top level ends the function (no return).
|
||||
// `---` / `***` = Markdown thematic break (narrative skip), not function end.
|
||||
// Side-effect-only helpers end with `*None*` / whole-line `**` / `****`, or at
|
||||
// the next heading / EOF.
|
||||
if is_frame(trimmed) {
|
||||
self.bump();
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
|
||||
if is_heading(trimmed) {
|
||||
@@ -271,6 +287,7 @@ impl<'a> Cursor<'a> {
|
||||
col: 1,
|
||||
};
|
||||
let bits = scan_prose_line(line.text.trim_end_matches(['\r', '\n']));
|
||||
let mut end_body = false;
|
||||
for bit in bits {
|
||||
match bit {
|
||||
ProseBit::Decl { name, default, .. } => {
|
||||
@@ -284,9 +301,16 @@ impl<'a> Cursor<'a> {
|
||||
}
|
||||
ProseBit::ItalicReturn { inner, .. } => {
|
||||
fun.body.push(stmt_from_italic_return(&inner, span.clone())?);
|
||||
// `##`+ : return ends the function so outer/sibling lines attach.
|
||||
// `#` objects: keep scanning for method headings.
|
||||
end_body = level >= 2;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if end_body {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -299,7 +323,12 @@ impl<'a> Cursor<'a> {
|
||||
continue;
|
||||
}
|
||||
|
||||
fun.body.push(self.parse_simple_stmt()?);
|
||||
let stmt = self.parse_simple_stmt()?;
|
||||
let end_body = matches!(stmt, Stmt::Return { .. }) && level >= 2;
|
||||
fun.body.push(stmt);
|
||||
if end_body {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
merge_inferred_params(&mut fun, &prose_decls)?;
|
||||
@@ -315,7 +344,8 @@ impl<'a> Cursor<'a> {
|
||||
let trimmed = line.text.trim();
|
||||
|
||||
if is_frame(trimmed) {
|
||||
bail!("{span}: unexpected frame line as statement");
|
||||
// Should be skipped by callers; keep defensive message if reached.
|
||||
bail!("{span}: unexpected frame line as statement (use empty return `*None*` / `**` / `****` to end a side-effect body)");
|
||||
}
|
||||
|
||||
if trimmed.starts_with("$$") {
|
||||
@@ -844,7 +874,12 @@ impl<'a> Cursor<'a> {
|
||||
body.push(self.parse_loop_or_err()?);
|
||||
continue;
|
||||
}
|
||||
body.push(self.parse_simple_stmt()?);
|
||||
let stmt = self.parse_simple_stmt()?;
|
||||
let end_arm = matches!(stmt, Stmt::Return { .. });
|
||||
body.push(stmt);
|
||||
if end_arm {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
@@ -1372,7 +1407,12 @@ fn collect_reads_expr(expr: &Expr, reads: &mut std::collections::HashSet<String>
|
||||
collect_reads_expr(right, reads);
|
||||
}
|
||||
Expr::Unary { expr, .. } => collect_reads_expr(expr, reads),
|
||||
Expr::Index { base, .. } => collect_reads_expr(base, reads),
|
||||
Expr::Index { base, label } => {
|
||||
collect_reads_expr(base, reads);
|
||||
if let IndexKey::Var(n) = label {
|
||||
reads.insert(n.clone());
|
||||
}
|
||||
}
|
||||
Expr::List(xs) => {
|
||||
for x in xs {
|
||||
collect_reads_expr(x, reads);
|
||||
|
||||
+106
-13
@@ -1,4 +1,7 @@
|
||||
//! Inline prose scan for Markup v0.3 (叙述中的 `` `名` `` / `**代码**` / `*返回*`).
|
||||
//!
|
||||
//! Soft Markdown emphasis that does not look like code/return is skipped (G2 —
|
||||
//! [code-as-docs-gaps.md](../../../doc/design/code-as-docs-gaps.md)).
|
||||
|
||||
use crate::lex::{matching_bold_close_inline, matching_italic_close_inline};
|
||||
|
||||
@@ -36,13 +39,12 @@ pub fn scan_prose_line(line: &str) -> Vec<ProseBit> {
|
||||
if c == b'*' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
|
||||
let rest = &line[i..];
|
||||
if let Some(close_rel) = matching_bold_close_inline(rest) {
|
||||
// close_rel is index within `rest` of first `*` of closing `**`
|
||||
let inner = rest[2..close_rel].to_string();
|
||||
out.push(ProseBit::BoldCode {
|
||||
inner,
|
||||
at: i,
|
||||
});
|
||||
i += close_rel + 2;
|
||||
let next = i + close_rel + 2;
|
||||
if looks_like_bold_code(&inner) {
|
||||
out.push(ProseBit::BoldCode { inner, at: i });
|
||||
}
|
||||
i = next;
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
@@ -56,11 +58,11 @@ pub fn scan_prose_line(line: &str) -> Vec<ProseBit> {
|
||||
}
|
||||
if let Some(close_rel) = matching_italic_close_inline(rest) {
|
||||
let inner = rest[1..close_rel].to_string();
|
||||
out.push(ProseBit::ItalicReturn {
|
||||
inner,
|
||||
at: i,
|
||||
});
|
||||
i += close_rel + 1;
|
||||
let next = i + close_rel + 1;
|
||||
if looks_like_italic_return(line, i, next, &inner) {
|
||||
out.push(ProseBit::ItalicReturn { inner, at: i });
|
||||
}
|
||||
i = next;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -69,6 +71,79 @@ pub fn scan_prose_line(line: &str) -> Vec<ProseBit> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `**inner**` should execute (assign / call / expr), not soft emphasis.
|
||||
pub fn looks_like_bold_code(inner: &str) -> bool {
|
||||
let t = inner.trim();
|
||||
if t.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if t.contains('=') || t.starts_with('>') {
|
||||
return true;
|
||||
}
|
||||
if t.chars().any(|c| matches!(c, '+' | '-' | '*' | '/' | '(' | ')' | '[' | ']')) {
|
||||
return true;
|
||||
}
|
||||
let parts: Vec<&str> = t.split_whitespace().collect();
|
||||
if parts.len() >= 2 {
|
||||
return parts[1..].iter().any(|p| {
|
||||
p.contains('=')
|
||||
|| p.starts_with('"')
|
||||
|| p.starts_with('\'')
|
||||
|| p.starts_with('`')
|
||||
|| p.chars().all(|c| c.is_ascii_digit())
|
||||
|| (p.contains('.')
|
||||
&& p.chars()
|
||||
.filter(|c| *c != '.')
|
||||
.all(|c| c.is_ascii_digit()))
|
||||
});
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether `*inner*` is a return (vs mid-prose English/CJK emphasis).
|
||||
fn looks_like_italic_return(line: &str, at: usize, after: usize, inner: &str) -> bool {
|
||||
let t = inner.trim();
|
||||
if t.is_empty()
|
||||
|| matches!(
|
||||
t,
|
||||
"None" | "无" | "空" | "True" | "False" | "真" | "假" | "true" | "false"
|
||||
)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if t.starts_with('>')
|
||||
|| t.contains('=')
|
||||
|| t.chars()
|
||||
.any(|c| matches!(c, '+' | '-' | '*' | '/' | '(' | ')' | '[' | ']'))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
// Whole-line return: only ws outside the italic span.
|
||||
let before = line[..at].trim();
|
||||
let after_s = line.get(after..).unwrap_or("").trim();
|
||||
if before.is_empty() && after_s.is_empty() {
|
||||
return true;
|
||||
}
|
||||
// Narration "返回*n*" / "return *n*"
|
||||
if before.ends_with("返回") || before.ends_with("return") || before.ends_with("Return") {
|
||||
return true;
|
||||
}
|
||||
// Mid-prose simple word → soft emphasis (G2).
|
||||
if is_simple_emphasis_word(t) {
|
||||
return false;
|
||||
}
|
||||
// Multi-token or dotted id mid-line: keep as return (rare).
|
||||
true
|
||||
}
|
||||
|
||||
fn is_simple_emphasis_word(t: &str) -> bool {
|
||||
if t.chars().any(|c| c.is_whitespace()) {
|
||||
return false;
|
||||
}
|
||||
t.chars()
|
||||
.all(|c| c.is_alphanumeric() || c == '_' || !c.is_ascii())
|
||||
}
|
||||
|
||||
fn scan_backtick_decl(line: &str, start: usize) -> Option<(ProseBit, usize)> {
|
||||
let rest = &line[start + 1..];
|
||||
let end = rest.find('`')?;
|
||||
@@ -78,9 +153,7 @@ fn scan_backtick_decl(line: &str, start: usize) -> Option<(ProseBit, usize)> {
|
||||
}
|
||||
let after_tick = start + 1 + end + 1;
|
||||
let after = line.get(after_tick..)?;
|
||||
// `` `名`=默认 `` — optional default glued after closing tick
|
||||
if let Some(stripped) = after.strip_prefix('=') {
|
||||
// default runs until whitespace or CJK punctuation-ish break for prose
|
||||
let def_end = stripped
|
||||
.find(|c: char| {
|
||||
c.is_whitespace()
|
||||
@@ -147,4 +220,24 @@ mod tests {
|
||||
_ => panic!("{:?}", bits[0]),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soft_bold_emphasis_skipped() {
|
||||
let bits = scan_prose_line("本文件既是**说明**也是**程序**。");
|
||||
assert!(bits.is_empty(), "{bits:?}");
|
||||
assert!(!looks_like_bold_code("说明"));
|
||||
assert!(looks_like_bold_code("n=n+1"));
|
||||
assert!(looks_like_bold_code("加一 37"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soft_italic_emphasis_skipped() {
|
||||
let bits = scan_prose_line("When soft=True, *only* FIND continues.");
|
||||
assert!(bits.is_empty(), "{bits:?}");
|
||||
let bits = scan_prose_line("*总额*");
|
||||
assert!(
|
||||
matches!(&bits[..], [ProseBit::ItalicReturn { inner, .. }] if inner == "总额"),
|
||||
"{bits:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -1341,7 +1341,11 @@ fn expr_prec(expr: &Expr, parent_prec: u8) -> String {
|
||||
format!("{{{}}}", parts.join(", "))
|
||||
}
|
||||
Expr::Index { base, label } => {
|
||||
format!("{}[^{}]", expr_prec(base, 8), label)
|
||||
let key = match label {
|
||||
crate::ast::IndexKey::Lit(s) => s.clone(),
|
||||
crate::ast::IndexKey::Var(n) => format!("`{n}`"),
|
||||
};
|
||||
format!("{}[^{}]", expr_prec(base, 8), key)
|
||||
}
|
||||
Expr::Formula(e) => format!("$$ {} $$", e.as_display()),
|
||||
Expr::Code(c) => format!("```{} …```", c.lang),
|
||||
@@ -1436,6 +1440,7 @@ fn lit_display(lit: &Literal) -> String {
|
||||
Literal::Bool(true) => "True".into(),
|
||||
Literal::Bool(false) => "False".into(),
|
||||
Literal::Int(n) => n.to_string(),
|
||||
Literal::Num(n) => crate::formula::format_num(*n),
|
||||
Literal::Text(t) => t.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3824,3 +3824,23 @@ fn markup_v03_multi_bold() {
|
||||
fn markup_v03_print_bold() {
|
||||
assert_out_v03("tests/markup-v03/print-bold.mq.md", "Hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markup_v03_module_hr() {
|
||||
assert_out_v03("tests/markup-v03/module-hr.mq.md", "ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markup_v03_soft_emphasis() {
|
||||
assert_out_v03("tests/markup-v03/soft-emphasis.mq.md", "2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markup_v03_float_discount() {
|
||||
assert_out_v03("tests/markup-v03/float-discount.mq.md", "23.8");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markup_v03_dynamic_footnote() {
|
||||
assert_out_v03("tests/markup-v03/dynamic-footnote.mq.md", "28");
|
||||
}
|
||||
@@ -15,6 +15,8 @@
|
||||
|
||||
见各 `.mq.md` frontmatter;汇总期望以 `gold.rs` 为准。
|
||||
|
||||
代码即文档叙述面(G1–G4):`module-hr` / `soft-emphasis` / `float-discount` / `dynamic-footnote` —— 设计见 [code-as-docs-gaps.md](../../doc/design/code-as-docs-gaps.md)。
|
||||
|
||||
```bash
|
||||
cargo test --test gold markup_v03
|
||||
marqdo run tests/markup-v03/inc-prose.mq.md
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
title: G4 动态脚注键
|
||||
description: 菜单[^`名`] 用变量值取 map 键
|
||||
markup: v0.3
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`菜单` =
|
||||
|
||||
| 美式 | 拿铁 |
|
||||
|------|------|
|
||||
| 18 | 28 |
|
||||
|
||||
**名 = "拿铁"**
|
||||
**价 = 菜单[^`名`]**
|
||||
> print text=`价`
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: v0.3 空返回(`---`)
|
||||
description: 副作用后分割线收束
|
||||
title: v0.3 副作用函数 + 体内 ---
|
||||
description: 分割线为叙述;函数在下一标题处结束(空返回见 empty-return-none)
|
||||
markup: v0.3
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
title: G3 浮点面量与折扣
|
||||
description: 0.85 可解析;Int * Num 得 Num
|
||||
markup: v0.3
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
**应付 = 28 * 0.85**
|
||||
> print text=`应付`
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
title: G1 模块级 --- 为叙述分隔线
|
||||
description: 顶层与函数体内 --- 均为叙述分隔(不再收束)
|
||||
markup: v0.3
|
||||
---
|
||||
|
||||
本段在 frontmatter 之后、入口之前。
|
||||
|
||||
---
|
||||
|
||||
中间再来一条分隔线也不应报错。
|
||||
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
> print text=ok
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
title: G2 叙述强调不执行
|
||||
description: 句中 **说明** / *only* 为装饰;像代码的粗体与整行斜体仍执行
|
||||
markup: v0.3
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
本段既是**说明**也是**程序**;英文里也有 *only* 这类强调词。
|
||||
|
||||
**n = 1**
|
||||
**n = n + 1**
|
||||
> print text=`n`
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: 函数结束 — 分割线
|
||||
description: --- 结束嵌套函数体,后续调用属于外层
|
||||
title: 函数体内 --- 为叙述分隔
|
||||
description: 分割线不再收束函数;嵌套 ## 在下一标题或空返回处结束
|
||||
---
|
||||
|
||||
# main
|
||||
@@ -13,3 +13,5 @@ description: --- 结束嵌套函数体,后续调用属于外层
|
||||
> print text=Hello `谁`!
|
||||
|
||||
---
|
||||
|
||||
叙述分隔线可写在函数体里,不结束函数;本例下一行已是文件尾,问候在 EOF 结束。
|
||||
Reference in new issue
Block a user