From 69b626e91963dd7235f414bb999054865476f9ae Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 4 Aug 2026 11:28:15 +0800 Subject: [PATCH] Add English builtins, pipeline dump flags, and M1 line classification. Document a minimal Python-inspired keyword set (print/input, True/False/None), require visible --dump-* stages, and ship working --dump-lines for .mq.md sources. Co-authored-by: Cursor --- README.md | 8 +- doc/README.md | 6 +- doc/design/code-vs-comment.md | 14 +-- doc/design/dependencies.md | 2 +- doc/design/generated-yaml-manifest.md | 2 +- doc/design/keywords.md | 84 +++++++++++++++ doc/design/markdown-mapping.md | 37 +++---- doc/design/pipeline-debug.md | 71 +++++++++++++ doc/design/return-hr-and-code-surface.md | 14 +-- doc/design/tech-stack.md | 2 +- doc/roadmap/interpreter.md | 4 +- examples/branch.mq.md | 8 +- examples/collection.mq.md | 4 +- examples/hello.mq.md | 6 +- examples/index.mq.md | 8 +- examples/loop.mq.md | 6 +- examples/utils.mq.md | 4 +- examples/with-import.mq.md | 4 +- spike/README.md | 2 +- src/debug.rs | 3 + src/lex/mod.rs | 127 ++++++++++++++++++++++- src/lib.rs | 74 ++++++++++--- src/main.rs | 57 +++++++++- tests/cli_m0.rs | 20 +++- 24 files changed, 481 insertions(+), 86 deletions(-) create mode 100644 doc/design/keywords.md create mode 100644 doc/design/pipeline-debug.md create mode 100644 src/debug.rs diff --git a/README.md b/README.md index 50606e8..7d3a506 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ -# Marqdo +# Marqdo **代码即文档。文档即代码。** Marqdo:Markdown **标记即语法**。源文件 `.mq.md` 既是文稿也是程序。 -语法宪法:[doc/design/markdown-mapping.md](doc/design/markdown-mapping.md) · 示例:[examples/](examples/) +语法宪法:[doc/design/markdown-mapping.md](doc/design/markdown-mapping.md) · 关键字:[keywords.md](doc/design/keywords.md) · 示例:[examples/](examples/) --- @@ -15,7 +15,7 @@ Marqdo:Markdown **标记即语法**。源文件 `.mq.md` 既是文稿也是程 | 无标记行 | 注释 | | `*…*` | 程序语句 | | `**…**` | **返回值**(架构) | -| `> 输出 …` 等 | 输出等副作用 = **普通函数**,非架构标记 | +| `> print …` 等 | 输出等副作用 = **普通函数**,非架构标记 | | `#` / `##` | 函数与作用域 | | `+` / `1.` | 分支(臂头单独 `*` = else) | | `-` | 循环(头下纯名则为形参) | @@ -25,7 +25,7 @@ Marqdo:Markdown **标记即语法**。源文件 `.mq.md` 既是文稿也是程 ```markdown # main -> 输出 内容=Hello World! +> print text=Hello World! ## 加一 - n diff --git a/doc/README.md b/doc/README.md index 24221a1..0a29b62 100644 --- a/doc/README.md +++ b/doc/README.md @@ -1,4 +1,4 @@ -# Marqdo 开发文档 +# Marqdo 开发文档 本目录存放各阶段设计、选型与路线图。 @@ -22,7 +22,9 @@ | [design/tech-stack.md](design/tech-stack.md) | 实现栈对比 | | [adr/0001-implementation-language.md](adr/0001-implementation-language.md) | **Accepted:Rust 参考解释器;不用 Flex/Bison** | | [design/dependencies.md](design/dependencies.md) | 依赖详单(无 Flex/Bison) | -| [dev-setup.md](dev-setup.md) | **开发环境配置(Rust M0)** | +| [design/keywords.md](design/keywords.md) | **英文最小关键字 / 内置 `print` `input`** | +| [design/pipeline-debug.md](design/pipeline-debug.md) | **流水线 `--dump-*` 可视调试** | +| [dev-setup.md](dev-setup.md) | 开发环境配置(Rust M0) | | [roadmap/interpreter.md](roadmap/interpreter.md) | 正经解释器路线图 | | [research/okf-and-marqdo.md](research/okf-and-marqdo.md) | OKF 调研 | diff --git a/doc/design/code-vs-comment.md b/doc/design/code-vs-comment.md index 0110c6a..125871b 100644 --- a/doc/design/code-vs-comment.md +++ b/doc/design/code-vs-comment.md @@ -1,8 +1,8 @@ -# 可执行面与叙述面 +# 可执行面与叙述面 | | | |---|---| -| 状态 | 与 mapping v0.1 对齐 | +| 状态 | 与 mapping v0.1 / keywords 对齐 | | 日期 | 2026-08-04 | --- @@ -15,13 +15,7 @@ | **Marqdo 可执行面** | 结构标记 + `*语句*` + `**返回**` | 本语言程序 | | **外联面** | ` ```lang ` | 其它语言(FFI) | -输出属于可执行面里的**函数调用**(如 `> 输出`),不是单独一类标记架构。 - ---- - -## 为何无标记不是「默认代码」 - -中文说明必须能直接写。可执行内容进入 `*` / `**` / `#` / `>` / `+` / `-` / 表等。详见 [markdown-mapping.md](markdown-mapping.md)。 +输出属于可执行面里的**函数调用**(`> print …`),见 [keywords.md](keywords.md)。 --- @@ -31,4 +25,4 @@ |-----------|------|------------| | `*…*` | 程序语句 | 是 | | `**…**` | 返回值 | 是 | -| `> 输出 …` | 打印等副作用 | 否(普通函数) | +| `> print …` | 打印副作用 | 否(内置函数) | diff --git a/doc/design/dependencies.md b/doc/design/dependencies.md index c455034..578c95b 100644 --- a/doc/design/dependencies.md +++ b/doc/design/dependencies.md @@ -1,4 +1,4 @@ -# Marqdo 实现依赖说明(Rust 参考解释器) +# Marqdo 实现依赖说明(Rust 参考解释器) | | | |---|---| diff --git a/doc/design/generated-yaml-manifest.md b/doc/design/generated-yaml-manifest.md index c7142f7..462b01b 100644 --- a/doc/design/generated-yaml-manifest.md +++ b/doc/design/generated-yaml-manifest.md @@ -1,4 +1,4 @@ -# 设计草案:机器生成的 YAML 清单(OKF 风格) +# 设计草案:机器生成的 YAML 清单(OKF 风格) | | | |---|---| diff --git a/doc/design/keywords.md b/doc/design/keywords.md new file mode 100644 index 0000000..e4043a7 --- /dev/null +++ b/doc/design/keywords.md @@ -0,0 +1,84 @@ +# Marqdo 关键字与内置名(v0 最小集) + +| | | +|---|---| +| 状态 | 已定(前期够用) | +| 日期 | 2026-08-04 | +| 原则 | **英文**;参考 [Python](https://realpython.com/python-keywords/) 但远更少;控制流仍靠 Markdown 标记,不引入 `if`/`while`/`def` | +| 相关 | [markdown-mapping.md](markdown-mapping.md) | + +--- + +## 1. 设计原则 + +1. **标记承担架构**:函数=`#`,分支=`+`,循环=`-`,返回=`**…**`,语句=`*…*`。因此 **不**把 `def`/`if`/`else`/`while`/`for`/`return` 做成关键字。 +2. **英文标识**:内置与字面量用英文,便于工具高亮与国际协作。 +3. **学 Python 的边界**:Python 3 里 [`print` / `input` 是内置函数,不是关键字](https://realpython.com/python-keywords/);布尔与空值是字面量关键字。Marqdo 同样区分 **关键字** vs **内置函数名**。 +4. **宁少勿多**:前期只列执行 examples 所需;要加再进 ADR。 + +--- + +## 2. 关键字(词法保留,不可作变量名) + +| 关键字 | 含义 | 备注 | +|--------|------|------| +| `True` | 布尔真 | 对齐 Python 大小写 | +| `False` | 布尔假 | | +| `None` | 空值 | | +| `and` | 逻辑与 | 表达式内 | +| `or` | 逻辑或 | | +| `not` | 逻辑非 | | + +**本期不引入:** `if` `else` `elif` `while` `for` `def` `class` `return` `import` `pass` `break` `continue` `in` `is` `lambda` … +(`else` 分支臂仍用臂头单独的 `*` 标记,不是单词 `else`。) + +--- + +## 3. 内置函数(可调用名,建议勿遮蔽) + +| 名称 | 作用 | 调用示例 | +|------|------|----------| +| `print` | 写到 stdout(副作用) | `> print text=Hello World!` | +| `input` | 从 stdin 读一行(返回文本) | `*`name` = > input prompt=Name: *` | + +参数约定(v0): + +- `print`:具名实参 `text`(必填);日后可扩展 `end` 等。 +- `input`:可选 `prompt`;返回用户输入字符串(不含换行)。 + +旧文档中的中文 `print` **废弃**,统一为 `print`。 + +--- + +## 4. 与 Markup 调用的关系 + +```markdown +# main + +> print text=Hello World! + +*`n` = 1* + ++ `n` > 0 + > print text=positive ++ * + > print text=other +``` + +- `>` 是**调用标记**(架构)。 +- `print` 是**被调名字**(内置库)。 +- 用户自定义 `# print` 会遮蔽内置(实现应警告)。 + +--- + +## 5. 标识符规则(摘要) + +- 变量:行内 `` `name` ``;`name` 不可为上表关键字。 +- 函数名:`#` 标题文本;建议 ASCII/英文,中文标题仍允许但内置名保持英文。 +- 比较:`==` `>` `<` `>=` `<=`;逻辑:`and` `or` `not`。 + +--- + +## 6. 后续可增(未批准) + +`len`、`str`、`int`、`float`、`range`;以及 `break`/`continue`(若循环需要)。增加前开短 ADR。 diff --git a/doc/design/markdown-mapping.md b/doc/design/markdown-mapping.md index 2313e8b..8062604 100644 --- a/doc/design/markdown-mapping.md +++ b/doc/design/markdown-mapping.md @@ -1,4 +1,4 @@ -# Marqdo 语法映射 v0.1(Markup-as-Syntax) +# Marqdo 语法映射 v0.1(Markup-as-Syntax) | | | |---|---| @@ -7,7 +7,7 @@ | 取代 | v0 中「`**`=输出、`*`=返回」 | | 相关 | [code-vs-comment.md](code-vs-comment.md) · [return-hr-and-code-surface.md](return-hr-and-code-surface.md) | -Markdown **标记即语法**。输出**不是**语言架构原语,而是普通函数(如 `> 输出`)。 +Markdown **标记即语法**。输出**不是**语言架构原语,而是内置函数 **`print`**(英文;见 [keywords.md](keywords.md))。 --- @@ -42,7 +42,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是普通 | 体内 `-` | 循环 | | 体内 `+` 或 `1.` | 分支 | | 分支臂头整行恰为 `*` | else | -| `> 函数 形参=实参` | 调用(含内置 `输出`) | +| `> 函数 形参=实参` | 调用(含内置 `print` / `input`) | | frontmatter `> path.mq.md` | 跨文件导入 | | `*…*` | **程序语句**(绑定、表达式句、可写的调用句等) | | `**…**` | **返回值**(架构级;函数结果) | @@ -55,10 +55,11 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是普通 | 错误(旧) | 正确(v0.1) | |------------|--------------| -| `**Hello**` 表示打印 | `> 输出 内容=Hello`(或 prelude 等价名) | +| `**Hello**` 表示打印 | `> print text=Hello` | +| 中文名 `输出`(已废弃) | 统一英文内置 `print` | | 输出与返回抢粗体 | 粗体只表示 **返回** | -`输出` 是与 `加一` 同类的函数,可内置、可用户实现。 +`print` / `input` 为内置函数,完整表见 [keywords.md](keywords.md)。 --- @@ -72,7 +73,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是普通 *`y` = `x` + 2* ``` -行首已是结构标记的构造(`#` `>` `+` `-` `|`)**不必**再包一层斜体;斜体用于「一般语句」槽位。也允许 `*> 输出 内容=hi*`,但不推荐。 +行首已是结构标记的构造(`#` `>` `+` `-` `|`)**不必**再包一层斜体;斜体用于「一般语句」槽位。 ### 返回值(粗体) @@ -83,12 +84,12 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是普通 **`n` + 1** ``` -### 输出(函数) +### 输出(内置函数 `print`) ```markdown # main -> 输出 内容=Hello World! +> print text=Hello World! ``` ### else 与斜体消歧 @@ -113,7 +114,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是普通 ```markdown # main -> 输出 内容=Hello World! +> print text=Hello World! ## 加问候 - 谁 @@ -121,7 +122,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是普通 **你好,`谁`** ``` -(需要打印时对返回值再 `> 输出`,或直接 `> 输出`。) +(需要打印时对返回值再 `> print`,或直接 `> print`。) 形参 `- 名` → 体内 `` `名` ``。 @@ -140,22 +141,22 @@ v0.1 **推荐**绑定写在斜体语句内,以保持「语句=斜体」一致 ## 8. 分支与循环 -分支(`+` / 有序),循环(`-`),语义同 v0。臂体内打印改为调用 `输出`: +分支(`+` / 有序),循环(`-`),语义同 v0。臂体内打印改为调用 `print`: ```markdown *`x` = 0* + `x` > 0 - > 输出 内容=正数 + > print text=正数 + `x` < 0 - > 输出 内容=负数 + > print text=负数 + * - > 输出 内容=零 + > print text=零 ``` ```markdown - [果](篮子) - > 输出 内容=今天吃`果` + > print text=今天吃`果` ``` --- @@ -171,7 +172,7 @@ v0.1 **推荐**绑定写在斜体语句内,以保持「语句=斜体」一致 1. 加载 `index.mq.md` + 导入。 2. Pass1 收集定义。 3. Pass2 执行 `# main`。 -4. `*` 语句、`**` 返回、`>` 调用、`+`/`-` 控制流、表绑定按语义执行;`> 输出` 写 stdout。 +4. `*` 语句、`**` 返回、`>` 调用、`+`/`-` 控制流、表绑定按语义执行;`> print` 写 stdout。 --- @@ -182,9 +183,9 @@ v0.1 **推荐**绑定写在斜体语句内,以保持「语句=斜体」一致 ```markdown --- + `x` > 0 - > 输出 内容=正 + > print text=正 + * - > 输出 内容=其它 + > print text=其它 --- ``` diff --git a/doc/design/pipeline-debug.md b/doc/design/pipeline-debug.md new file mode 100644 index 0000000..b94245e --- /dev/null +++ b/doc/design/pipeline-debug.md @@ -0,0 +1,71 @@ +# 解释器流水线可视调试 + +| | | +|---|---| +| 状态 | 已定(开发期强制友好) | +| 日期 | 2026-08-04 | +| 参考 | [Crafting Interpreters — Scanning](https://www.craftinginterpreters.com/scanning.html)(先打 token)· [AstPrinter](https://craftinginterpreters.com/representing-code.html) · CLI `--dump-ast` 类实践 | + +--- + +## 1. 目标 + +开发 `marqdo` 时,对任意 `.mq.md` 应能**分阶段看见**中间结果,避免黑盒;正式 `run` 默认安静,仅输出程序 `print` 的内容。 + +--- + +## 2. CLI 开关 + +```bash +marqdo run FILE [dumps...] +marqdo dump FILE --stage lines|tokens|ast|sema|all +``` + +| 标志 | 阶段 | 输出内容 | +|------|------|----------| +| `--dump-lines` | 行分类 | 每行:`LINE kind=Comment\|Code\|Blank` + 原文预览 | +| `--dump-tokens` | 词法 | Token 流:`type lexeme line:col` | +| `--dump-ast` | 语法 | S 表达式或缩进树(模块/函数/语句) | +| `--dump-sema` | 语义 | 作用域、导入图、提升后的符号表 | +| `--trace-eval` | 求值 | 进入/离开函数、绑定、分支臂选择、`print` 调用 | +| `--dump-all` | 以上全部 | 按管道顺序打印,段之间用横幅分隔 | + +格式约定: + +- 人类可读优先;段首统一:`=== marqdo: ===` +- 可选 `--dump-format=text|json`(json 后置,text 先做) +- 有 dump 时:若求值未实现,仍打印已实现阶段再以非 0 退出(便于 M1 只测 lines) + +--- + +## 3. 横幅示例 + +``` +=== marqdo: lines (examples/hello.mq.md) === + 1 Blank + 2 Comment | # Hello World + 3 Blank + 4 Comment | 本程序调用... + 5 Blank + 6 Code | > print text=Hello World! +=== marqdo: end lines === +``` + +--- + +## 4. 实现要点 + +- dump 逻辑放在 `src/debug/`(或各阶段 `fmt`),**不**与安静求值路径搅在一起。 +- 每个阶段纯函数:`input → (artifacts, diagnostics)`,CLI 负责打印。 +- 单测可断言 dump 字符串包含关键行(稳定子集),避免绑死全文格式。 + +--- + +## 5. 与里程碑 + +| 里程碑 | 必须可用的 dump | +|--------|-----------------| +| M1 | `--dump-lines`(及可选 tokens 雏形) | +| M2 | `--dump-ast` | +| M3–M4 | `--dump-sema`、`--trace-eval` | +| 全程 | `--dump-all` 随阶段增长自动变完整 | diff --git a/doc/design/return-hr-and-code-surface.md b/doc/design/return-hr-and-code-surface.md index 4625d2b..77d0e5d 100644 --- a/doc/design/return-hr-and-code-surface.md +++ b/doc/design/return-hr-and-code-surface.md @@ -1,18 +1,18 @@ -# 记录:返回 / 语句 / 输出 / 分割线(决议) +# 记录:返回 / 语句 / 输出 / 分割线(决议) | | | |---|---| -| 状态 | 已决议(并入 mapping v0.1) | +| 状态 | 已决议(并入 mapping v0.1 + keywords) | | 日期 | 2026-08-04 | --- ## 决议 -1. **`*…*` = 程序语句**(与粗体不冲突)。 +1. **`*…*` = 程序语句**。 2. **`**…**` = 返回值**(架构级)。 -3. **输出**不用粗体;用**关键字/函数**(如 `> 输出`)。输出不是语言架构一环,只是函数。 -4. **`---` / `***`**:建议用于**可选地框住**分支与循环,使版面清晰;**不强制**;若暂时不用,留待日后缺块级语法时再升级。 -5. **否决**:无标记行 = 默认代码(叙述会崩溃)。无标记保持注释。 +3. **输出**用内置函数 **`print`**(英文),不是粗体,不是中文名。 +4. **`---` / `***`**:可选框住分支/循环,不强制。 +5. **否决**:无标记行 = 默认代码。 -曾讨论「粗体=一般程序面 / 分割线=返回」的路径,由本决议取代。权威条文见 [markdown-mapping.md](markdown-mapping.md)。 +详见 [keywords.md](keywords.md)、[markdown-mapping.md](markdown-mapping.md)。 diff --git a/doc/design/tech-stack.md b/doc/design/tech-stack.md index 6d2f029..616a536 100644 --- a/doc/design/tech-stack.md +++ b/doc/design/tech-stack.md @@ -1,4 +1,4 @@ -# 参考实现:技术选型分析(尚未拍板) +# 参考实现:技术选型分析(尚未拍板) | | | |---|---| diff --git a/doc/roadmap/interpreter.md b/doc/roadmap/interpreter.md index 09d414f..4121498 100644 --- a/doc/roadmap/interpreter.md +++ b/doc/roadmap/interpreter.md @@ -1,4 +1,4 @@ -# Marqdo 参考实现:正经解释器路线图 +# Marqdo 参考实现:正经解释器路线图 | | | |---|---| @@ -95,7 +95,7 @@ Phase I 对齐 Crafting Interpreters 的 **jlox(树遍历)**;Phase II 对 1. **词法 / 行分类**:注释与代码严格分离。 2. **语法 → AST**:函数、形参、`*` 语句、`**` 返回、`>` 调用、`+` 分支、`-` 循环、表格集合、绑定与 `==`。 3. **语义**:提升、嵌套作用域、`##` 私有、frontmatter 导入公有顶层。 -4. **运行时**:环境、调用栈、值(文/数/表/记录)、内置 `输出`。 +4. **运行时**:环境、调用栈、值(文/数/表/记录)、内置 `print`。 5. **验收**:`examples/hello` … `with-import` 全部 `marqdo run` 通过。 ### Phase II — 字节码 VM(正经化) diff --git a/examples/branch.mq.md b/examples/branch.mq.md index 8efa8c4..462d442 100644 --- a/examples/branch.mq.md +++ b/examples/branch.mq.md @@ -1,4 +1,4 @@ ---- +--- title: 分支示例 --- @@ -7,8 +7,8 @@ title: 分支示例 *`x` = 0* + `x` > 0 - > 输出 内容=正数 + > print text=正数 + `x` < 0 - > 输出 内容=负数 + > print text=负数 + * - > 输出 内容=零 + > print text=零 diff --git a/examples/collection.mq.md b/examples/collection.mq.md index 7736ad7..4f7f200 100644 --- a/examples/collection.mq.md +++ b/examples/collection.mq.md @@ -1,4 +1,4 @@ ---- +--- title: 集合(表格)示例 --- @@ -13,4 +13,4 @@ title: 集合(表格)示例 | 桃 | - [果](篮子) - > 输出 内容=`果` + > print text=`果` diff --git a/examples/hello.mq.md b/examples/hello.mq.md index 16babba..6760fa1 100644 --- a/examples/hello.mq.md +++ b/examples/hello.mq.md @@ -1,5 +1,5 @@ -# Hello World +# Hello World -本程序调用内置(或 prelude)函数 `输出` 打印问候。注释里的 **粗体** 与 *斜体* 都不执行。 +本程序调用内置函数 `print` 打印问候。注释里的 **粗体** 与 *斜体* 都不执行。 -> 输出 内容=Hello World! +> print text=Hello World! diff --git a/examples/index.mq.md b/examples/index.mq.md index 27a7dc2..94026f0 100644 --- a/examples/index.mq.md +++ b/examples/index.mq.md @@ -1,15 +1,15 @@ ---- +--- title: Hello World -description: 推荐风格——内嵌函数;输出为函数调用;返回用粗体 +description: Recommended entry — nested fn; print builtin; bold return --- # main -打印一句问候。`输出` 是函数,不是语法架构;粗体只用于返回值。 +打印一句问候。`print` 是函数,不是语法架构;粗体只用于返回值。 > 问候 谁=World ## 问候 - 谁 -> 输出 内容=Hello `谁`! +> print text=Hello `谁`! diff --git a/examples/loop.mq.md b/examples/loop.mq.md index aa4a463..d86222a 100644 --- a/examples/loop.mq.md +++ b/examples/loop.mq.md @@ -1,4 +1,4 @@ ---- +--- title: 循环示例 --- @@ -9,7 +9,7 @@ title: 循环示例 *`n` = 3* - `n` > 0 - > 输出 内容=`n` + > print text=`n` *`n` = `n` - 1* ## foreach:遍历篮子 @@ -22,4 +22,4 @@ title: 循环示例 | 梨 | - [果](篮子) - > 输出 内容=今天吃`果` + > print text=今天吃`果` diff --git a/examples/utils.mq.md b/examples/utils.mq.md index 0bbece1a..8d7a2fc 100644 --- a/examples/utils.mq.md +++ b/examples/utils.mq.md @@ -1,4 +1,4 @@ ---- +--- title: 工具函数 description: 供 frontmatter > 导入;返回用粗体;副作用用输出函数 --- @@ -11,4 +11,4 @@ description: 供 frontmatter > 导入;返回用粗体;副作用用输出函 # 问候 - 谁 -> 输出 内容=你好,`谁`! +> print text=你好,`谁`! diff --git a/examples/with-import.mq.md b/examples/with-import.mq.md index e425928..798f869 100644 --- a/examples/with-import.mq.md +++ b/examples/with-import.mq.md @@ -1,4 +1,4 @@ ---- +--- title: 跨文件导入示例 > utils.mq.md --- @@ -9,6 +9,6 @@ title: 跨文件导入示例 *`y` = > 加一 n=41* -> 输出 内容=`y` +> print text=`y` > 问候 谁=Marqdo diff --git a/spike/README.md b/spike/README.md index 8a1c09a..208251d 100644 --- a/spike/README.md +++ b/spike/README.md @@ -1,4 +1,4 @@ -# Marqdo Spike(Python) +# Marqdo Spike(Python) 快速验收 ADR 0001 中的 S1–S5,**不是**完整解释器。 diff --git a/src/debug.rs b/src/debug.rs new file mode 100644 index 0000000..d8fe816 --- /dev/null +++ b/src/debug.rs @@ -0,0 +1,3 @@ +//! Pipeline dump helpers (see doc/design/pipeline-debug.md). + +pub use crate::lex::format_lines_dump; diff --git a/src/lex/mod.rs b/src/lex/mod.rs index 6dc4c48..da8c140 100644 --- a/src/lex/mod.rs +++ b/src/lex/mod.rs @@ -1,11 +1,130 @@ -//! Line classification and tokenization (no Flex). -//! Implementation arrives in M1. +//! Line classification (M1) — no Flex. +//! +//! Unmarked lines are comments; lines whose first non-whitespace character +//! opens a Marqdo/Markdown marker are code. -#![allow(dead_code)] +use std::fmt; +/// Kind of a source line after skipping leading indentation for the test. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LineKind { + Blank, Comment, Code, - Blank, +} + +impl fmt::Display for LineKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + LineKind::Blank => write!(f, "Blank"), + LineKind::Comment => write!(f, "Comment"), + LineKind::Code => write!(f, "Code"), + } + } +} + +/// One classified source line (1-based line number). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ClassifiedLine { + pub line_no: u32, + pub kind: LineKind, + pub text: String, +} + +/// Characters that start a code line when they appear as the first non-ws char. +fn is_code_starter(c: char) -> bool { + matches!( + c, + '#' | '*' | '>' | '+' | '-' | '`' | '|' | '~' + ) || c.is_ascii_digit() +} + +/// Classify a single logical line (no trailing newline required). +pub fn classify_line(text: &str) -> LineKind { + let trimmed = text.trim_end_matches(['\r', '\n']); + if trimmed.chars().all(|c| c.is_whitespace()) { + return LineKind::Blank; + } + let first = trimmed.chars().find(|c| !c.is_whitespace()); + match first { + None => LineKind::Blank, + Some(c) if is_code_starter(c) => LineKind::Code, + Some(_) => LineKind::Comment, + } +} + +/// Classify every line of a source file. +pub fn classify_source(source: &str) -> Vec { + let source = source.strip_prefix('\u{feff}').unwrap_or(source); + let lines: Vec<&str> = if source.is_empty() { + Vec::new() + } else { + source.lines().collect() + }; + + lines + .into_iter() + .enumerate() + .map(|(i, text)| ClassifiedLine { + line_no: (i + 1) as u32, + kind: classify_line(text), + text: text.to_string(), + }) + .collect() +} + +/// Human-readable dump for `--dump-lines`. +pub fn format_lines_dump(path: &str, lines: &[ClassifiedLine]) -> String { + let mut out = String::new(); + out.push_str(&format!("=== marqdo: lines ({path}) ===\n")); + for line in lines { + let preview = if line.text.len() > 80 { + format!("{}…", &line.text.chars().take(80).collect::()) + } else { + line.text.clone() + }; + match line.kind { + LineKind::Blank => { + out.push_str(&format!("{:4} {:7}\n", line.line_no, line.kind)); + } + _ => { + out.push_str(&format!( + "{:4} {:7} | {}\n", + line.line_no, line.kind, preview + )); + } + } + } + out.push_str("=== marqdo: end lines ===\n"); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blank_and_comment_and_code() { + assert_eq!(classify_line(""), LineKind::Blank); + assert_eq!(classify_line(" "), LineKind::Blank); + assert_eq!(classify_line("hello world"), LineKind::Comment); + assert_eq!(classify_line(" 中文说明"), LineKind::Comment); + assert_eq!(classify_line("> print text=hi"), LineKind::Code); + assert_eq!(classify_line("# main"), LineKind::Code); + assert_eq!(classify_line("*`x` = 1*"), LineKind::Code); + assert_eq!(classify_line("**ret**"), LineKind::Code); + assert_eq!(classify_line("+ `x` > 0"), LineKind::Code); + assert_eq!(classify_line("- item"), LineKind::Code); + assert_eq!(classify_line("1. arm"), LineKind::Code); + assert_eq!(classify_line("| a |"), LineKind::Code); + assert_eq!(classify_line("`x` = 1"), LineKind::Code); + } + + #[test] + fn classify_hello_fixture() { + let src = include_str!("../../examples/hello.mq.md"); + let lines = classify_source(src); + assert!(lines.iter().any(|l| l.kind == LineKind::Code && l.text.contains("print"))); + assert!(lines.iter().any(|l| l.kind == LineKind::Comment)); + } } diff --git a/src/lib.rs b/src/lib.rs index 0f2071b..ca99a4a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,8 +1,8 @@ -//! Marqdo reference interpreter (Phase I scaffolding). +//! Marqdo reference interpreter (Phase I). //! -//! Pipeline (see `doc/roadmap/interpreter.md`): -//! load → line classify / lex → parse → sema → tree-walk eval. +//! Pipeline: load → line classify / lex → parse → sema → tree-walk eval. +pub mod debug; pub mod diagnostics; pub mod lex; pub mod parse; @@ -11,20 +11,70 @@ use std::path::Path; use anyhow::{bail, Context, Result}; -/// Run a `.mq.md` program. Phase I: not yet implemented beyond scaffolding. -pub fn run_file(path: &Path) -> Result { +use crate::lex::{classify_source, format_lines_dump}; + +/// Options for a single `run` / dump invocation. +#[derive(Debug, Clone, Default)] +pub struct RunOptions { + pub dump_lines: bool, + pub dump_tokens: bool, + pub dump_ast: bool, + pub dump_sema: bool, + pub trace_eval: bool, +} + +impl RunOptions { + pub fn dump_all() -> Self { + Self { + dump_lines: true, + dump_tokens: true, + dump_ast: true, + dump_sema: true, + trace_eval: true, + } + } + + pub fn any_dump(&self) -> bool { + self.dump_lines || self.dump_tokens || self.dump_ast || self.dump_sema || self.trace_eval + } +} + +/// Run a `.mq.md` program (M1: line classify + dumps; eval still TODO). +pub fn run_file(path: &Path, opts: &RunOptions) -> Result { let source = std::fs::read_to_string(path) .with_context(|| format!("failed to read {}", path.display()))?; + let path_label = path.display().to_string(); + let lines = classify_source(&source); + + if opts.dump_lines { + print!("{}", format_lines_dump(&path_label, &lines)); + } + if opts.dump_tokens { + println!("=== marqdo: tokens ({path_label}) ==="); + println!("(tokens not implemented yet — M1+)"); + println!("=== marqdo: end tokens ==="); + } + if opts.dump_ast { + println!("=== marqdo: ast ({path_label}) ==="); + println!("(ast not implemented yet — M2)"); + println!("=== marqdo: end ast ==="); + } + if opts.dump_sema { + println!("=== marqdo: sema ({path_label}) ==="); + println!("(sema not implemented yet — M3+)"); + println!("=== marqdo: end sema ==="); + } + if opts.trace_eval { + println!("=== marqdo: trace-eval ({path_label}) ==="); + println!("(eval not implemented yet — M2+)"); + println!("=== marqdo: end trace-eval ==="); + } + if source.is_empty() { bail!("{} is empty", path.display()); } - // Placeholder: real lex/parse/eval lands in subsequent milestones. - eprintln!( - "marqdo: loaded {} ({} bytes); interpreter not implemented yet (M0 scaffold)", - path.display(), - source.len() - ); - bail!("evaluation not implemented — see doc/roadmap/interpreter.md (M1+)") + // Until eval exists: dumps are useful; run still fails loudly. + bail!("evaluation not implemented — see doc/roadmap/interpreter.md (M2+)") } diff --git a/src/main.rs b/src/main.rs index d46eddf..7228b98 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,8 @@ use std::process::ExitCode; use anyhow::Result; use clap::{Parser, Subcommand}; +use marqdo::RunOptions; + #[derive(Parser, Debug)] #[command(name = "marqdo", version, about = "Marqdo interpreter — run .mq.md programs")] struct Cli { @@ -18,6 +20,30 @@ enum Commands { /// Path to a `.mq.md` file #[arg(value_name = "FILE")] file: Option, + + /// Dump line classification + #[arg(long)] + dump_lines: bool, + + /// Dump tokens (placeholder until lexer fills in) + #[arg(long)] + dump_tokens: bool, + + /// Dump AST (placeholder until parser exists) + #[arg(long)] + dump_ast: bool, + + /// Dump semantic info (placeholder) + #[arg(long)] + dump_sema: bool, + + /// Trace evaluation (placeholder) + #[arg(long)] + trace_eval: bool, + + /// Enable all dumps + #[arg(long)] + dump_all: bool, }, } @@ -34,9 +60,36 @@ fn main() -> ExitCode { fn try_main() -> Result { let cli = Cli::parse(); match cli.command { - Commands::Run { file } => { + Commands::Run { + file, + dump_lines, + dump_tokens, + dump_ast, + dump_sema, + trace_eval, + dump_all, + } => { let path = file.unwrap_or_else(|| PathBuf::from("index.mq.md")); - marqdo::run_file(&path)?; + let mut opts = if dump_all { + RunOptions::dump_all() + } else { + RunOptions { + dump_lines, + dump_tokens, + dump_ast, + dump_sema, + trace_eval, + } + }; + // dump_all already set; individual flags merge if not dump_all + if !dump_all { + opts.dump_lines = dump_lines; + opts.dump_tokens = dump_tokens; + opts.dump_ast = dump_ast; + opts.dump_sema = dump_sema; + opts.trace_eval = trace_eval; + } + marqdo::run_file(&path, &opts)?; Ok(0) } } diff --git a/tests/cli_m0.rs b/tests/cli_m0.rs index 3e5e9c1..89d4308 100644 --- a/tests/cli_m0.rs +++ b/tests/cli_m0.rs @@ -9,7 +9,7 @@ fn cli_runs_and_reports_unimplemented() { assert!( !output.status.success(), - "M0 should exit non-zero until eval exists" + "M0/M1 should exit non-zero until eval exists" ); let stderr = String::from_utf8_lossy(&output.stderr); assert!( @@ -17,3 +17,21 @@ fn cli_runs_and_reports_unimplemented() { "stderr was: {stderr}" ); } + +#[test] +fn cli_dump_lines_shows_classification() { + let output = Command::new(env!("CARGO_BIN_EXE_marqdo")) + .args(["run", "examples/hello.mq.md", "--dump-lines"]) + .output() + .expect("failed to run marqdo"); + + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + stdout.contains("=== marqdo: lines"), + "stdout was: {stdout}" + ); + assert!(stdout.contains("Code"), "expected Code line: {stdout}"); + assert!(stdout.contains("Comment") || stdout.contains("Blank"), "{stdout}"); + assert!(stdout.contains("print"), "{stdout}"); + assert!(!output.status.success()); +}