Add math stdlib with formulas/plots and polish the docs view.

Ship Num/Formula runtime, bilingual math libs, SVG plots with axes/grid, and view UX for collapsible folders plus centered plots.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-05 11:30:47 +08:00
1 parent a53ebb65ee
commit dcd0cdb8f7
40 files changed
+3553 -276

No files matched your search

+1 -1
View File
@@ -27,7 +27,7 @@
| [design/stdlib.md](design/stdlib.md) | **P2 标准库:内置 + `lib/` + 错误约定** |
| [design/stdlib-i18n.md](design/stdlib-i18n.md) | **标准库中英命名:靠库文件名区分,无 lang 开关** |
| [design/stdlib-modules.md](design/stdlib-modules.md) | **本波 L1:文件/系统/时间/JSON/网络(JSON 中英同库)** |
| [design/stdlib-math.md](design/stdlib-math.md) | **暂缓:数学库(数值/符号/作图/`$$`)** |
| [design/stdlib-math.md](design/stdlib-math.md) | **方案:数学库(数值/随机/作图/轻量求解)** |
| [design/stdlib-foreign.md](design/stdlib-foreign.md) | **暂缓:外联胶水(\`\`\`lang 具名块)** |
| [design/call-arguments.md](design/call-arguments.md) | **调用:具名 + 位置实参** |
| [design/examples-and-tests.md](design/examples-and-tests.md) | **tests/ 金样例目录布局** |
+1
View File
@@ -51,6 +51,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
| `****` / `**` + 空白 + `**` | **空返回**(`None`),并结束本函数体 |
| 无标记行 / 成段续行 | 注释(空行分段,见 §2) |
| GFM 表格 | 集合 |
| 空 RHS 赋值 + 后随 `$$…$$`(或同行 `$$…$$`) | **公式赋值** → 运行时 `formula`(见 [stdlib-math.md](stdlib-math.md));叙述面无名 `$$` 仅展示 |
| ` ```lang ` | 外联异种代码 |
| 函数体内 `---` / `***` | **结束本函数体**(无返回值函数的收束;见 §11) |
+172 -122
View File
@@ -1,181 +1,231 @@
# 数学标准库(候选)
# 数学标准库(方案)
| | |
|---|---|
| 状态 | **草案 / 暂缓**(本波不实现;五库之后再议) |
| 状态 | **已实现(M1–M4)** |
| 日期 | 2026-08-05 |
| 相关 | [stdlib-modules.md](stdlib-modules.md) · [stdlib-i18n.md](stdlib-i18n.md) · [view.md](view.md) · [markdown-mapping.md](markdown-mapping.md) |
| 灵感 | Markdown `$$…$$` / `$…$` 公式面;文档即计算笔记本 |
| 相关 | [stdlib-modules.md](stdlib-modules.md) · [stdlib-i18n.md](stdlib-i18n.md) · [markdown-mapping.md](markdown-mapping.md) · [view.md](view.md) |
| 导入 | `lib/math.mq.md`(英)· `lib/数学.mq.md`(中) |
| 范围 | **高中数学**(初等函数、导数、圆锥曲线、简单方程);非大学 CAS |
---
## 1. 为什么值得做
## 1. 目标
Markdown 读者已习惯用 `$$` 写公式。若 Marqdo 能:
1. **公式类型**:解析 `$$…$$`(及行内 `$…$` 的可选支持),得到可绑定、可传递的 **`formula` 值**——语义上像「公式常量 / 公式变量」。
2. **数学库对 `formula`(及文本表达式)做操作**:求值、化简、求导、求解、作图等。
3. **数值 + 随机**:日常算术与可复现随机。
4. **作图**:view / 静态页内嵌 SVG;CLI 写本地文件(可指定 `path`)。
1. **认出**文档中的公式(或显式传入 LaTeX/ASCII-math 字符串);
2. **符号整理 / 求值 / 求解**;
3. 在 **`marqdo view` 里画出**简单图像;
则同一份 `.mq.md` 既是讲义又是可运行实验,差异化远大于「再包一层 `sin`」。
风险同样大:CAS、数值稳定、渲染栈都会显著增加依赖与维护面。故标为**候选**:先定分层,允许只实现「数值 + 显式字符串」,再渐进接 `$$`。
**难度自觉:** 只覆盖高中知识面,自研小型表达式 AST + 规则即可,**不**追求 Mathematica / SymPy 完备性。
---
## 2. 产品分层(建议)
## 2. 核心模型:`formula` 类型
| 层 | 能力 | 依赖量 | 建议阶段 |
|----|------|--------|----------|
| **Math-N(数值)** | 四则、幂、根、三角函数、常数;列表上的 map 式计算 | 小(可纯 Rust) | 若纳入官方库,**先做这层** |
| **Math-S(符号)** | 化简、展开、求导、代入、解方程(单变元优先) | 中–大(自研子集或嵌 CAS) | 第二期 |
| **Math-P(作图)** | 把表达式/点列渲染为 SVG(或 PNG)嵌入 view | 中(SVG 即可) | 与 view 同期 |
| **Math-D(文档公式)** | 解析正文 `$$…$$`,命名后供调用 | 中(词法/源映射) | 第三期 |
### 2.1 运行时
**默认发版建议:** 官方 `lib/math` 先只承诺 **Math-N**;S/P/D 放 `experimental` 或 feature `math-cas` / `math-plot`,避免「标准库」名不副实。
| 类型 | `type` 标签 | 说明 |
|------|-------------|------|
| `Value::Num(f64)` | `num` | 浮点 |
| `Value::Formula(…)` | `formula` | 已解析的表达式树(或等价内部表示) |
---
`print` / `str` 对 `formula`:输出规范 ASCII(如 `2*x + 1`)或保留源 LaTeX 的一种(实现时写死并文档化;建议 **ASCII 规范式** 便于测试)。
## 3. 导入与命名
### 2.2 文档中的 `$$` = 公式赋值(与表格同构)
| 导入 | API 语言 |
|------|----------|
| `> lib/math.mq.md` | 英文 |
| `> lib/数学.mq.md` | 中文 |
在可执行面用 **空 RHS 赋值** 后跟展示数学块,把公式绑到变量(与 `` `xs` = `` 后跟表格一致):
宿主原语(L0.5)示例:`math_sin`、`math_eval`、`math_solve` —— 仅供库包装。
````markdown
# main
---
`f` =
$$
sin(x) + x
$$
## 4. 用户 API 草图
*`df` = > diff formula=`f` var=x *
### 4.1 数值(Math-N)
> plot formula=`f` var=x min=-3 max=3 path=f.svg
````
也支持:
- 单行围栏:下一行 `$$x^2 - 2$$`
- 同行 compact:`*`f` = $$x^2 - 2$$ *`
**废除:** `$$:name` / `$$ name=…` 模块级具名块(不再产生绑定)。
**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区若出现未挂在赋值上的裸 `$$` 围栏 → 报错,提示使用 `` `name` = `` + 围栏。
**行内 `$…$`:** v1 不做绑定;需要时用 `> formula text=…` 显式构造。
### 2.3 从文本构造
| 英文 | 中文 | 说明 |
|------|------|------|
| `pi` / `e` | `圆周率` / `自然底数` | 无参,返回文本或「十进制文本」——**本波仍无 float 类型时用文本十进制**,或引入 `num` 宿主类型 |
| `add` `sub` `mul` `div` `pow` `sqrt` | `加` `减` `乘` `除` `幂` `根` | |
| `sin` `cos` `tan` `ln` `exp` | `正弦` `余弦` `正切` `对数` `指数` | 弧度 |
| `round` `floor` `ceil` | `四舍` `向下` `向上` | |
| `eval_num` | `求值` | `expr` 文本 → 数值文本 |
| `formula` | `公式` | `text=` 解析为 `formula`(ASCII 或简单 LaTeX 子集) |
**类型抉择(必须先 ADR):**
数学库函数形参统一接受:**`formula` 值**,或能解析的 **文本**(内部先 `formula` 化)。
| 选项 | 优点 | 缺点 |
### 2.4 与叙述面的关系
- `` `f` = `` + `$$…$$`:代码面赋值,得到 `formula` 值。
- 成段注释里的 `$$`:仍是注释,不解析为公式。
- view:公式赋值在 Structure 中显示为绑定,不是 comment。
(见 [markdown-mapping.md](markdown-mapping.md):空 RHS + `$$` → 公式赋值。)
---
## 3. 知识范围(高中)
### 3.1 表达式与符号(S)
| 纳入 | 例子 |
|------|------|
| 多项式 | `x^2 - 3*x + 2` |
| 初等函数 | `sin` `cos` `tan` `ln` `exp` `sqrt` `abs` |
| 四则、幂 | `+ - * / ^` |
| 化简 / 展开 | 合并同类项、基本三角恒等(小集合) |
| 求导 | 单变元,初等函数求导法则 |
| 代入求值 | `subs` → `num` 或公式 |
| 求解 | 一元一次 / 二次闭式;其它用数值求根并标明 |
**不做(本波):** 多元方程组、极限 ε-δ、级数、积分保证、矩阵、复数完备、任意证明。
### 3.2 作图(P)
| 纳入 | 说明 |
|------|------|
| 显函数 `y=f(x)` | 采样折线 SVG |
| 导数曲线 | 对 `formula` 先 `diff` 再画,或 `plot` 选项 `derivative=true` |
| 圆锥曲线 | 标准形:圆、椭圆、双曲线、抛物线(参数方程或隐式采样) |
| 点列 | `plot_points` |
**不做:** 三维、隐函数通用求解器、交互缩放(静态 SVG 足够)。
### 3.3 数值与随机(N)
常数、四则、三角、对数、取整、`num` 转换、`random` / `random_int` / `seed`(同前稿)。
---
## 4. API 草图(对 `formula` 操作)
### 4.1 构造与数值
| 英文 | 中文 | 要点 |
|------|------|------|
| A. 继续只用 `int` + 十进制 `text` | 不碰 L0 | 慢、易错 |
| B. 新增宿主 `num`(十进制或 f64) | API 干净 | 类型与字节码要跟进 |
| C. 数学库内部不透明 `handle` | 隔离好 | 与 `print`/`json` 互通差 |
| `formula` | `公式` | 文本 → formula |
| `pi` `e` | `圆周率` `自然底数` | → num |
| `add`… / `sin`… | `加`… / `正弦`… | 对 num;若传入 formula 则返回 formula(符号)或报错——**v1 建议:算术函数只接 num;符号用 simplify/diff/subs** |
| `eval` | `求值` | `formula` + 变量赋值 → num |
| `random` / `random_int` / `seed` | `随机` / `随机整数` / `设种子` | 见前 |
倾向:**B(`num`)**,与 JSON 的非整数数字策略一并设计。
### 4.2 符号(Math-S)
### 4.2 符号
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `simplify` | `化简` | `expr` | 表达式文本(或 handle) |
| `expand` | `展开` | `expr` | 同上 |
| `diff` | `求导` | `expr`, `var` | 同上 |
| `subs` | `代入` | `expr`, `var`, `value` | 同上 |
| `solve` | `求解` | `expr`, `var` | 解列表(文本) |
| `simplify` | `化简` | `formula` | formula |
| `expand` | `展开` | `formula` | formula |
| `diff` | `求导` | `formula`, `var` | formula |
| `subs` | `代入` | `formula`, `var`, `value` | formula 或 num |
| `solve` | `求解` | `formula`, `var`,可选区间 | list(num 或公式根) |
表达式互换格式(草案):**ASCII 优先**(`2*x^2 + 1`),LaTeX 作为可选输入 `format=latex`。
### 4.3 作图
单变元多项式 / 简单超越方程为 v1 目标;多变元方程组、积分:**不做承诺**。
### 4.3 作图(Math-P)
| 英文 | 中文 | 说明 |
| 英文 | 中文 | 形参 |
|------|------|------|
| `plot_fn` | `绘函数` | `expr`, `var`, `min`, `max`, 可选 `steps` → **SVG 文本** |
| `plot_points` | `绘点列` | `xs`, `ys` → SVG 文本 |
| `plot` | `绘图` | **`formula`**(或 `expr` 文本), `var`, `min`, `max`;可选 `steps`, `path`, `derivative`, **`grid`**(默认开;`False`/`假` 关) |
| `plot_conic` | `绘圆锥` | `kind`(circle/ellipse/hyperbola/parabola)+ 系数;可选 `path`, `grid` |
| `plot_points` | `绘点列` | `xs`, `ys`;可选 `path`, `grid` |
view 行为:
返回 **SVG 文本**;坐标轴带箭头与刻度,默认网格;写文件与 view 嵌入规则同前(§5)。
- 若 stdout / 返回值为「带标记的 SVG」或约定 MIME,Execution 区**内嵌渲染**(非仅 `<pre>`)。
- 静态 `view output`:把 SVG 写入 HTML。
- CLI:默认打印 SVG 文本;`--plot-file out.svg` 可选。
`diff` / `simplify` / `expand` / 未完全数值化的 `subs` 返回 **`formula`**,可继续链式调用。
不引入完整浏览器 Chart 框架;**SVG 路径足够**教微积分与拟合入门。
示例:
### 4.4 文档公式面(Math-D)
```markdown
# main
与 [markdown-mapping.md](markdown-mapping.md) 的衔接:
`f` =
$$
x^2 - 2
$$
| 现状 | 目标 |
*`roots` = > solve formula=`f` var=x *
> print text=`roots`
*`svg` = > plot formula=`f` var=x min=-3 max=3 path=parabola.svg *
```
---
## 5. 作图:CLI / view / 静态(不变精神)
| 场景 | 行为 |
|------|------|
| `$$` 多半落入叙述/未定义 | 可选:**命名公式块**可被引用 |
| 带 `path=` | 写 SVG 到该路径(沙箱内) |
| CLI 无 path | 自动 `{stem}-plot-{n}.svg` + 一行 `plot: …` |
| view / 导出无 path | 不强制写盘;加入 **plots 产物列表**,Execution 内嵌 |
| view / 导出有 path | 写盘 + 内嵌 |
建议语法(草案,需进 mapping 修订):
```markdown
$$:energy
E = mc^2
$$
```
或 frontmatter / 标题锚定:
```markdown
## energy
$$
E = mc^2
$$
```
调用:
```markdown
---`
> lib/math.mq.md
---`
*`e2` = > simplify expr=> formula name=energy *
```
更简单的 v1:**不解析正文 `$$`**,只接受:
```markdown
*`e2` = > simplify expr=E=mc^2 format=latex *
```
正文 `$$` 仍由 view 的 Markdown 渲染(KaTeX/MathJax)负责「好看」,计算走显式字符串——**降低词法耦合**,推荐作为第一刀。
不把整段 SVG 默认灌进 CLI stdout。
---
## 5. 实现策略选项
## 6. 分期
| 策略 | 说明 | 建议 |
|------|------|------|
| **纯 Rust 数值** | `libm` / 自写 | Math-N 必选 |
| **嵌入轻量 CAS** | 如符号子集自研,或绑 `meval`/`fasteval` 仅数值 | 求值用 |
| **外挂 SymPy(经外联库)** | 符号交给 Python | 与 [stdlib-foreign.md](stdlib-foreign.md) 合流;标准库变薄 |
| **WASM CAS** | 可嵌入 view | 后期 |
| 期 | 交付 |
|----|------|
| **M1** | `Num` + 数值/随机;`Formula` AST + `` `name` = `` + `$$…$$` 赋值绑定 |
| **M2** | `simplify` / `diff` / `subs` / `eval` / 二次 `solve`(高中子集) |
| **M3** | `plot` / `plot_points` / `plot_conic` + view 内嵌 + path 写盘 |
| **M4** | 用户文档 `public/stdlib/math*` · 金样例 · mapping 文档补丁 |
务实路径:**Math-N 自研 → Math-P SVG → Math-S 先外联 SymPy(可选)→ 再考虑内嵌**。这样「数学标准库」在官方包里可以很瘦,重能力走外联 feature。
M1–M3 可在同一发版列车上连续落地;验收以「公式赋值 → 求导 → 作图」一条龙为准。
---
## 6. 安全与性能
## 7. 实现要点
- 表达式长度、求解迭代、绘图采样点设硬上限。
- 禁止公式里跑任意宿主代码(与外联分离)。
- view 中绘图同步、限时。
```text
src/formula/ # 词法/AST/化简/求导/求值(高中规则表)
src/host/math.rs # 数值、随机、对 formula 的 host 入口
src/host/plot.rs # SVG
lex/parse:空 RHS 赋值 + $$ 围栏 → Expr::Formula
Value::Num / Value::Formula
Interpreter.plots: Vec<String>
lib/math.mq.md · lib/数学.mq.md
```
依赖:纯 Rust;不绑 SymPy。公式复杂度、采样点、SVG 大小设硬上限。
---
## 7. 是否定为「标准库」的决策标准
## 8. 刻意不做
纳入默认 `lib/math` 当且仅当:
1. Math-N API 稳定且有中英金样例;
2. 不强制下载数百 MB 依赖;
3. 无外联时文档站示例仍可跑(纯数值 + 可选 SVG)。
若符号/作图依赖 SymPy 或大型引擎 → 标 **`lib/math` = 数值**,符号示例放到 `examples/math-cas` 并要求 `--allow-foreign`。
- `$$:name` 模块级具名绑定(已废除)。
- 无名 `$$` 自动进运行时。
- 大学级数 / 完备积分 / 定理证明。
- 通用隐函数作图引擎。
- 3D、交互式图表库。
---
## 8. 一句话
## 9. 验收
**用 Markdown 的公式习惯服务「可计算文档」;官方数学库先数值与 SVG,符号与 `$$` 引用分期,必要时借外联而非做大内核。**
1. `` `f` = `` + `$$…$$` + `diff` / `solve` / `plot` 金样例(中英库)。
2. 固定 `seed` 的随机金样例。
3. `plot` + `path` 在 CLI 落盘;view HTML 含 `<svg`。
4. `type` 对公式为 `formula`,对浮点为 `num`。
5. view Structure 将公式赋值显示为绑定,而非 comment。
---
## 10. 一句话
**`` `f` = `` + `$$…$$` 产出 `formula` 值;数学库对它做高中范围的符号运算、求解与作图——数值与随机并行,图在 view 内嵌、在 CLI 写文件。**
+5 -4
View File
@@ -2,10 +2,11 @@
| | |
|---|---|
| 状态 | **本波已落地(M1–M5)**;HTTPS 与带 `/` 的裸路径字面量仍受限 |
| 状态 | **五库已落地**;下一波:**数学库**([stdlib-math.md](stdlib-math.md));外联仍暂缓 |
| 日期 | 2026-08-05 |
| 本波范围 | **仅前五个库**:文件 / 系统 / 时间 / JSON / 网络 |
| 暂缓 | 数学、外联(重型;详稿保留、不排期)— [stdlib-math.md](stdlib-math.md) · [stdlib-foreign.md](stdlib-foreign.md) |
| 本波范围 | 文件 / 系统 / 时间 / JSON / 网络(已完成) |
| 下一波 | **数学**(数值+随机+作图+轻量求解) |
| 暂缓 | 外联 — [stdlib-foreign.md](stdlib-foreign.md) |
| 原则 | 全部经 frontmatter **导入**;除 JSON 外中英分文件;内核保持少而精 |
| 相关 | [stdlib.md](stdlib.md) · [stdlib-i18n.md](stdlib-i18n.md) · [keywords-i18n.md](keywords-i18n.md) · [view.md](view.md) |
@@ -24,7 +25,7 @@
| **时间** | `lib/time.mq.md` | `lib/时间.mq.md` | **做** |
| **JSON** | `lib/json.mq.md` | **同文件(特例,§3.4)** | **做** |
| **网络(简)** | `lib/net.mq.md` | `lib/网络.mq.md` | **做** |
| 数学 | `lib/math.mq.md` | `lib/数学.mq.md` | **暂缓** |
| 数学 | `lib/math.mq.md` | `lib/数学.mq.md` | **下一波** |
| 外联 | `lib/foreign.mq.md` | `lib/外联.mq.md` | **暂缓** |
---
+200
View File
@@ -0,0 +1,200 @@
---
title: lib/math
description: High-school math — num, random, formula, plot
---
# pi
**> host_pi**
# e
**> host_e**
# num
- value
**> host_num value=`value`**
# add
- a
- b
**> host_math_add a=`a` b=`b`**
# sub
- a
- b
**> host_math_sub a=`a` b=`b`**
# mul
- a
- b
**> host_math_mul a=`a` b=`b`**
# div
- a
- b
**> host_math_div a=`a` b=`b`**
# pow
- a
- b
**> host_math_pow a=`a` b=`b`**
# neg
- value
**> host_math_neg value=`value`**
# sin
- value
**> host_math_sin value=`value`**
# cos
- value
**> host_math_cos value=`value`**
# tan
- value
**> host_math_tan value=`value`**
# asin
- value
**> host_math_asin value=`value`**
# acos
- value
**> host_math_acos value=`value`**
# atan
- value
**> host_math_atan value=`value`**
# sqrt
- value
**> host_math_sqrt value=`value`**
# abs
- value
**> host_math_abs value=`value`**
# ln
- value
**> host_math_ln value=`value`**
# exp
- value
**> host_math_exp value=`value`**
# floor
- value
**> host_math_floor value=`value`**
# ceil
- value
**> host_math_ceil value=`value`**
# min
- a
- b
**> host_math_min a=`a` b=`b`**
# max
- a
- b
**> host_math_max a=`a` b=`b`**
# random
**> host_random**
# random_int
- min
- max
**> host_random_int min=`min` max=`max`**
# seed
- value
**> host_seed value=`value`**
# formula
- text
**> host_formula value=`text`**
# simplify
- formula
**> host_simplify value=`formula`**
# expand
- formula
**> host_expand value=`formula`**
# diff
- formula
- var
**> host_diff formula=`formula` var=`var`**
# subs
- formula
- var
- value
**> host_subs formula=`formula` var=`var` value=`value`**
# eval
- formula
- var
- value
**> host_eval formula=`formula` var=`var` value=`value`**
# solve
- formula
- var
**> host_solve formula=`formula` var=`var`**
# plot
- formula
- var
- min
- max
**> host_plot formula=`formula` var=`var` min=`min` max=`max`**
# plot_points
- xs
- ys
**> host_plot_points xs=`xs` ys=`ys`**
# plot_conic
- kind
- a
**> host_plot_conic kind=`kind` a=`a`**
+200
View File
@@ -0,0 +1,200 @@
---
title: lib/数学
description: 高中数学 — 数值、随机、公式、作图
---
# 圆周率
**> host_pi**
# 自然底数
**> host_e**
# 数
- value
**> host_num value=`value`**
# 加
- a
- b
**> host_math_add a=`a` b=`b`**
# 减
- a
- b
**> host_math_sub a=`a` b=`b`**
# 乘
- a
- b
**> host_math_mul a=`a` b=`b`**
# 除
- a
- b
**> host_math_div a=`a` b=`b`**
# 幂
- a
- b
**> host_math_pow a=`a` b=`b`**
# 负
- value
**> host_math_neg value=`value`**
# 正弦
- value
**> host_math_sin value=`value`**
# 余弦
- value
**> host_math_cos value=`value`**
# 正切
- value
**> host_math_tan value=`value`**
# 反正弦
- value
**> host_math_asin value=`value`**
# 反余弦
- value
**> host_math_acos value=`value`**
# 反正切
- value
**> host_math_atan value=`value`**
# 平方根
- value
**> host_math_sqrt value=`value`**
# 绝对值
- value
**> host_math_abs value=`value`**
# 对数
- value
**> host_math_ln value=`value`**
# 指数
- value
**> host_math_exp value=`value`**
# 向下取整
- value
**> host_math_floor value=`value`**
# 向上取整
- value
**> host_math_ceil value=`value`**
# 最小
- a
- b
**> host_math_min a=`a` b=`b`**
# 最大
- a
- b
**> host_math_max a=`a` b=`b`**
# 随机
**> host_random**
# 随机整数
- min
- max
**> host_random_int min=`min` max=`max`**
# 设种子
- value
**> host_seed value=`value`**
# 公式
- text
**> host_formula value=`text`**
# 化简
- formula
**> host_simplify value=`formula`**
# 展开
- formula
**> host_expand value=`formula`**
# 求导
- formula
- var
**> host_diff formula=`formula` var=`var`**
# 代入
- formula
- var
- value
**> host_subs formula=`formula` var=`var` value=`value`**
# 求值
- formula
- var
- value
**> host_eval formula=`formula` var=`var` value=`value`**
# 求解
- formula
- var
**> host_solve formula=`formula` var=`var`**
# 绘图
- formula
- var
- min
- max
**> host_plot formula=`formula` var=`var` min=`min` max=`max`**
# 绘点列
- xs
- ys
**> host_plot_points xs=`xs` ys=`ys`**
# 绘圆锥
- kind
- a
**> host_plot_conic kind=`kind` a=`a`**
+1 -2
View File
@@ -9,9 +9,8 @@
| [`00-welcome.mq.md`](00-welcome.mq.md) / [`00-欢迎.mq.md`](00-欢迎.mq.md) | 首页(英 / 中) |
| [`structure/`](structure/) | 基本结构 |
| [`keywords/`](keywords/) | 关键字与 L0 内置 |
| [`stdlib/`](stdlib/) | **标准库**(导入方式 + text/表/文件/时间/系统/json/网络) |
| [`stdlib/`](stdlib/) | **标准库**(导入方式 + text/表/文件/时间/系统/json/网络/数学) |
| [`features/`](features/) | 特性迭代 |
| [`lib-import.mq.md`](lib-import.mq.md) / [`lib-导入.mq.md`](lib-导入.mq.md) | 快速导入示例(text) |
**不放** `errors/`:失败样例只在 `tests/errors/`。
-13
View File
@@ -1,13 +0,0 @@
---
title: Import official lib
description: Frontmatter `lib/…` or `std/…`
> lib/text.mq.md
---
# main
After importing `lib/text.mq.md`, call the English wrappers:
*`t` = > str_trim s= marqdo *
> print text=`t`
-13
View File
@@ -1,13 +0,0 @@
---
title: 导入官方库
description: frontmatter 使用 lib/… 或 std/…
> lib/文本.mq.md
---
# main
导入 `lib/文本.mq.md` 后可调用中文包装函数:
*`t` = > 去空白 s= marqdo *
> 打印 内容=`t`
+1 -1
View File
@@ -11,7 +11,7 @@ English-named files export English APIs; Chinese-named files export Chinese APIs
No extra allow flags: importing a module means you intend to use it. Under marqdo view or static export, exit soft-fails and long sleeps are clamped so the console stays up.
Modules: text (text / 文本), table (table / 表), files (fs / 文件), time (time / 时间), system (sys / 系统), json (json only), net (net / 网络).
Modules: text (text / 文本), table (table / 表), files (fs / 文件), time (time / 时间), system (sys / 系统), json (json only), net (net / 网络), math (math / 数学).
Sibling pages in this folder document each module. Chinese overview: 00-索引.mq.md.
+1 -1
View File
@@ -11,7 +11,7 @@ description: 如何导入官方 lib 模块
导入即表示要用对应能力,无需再加允许旗标。marqdo view 或静态导出里,退出会软失败、长睡眠会被钳制,以免拖垮控制台。
模块:文本(text / 文本)、表(table / 表)、文件(fs / 文件)、时间(time / 时间)、系统(sys / 系统)、json(仅 json)、网络(net / 网络)。
模块:文本(text / 文本)、表(table / 表)、文件(fs / 文件)、时间(time / 时间)、系统(sys / 系统)、json(仅 json)、网络(net / 网络)、数学(math / 数学)。
各模块说明见本目录其它页。English: 00-overview.mq.md.
+38
View File
@@ -0,0 +1,38 @@
---
title: lib/math — numbers, formulas, plots
description: High-school math stdlib (English)
> lib/math.mq.md
---
# main
Import lib/math.mq.md. Runtime types: num (float) and formula (symbolic tree). Bind a formula with an empty-RHS assign followed by a `$$…$$` fence (same shape as table assigns). In view, Structure renders that fence with KaTeX.
`f` =
$$
x^2 - 2
$$
Numeric helpers: pi, e, num, add/sub/mul/div/pow, sin/cos/tan, sqrt/abs/ln/exp, floor/ceil, min/max. Random: seed, random, random_int (reproducible after seed).
Symbolic: formula(text), simplify, expand, diff, subs, eval, solve.
Plotting (already in the library): plot / plot_points / plot_conic return SVG text. Axes include arrows and tick labels; **grid is on by default** (pass grid=False / grid=假 to hide). Optional path= writes a file under the sandbox. With no path, CLI auto-writes stem-plot-n.svg and prints plot: …; view embeds the SVG under Execution.
diff / simplify / expand / partial subs return formula values so you can chain (e.g. differentiate twice, then plot or eval).
*`ty` = > type `f` *
> print text=`ty`
*`df` = > diff formula=`f` var=x *
> print text=`df`
*`roots` = > solve formula=`f` var=x *
> print text=`roots`
*`_svg` = > plot formula=`f` var=x min=-3 max=3 *
> print text=plot-ok
+38
View File
@@ -0,0 +1,38 @@
---
title: lib/数学 — 数值、公式、作图
description: 高中数学标准库(中文)
> lib/数学.mq.md
---
# main
导入 lib/数学.mq.md。运行时类型:num(浮点)与 formula(符号树)。用空 RHS 赋值后跟 `$$…$$` 围栏绑定公式(与表格赋值同构)。view 的 Structure 会用 KaTeX 渲染该公式。
`f` =
$$
x^2 - 2
$$
数值:圆周率、自然底数、数、加/减/乘/除/幂、正弦/余弦/正切、平方根/绝对值/对数/指数、向下取整/向上取整、最小/最大。随机:设种子、随机、随机整数。
符号:公式、化简、展开、求导、代入、求值、求解。
作图(库已提供):绘图 / 绘点列 / 绘圆锥,返回 SVG 文本。坐标轴带箭头与刻度;**默认显示网格**(`grid=假` 可关闭)。可选 path= 写盘。无 path 时 CLI 自动写 stem-plot-n.svg 并打印 plot: …;view 在 Execution 内嵌 SVG。
求导 / 化简 / 展开 / 未完全数值化的代入仍返回 formula,可继续链式调用(例如求二阶导后再绘图或求值)。
*`ty` = > type `f` *
> print text=`ty`
*`df` = > 求导 formula=`f` var=x *
> print text=`df`
*`roots` = > 求解 formula=`f` var=x *
> print text=`roots`
*`_svg` = > 绘图 formula=`f` var=x min=-3 max=3 *
> print text=plot-ok
+9
View File
@@ -51,6 +51,15 @@ pub fn canonical_param(builtin: &str, param: &str) -> String {
("split" | "join", "sep" | "分隔") => "sep".into(),
("at", "value" | "值") => "value".into(),
("at", "index" | "下标") => "index".into(),
(
"host_plot" | "host_plot_points" | "host_plot_conic",
"grid" | "网格",
) => "grid".into(),
("host_plot" | "host_plot_points" | "host_plot_conic", "path" | "路径") => {
"path".into()
}
("host_plot", "steps" | "步数") => "steps".into(),
("host_plot", "derivative" | "导数") => "derivative".into(),
_ => param.to_string(),
}
}
+14 -2
View File
@@ -1,6 +1,7 @@
//! Marqdo AST (Phase I).
use crate::diagnostics::Span;
use crate::formula::Expr as FormulaExpr;
#[derive(Debug, Clone)]
pub struct Module {
@@ -24,6 +25,8 @@ pub enum Stmt {
name: String,
value: Expr,
span: Span,
/// Inclusive last source line (covers following `$$` fence or table rows).
end_line: u32,
},
Return {
value: Expr,
@@ -86,6 +89,8 @@ pub enum Expr {
},
Call(CallExpr),
List(Vec<Expr>),
/// Parsed `$$…$$` formula tree (from assignment RHS).
Formula(FormulaExpr),
}
#[derive(Debug, Clone)]
@@ -156,8 +161,15 @@ fn dump_fun(out: &mut String, fun: &Function, depth: usize) {
fn dump_stmt(out: &mut String, stmt: &Stmt, depth: usize) {
let pad = " ".repeat(depth);
match stmt {
Stmt::Assign { name, value, span } => {
out.push_str(&format!("{pad}(assign {name:?} {value:?} @{span})\n"));
Stmt::Assign {
name,
value,
span,
end_line,
} => {
out.push_str(&format!(
"{pad}(assign {name:?} {value:?} @{span}..{end_line})\n"
));
}
Stmt::Return { value, span } => {
out.push_str(&format!("{pad}(return {value:?} @{span})\n"));
+5 -2
View File
@@ -20,6 +20,7 @@ pub fn builtin_str(v: &Value) -> Value {
pub fn builtin_int(v: &Value) -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
Value::Num(n) => Ok(*n as i64),
Value::Bool(true) => Ok(1),
Value::Bool(false) => Ok(0),
Value::Text(s) => {
@@ -27,20 +28,22 @@ pub fn builtin_int(v: &Value) -> Result<i64, String> {
t.parse::<i64>()
.map_err(|_| format!("cannot convert to int: {s:?}"))
}
_ => Err("int needs int, bool, or text".into()),
_ => Err("int needs int, num, bool, or text".into()),
}
}
/// `type`: type tag as text (`none` / `bool` / `int` / `text` / `list` / `map`).
/// `type`: type tag as text (`none` / `bool` / `int` / `num` / `text` / `list` / `map` / `formula`).
pub fn builtin_type(v: &Value) -> Value {
Value::Text(
match v {
Value::None => "none",
Value::Bool(_) => "bool",
Value::Int(_) => "int",
Value::Num(_) => "num",
Value::Text(_) => "text",
Value::List(_) => "list",
Value::Map(_) => "map",
Value::Formula(_) => "formula",
}
.into(),
)
+5 -1
View File
@@ -206,7 +206,7 @@ impl<'a> FnCompiler<'a> {
fn compile_stmt(&mut self, stmt: &Stmt) -> Result<()> {
match stmt {
Stmt::Assign { name, value, span } => {
Stmt::Assign { name, value, span, .. } => {
self.stmt_span = *span;
self.compile_expr(value)?;
let slot = self.local_slot(name);
@@ -637,6 +637,10 @@ impl<'a> FnCompiler<'a> {
}
self.emit(Op::BuildList(items.len() as u16));
}
Expr::Formula(e) => {
let i = self.add_const(Value::Formula(e.clone()));
self.emit(Op::Constant(i));
}
}
Ok(())
}
+13 -2
View File
@@ -69,6 +69,10 @@ impl Vm {
self
}
pub fn take_plots(&mut self) -> Vec<crate::host::PlotArtifact> {
std::mem::take(&mut self.host.plots)
}
fn emit_line(&mut self, text: &str) {
if self.capture {
self.captured_stdout.push_str(text);
@@ -312,7 +316,7 @@ impl Vm {
}
}
let result =
call_host(&self.host, hf, &bound).map_err(|m| self.err_at(span, m))?;
call_host(&mut self.host, hf, &bound).map_err(|m| self.err_at(span, m))?;
stack.push(result);
}
Op::Call(fid, argc) => {
@@ -380,8 +384,15 @@ fn cmp(stack: &mut Vec<Value>, pred: impl Fn(std::cmp::Ordering) -> bool) -> Res
let a = pop(stack)?;
let ord = match (&a, &b) {
(Value::Int(x), Value::Int(y)) => x.cmp(y),
(Value::Num(x), Value::Num(y)) => x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal),
(Value::Int(x), Value::Num(y)) => {
(*x as f64).partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)
}
(Value::Num(x), Value::Int(y)) => {
x.partial_cmp(&(*y as f64)).unwrap_or(std::cmp::Ordering::Equal)
}
(Value::Text(x), Value::Text(y)) => x.cmp(y),
_ => return Err("comparison needs two ints or two texts".into()),
_ => return Err("comparison needs two ints/nums or two texts".into()),
};
stack.push(Value::Bool(pred(ord)));
Ok(())
+2
View File
@@ -1,9 +1,11 @@
//! Captured program run (for tests and `view`).
use crate::value::Value;
use crate::host::PlotArtifact;
#[derive(Debug, Clone)]
pub struct RunCapture {
pub stdout: String,
pub value: Value,
pub plots: Vec<PlotArtifact>,
}
+961
View File
@@ -0,0 +1,961 @@
//! High-school formula AST: parse, simplify, diff, eval, solve, plot helpers.
mod plot;
pub use plot::{plot_conic_svg, plot_function_svg, plot_points_svg, PlotStyle};
use std::collections::HashMap;
use std::fmt;
/// Expression tree for `Value::Formula`.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
Num(f64),
Var(String),
UnaryNeg(Box<Expr>),
Bin {
op: BinOp,
left: Box<Expr>,
right: Box<Expr>,
},
Call {
name: String,
args: Vec<Expr>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
Pow,
}
impl Expr {
pub fn num(n: f64) -> Self {
Expr::Num(n)
}
pub fn var(name: impl Into<String>) -> Self {
Expr::Var(name.into())
}
pub fn as_display(&self) -> String {
self.fmt_prec(0)
}
fn fmt_prec(&self, parent_prec: u8) -> String {
match self {
Expr::Num(n) => format_num(*n),
Expr::Var(v) => v.clone(),
Expr::UnaryNeg(e) => {
let inner = e.fmt_prec(3);
let s = format!("-{inner}");
if parent_prec > 2 {
format!("({s})")
} else {
s
}
}
Expr::Bin { op, left, right } => {
let prec = op.prec();
let ls = left.fmt_prec(prec);
let rs = right.fmt_prec(if matches!(op, BinOp::Sub | BinOp::Div) {
prec + 1
} else if matches!(op, BinOp::Pow) {
prec
} else {
prec
});
let s = format!("{ls}{}{rs}", op.sym());
if prec < parent_prec {
format!("({s})")
} else {
s
}
}
Expr::Call { name, args } => {
let joined: Vec<String> = args.iter().map(|a| a.as_display()).collect();
format!("{name}({})", joined.join(", "))
}
}
}
}
impl fmt::Display for Expr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_display())
}
}
impl BinOp {
fn prec(self) -> u8 {
match self {
BinOp::Add | BinOp::Sub => 1,
BinOp::Mul | BinOp::Div => 2,
BinOp::Pow => 3,
}
}
fn sym(self) -> &'static str {
match self {
BinOp::Add => " + ",
BinOp::Sub => " - ",
BinOp::Mul => "*",
BinOp::Div => "/",
BinOp::Pow => "^",
}
}
}
pub fn format_num(n: f64) -> String {
if n.is_nan() {
return "nan".into();
}
if n.is_infinite() {
return if n.is_sign_positive() {
"inf".into()
} else {
"-inf".into()
};
}
if n.fract() == 0.0 && n.abs() < 1e15 {
return format!("{}", n as i64);
}
let s = format!("{n:.10}");
let s = s.trim_end_matches('0').trim_end_matches('.');
if s.is_empty() || s == "-" {
"0".into()
} else {
s.to_string()
}
}
/// Parse ASCII formula text (`sin(x) + x^2`, optional simple `y = …` left strip).
pub fn parse(input: &str) -> Result<Expr, String> {
let t = input.trim();
if t.is_empty() {
return Err("empty formula".into());
}
let body = if let Some((lhs, rhs)) = t.split_once('=') {
let lhs = lhs.trim();
if lhs.chars().all(|c| c.is_ascii_alphabetic() || c == '_') && !rhs.trim().is_empty() {
rhs.trim()
} else {
t
}
} else {
t
};
let mut p = Parser {
src: body.chars().collect(),
i: 0,
};
let e = p.parse_expr()?;
p.skip_ws();
if p.i < p.src.len() {
return Err(format!(
"unexpected trailing input near `{}`",
p.src[p.i..].iter().collect::<String>()
));
}
Ok(e)
}
struct Parser {
src: Vec<char>,
i: usize,
}
impl Parser {
fn skip_ws(&mut self) {
while self.i < self.src.len() && self.src[self.i].is_whitespace() {
self.i += 1;
}
}
fn peek(&mut self) -> Option<char> {
self.skip_ws();
self.src.get(self.i).copied()
}
fn bump(&mut self) -> Option<char> {
self.skip_ws();
let c = self.src.get(self.i).copied()?;
self.i += 1;
Some(c)
}
fn parse_expr(&mut self) -> Result<Expr, String> {
self.parse_add()
}
fn parse_add(&mut self) -> Result<Expr, String> {
let mut left = self.parse_mul()?;
loop {
match self.peek() {
Some('+') => {
self.bump();
let right = self.parse_mul()?;
left = Expr::Bin {
op: BinOp::Add,
left: Box::new(left),
right: Box::new(right),
};
}
Some('-') => {
self.bump();
let right = self.parse_mul()?;
left = Expr::Bin {
op: BinOp::Sub,
left: Box::new(left),
right: Box::new(right),
};
}
_ => break,
}
}
Ok(left)
}
fn parse_mul(&mut self) -> Result<Expr, String> {
let mut left = self.parse_pow()?;
loop {
match self.peek() {
Some('*') => {
self.bump();
let right = self.parse_pow()?;
left = Expr::Bin {
op: BinOp::Mul,
left: Box::new(left),
right: Box::new(right),
};
}
Some('/') => {
self.bump();
let right = self.parse_pow()?;
left = Expr::Bin {
op: BinOp::Div,
left: Box::new(left),
right: Box::new(right),
};
}
_ => break,
}
}
Ok(left)
}
fn parse_pow(&mut self) -> Result<Expr, String> {
let left = self.parse_unary()?;
if self.peek() == Some('^') {
self.bump();
let right = self.parse_pow()?; // right-assoc
Ok(Expr::Bin {
op: BinOp::Pow,
left: Box::new(left),
right: Box::new(right),
})
} else {
Ok(left)
}
}
fn parse_unary(&mut self) -> Result<Expr, String> {
match self.peek() {
Some('+') => {
self.bump();
self.parse_unary()
}
Some('-') => {
self.bump();
Ok(Expr::UnaryNeg(Box::new(self.parse_unary()?)))
}
_ => self.parse_primary(),
}
}
fn parse_primary(&mut self) -> Result<Expr, String> {
match self.peek() {
Some('(') => {
self.bump();
let e = self.parse_expr()?;
if self.bump() != Some(')') {
return Err("expected `)`".into());
}
Ok(e)
}
Some(c) if c.is_ascii_digit() || c == '.' => self.parse_number(),
Some(c) if c.is_ascii_alphabetic() || c == '_' => {
let name = self.parse_ident()?;
if self.peek() == Some('(') {
self.bump();
let mut args = Vec::new();
if self.peek() != Some(')') {
loop {
args.push(self.parse_expr()?);
match self.peek() {
Some(',') => {
self.bump();
}
Some(')') => break,
_ => return Err("expected `,` or `)` in call".into()),
}
}
}
if self.bump() != Some(')') {
return Err("expected `)` after call args".into());
}
Ok(Expr::Call { name, args })
} else {
Ok(Expr::Var(name))
}
}
Some(c) => Err(format!("unexpected `{c}` in formula")),
None => Err("unexpected end of formula".into()),
}
}
fn parse_number(&mut self) -> Result<Expr, String> {
self.skip_ws();
let start = self.i;
while self.i < self.src.len()
&& (self.src[self.i].is_ascii_digit() || self.src[self.i] == '.')
{
self.i += 1;
}
let s: String = self.src[start..self.i].iter().collect();
let n: f64 = s
.parse()
.map_err(|_| format!("invalid number `{s}`"))?;
Ok(Expr::Num(n))
}
fn parse_ident(&mut self) -> Result<String, String> {
self.skip_ws();
let start = self.i;
while self.i < self.src.len() {
let c = self.src[self.i];
if c.is_ascii_alphanumeric() || c == '_' {
self.i += 1;
} else {
break;
}
}
if start == self.i {
return Err("expected identifier".into());
}
Ok(self.src[start..self.i].iter().collect())
}
}
/// Constant-fold + light algebraic cleanup.
pub fn simplify(e: &Expr) -> Expr {
match e {
Expr::Num(n) => Expr::Num(*n),
Expr::Var(v) => Expr::Var(v.clone()),
Expr::UnaryNeg(inner) => {
let i = simplify(inner);
match i {
Expr::Num(n) => Expr::Num(-n),
Expr::UnaryNeg(x) => *x,
other => Expr::UnaryNeg(Box::new(other)),
}
}
Expr::Bin { op, left, right } => {
let l = simplify(left);
let r = simplify(right);
fold_bin(*op, l, r)
}
Expr::Call { name, args } => {
let args: Vec<Expr> = args.iter().map(simplify).collect();
if args.len() == 1 {
if let Expr::Num(n) = &args[0] {
if let Some(v) = eval_call_f64(name, &[*n]) {
return Expr::Num(v);
}
}
}
Expr::Call {
name: name.clone(),
args,
}
}
}
}
fn fold_bin(op: BinOp, l: Expr, r: Expr) -> Expr {
match (op, &l, &r) {
(BinOp::Add, Expr::Num(a), Expr::Num(b)) => Expr::Num(a + b),
(BinOp::Sub, Expr::Num(a), Expr::Num(b)) => Expr::Num(a - b),
(BinOp::Mul, Expr::Num(a), Expr::Num(b)) => Expr::Num(a * b),
(BinOp::Div, Expr::Num(a), Expr::Num(b)) if *b != 0.0 => Expr::Num(a / b),
(BinOp::Pow, Expr::Num(a), Expr::Num(b)) => Expr::Num(a.powf(*b)),
(BinOp::Add, _, Expr::Num(0.0)) => l,
(BinOp::Add, Expr::Num(0.0), _) => r,
(BinOp::Sub, _, Expr::Num(0.0)) => l,
(BinOp::Mul, _, Expr::Num(1.0)) => l,
(BinOp::Mul, Expr::Num(1.0), _) => r,
(BinOp::Mul, _, Expr::Num(0.0)) | (BinOp::Mul, Expr::Num(0.0), _) => Expr::Num(0.0),
(BinOp::Pow, _, Expr::Num(1.0)) => l,
(BinOp::Pow, _, Expr::Num(0.0)) => Expr::Num(1.0),
(BinOp::Div, _, Expr::Num(1.0)) => l,
_ => Expr::Bin {
op,
left: Box::new(l),
right: Box::new(r),
},
}
}
/// Lightweight expand: distribute multiplication over addition one level.
pub fn expand(e: &Expr) -> Expr {
let e = simplify(e);
match e {
Expr::Bin {
op: BinOp::Mul,
left,
right,
} => {
let l = expand(&left);
let r = expand(&right);
match (l, r) {
(
Expr::Bin {
op: BinOp::Add,
left: a,
right: b,
},
r,
) => simplify(&Expr::Bin {
op: BinOp::Add,
left: Box::new(Expr::Bin {
op: BinOp::Mul,
left: a,
right: Box::new(r.clone()),
}),
right: Box::new(Expr::Bin {
op: BinOp::Mul,
left: b,
right: Box::new(r),
}),
}),
(
l,
Expr::Bin {
op: BinOp::Add,
left: a,
right: b,
},
) => simplify(&Expr::Bin {
op: BinOp::Add,
left: Box::new(Expr::Bin {
op: BinOp::Mul,
left: Box::new(l.clone()),
right: a,
}),
right: Box::new(Expr::Bin {
op: BinOp::Mul,
left: Box::new(l),
right: b,
}),
}),
(l, r) => simplify(&Expr::Bin {
op: BinOp::Mul,
left: Box::new(l),
right: Box::new(r),
}),
}
}
Expr::Bin { op, left, right } => simplify(&Expr::Bin {
op,
left: Box::new(expand(&left)),
right: Box::new(expand(&right)),
}),
Expr::UnaryNeg(x) => simplify(&Expr::UnaryNeg(Box::new(expand(&x)))),
Expr::Call { name, args } => Expr::Call {
name,
args: args.iter().map(expand).collect(),
},
other => other,
}
}
pub fn diff(e: &Expr, var: &str) -> Expr {
simplify(&diff_raw(e, var))
}
fn diff_raw(e: &Expr, var: &str) -> Expr {
match e {
Expr::Num(_) => Expr::Num(0.0),
Expr::Var(v) => {
if v == var {
Expr::Num(1.0)
} else {
Expr::Num(0.0)
}
}
Expr::UnaryNeg(x) => Expr::UnaryNeg(Box::new(diff_raw(x, var))),
Expr::Bin {
op: BinOp::Add,
left,
right,
} => Expr::Bin {
op: BinOp::Add,
left: Box::new(diff_raw(left, var)),
right: Box::new(diff_raw(right, var)),
},
Expr::Bin {
op: BinOp::Sub,
left,
right,
} => Expr::Bin {
op: BinOp::Sub,
left: Box::new(diff_raw(left, var)),
right: Box::new(diff_raw(right, var)),
},
Expr::Bin {
op: BinOp::Mul,
left,
right,
} => {
// product rule
Expr::Bin {
op: BinOp::Add,
left: Box::new(Expr::Bin {
op: BinOp::Mul,
left: Box::new(diff_raw(left, var)),
right: right.clone(),
}),
right: Box::new(Expr::Bin {
op: BinOp::Mul,
left: left.clone(),
right: Box::new(diff_raw(right, var)),
}),
}
}
Expr::Bin {
op: BinOp::Div,
left,
right,
} => {
// (u'v - uv') / v^2
let num = Expr::Bin {
op: BinOp::Sub,
left: Box::new(Expr::Bin {
op: BinOp::Mul,
left: Box::new(diff_raw(left, var)),
right: right.clone(),
}),
right: Box::new(Expr::Bin {
op: BinOp::Mul,
left: left.clone(),
right: Box::new(diff_raw(right, var)),
}),
};
Expr::Bin {
op: BinOp::Div,
left: Box::new(num),
right: Box::new(Expr::Bin {
op: BinOp::Pow,
left: right.clone(),
right: Box::new(Expr::Num(2.0)),
}),
}
}
Expr::Bin {
op: BinOp::Pow,
left,
right,
} => {
// d/dx [u^n] when n constant: n*u^(n-1)*u'
if let Expr::Num(n) = right.as_ref() {
Expr::Bin {
op: BinOp::Mul,
left: Box::new(Expr::Bin {
op: BinOp::Mul,
left: Box::new(Expr::Num(*n)),
right: Box::new(Expr::Bin {
op: BinOp::Pow,
left: left.clone(),
right: Box::new(Expr::Num(n - 1.0)),
}),
}),
right: Box::new(diff_raw(left, var)),
}
} else {
// a^u → a^u * ln(a) * u' when a constant
if let Expr::Num(a) = left.as_ref() {
Expr::Bin {
op: BinOp::Mul,
left: Box::new(Expr::Bin {
op: BinOp::Mul,
left: Box::new(e.clone()),
right: Box::new(Expr::Call {
name: "ln".into(),
args: vec![Expr::Num(*a)],
}),
}),
right: Box::new(diff_raw(right, var)),
}
} else {
// fallback: treat as exp(v*ln(u))
Expr::Num(0.0)
}
}
}
Expr::Call { name, args } => {
if args.len() != 1 {
return Expr::Num(0.0);
}
let u = &args[0];
let du = diff_raw(u, var);
let chain = |outer: Expr| {
Expr::Bin {
op: BinOp::Mul,
left: Box::new(outer),
right: Box::new(du.clone()),
}
};
match name.as_str() {
"sin" => chain(Expr::Call {
name: "cos".into(),
args: vec![u.clone()],
}),
"cos" => chain(Expr::UnaryNeg(Box::new(Expr::Call {
name: "sin".into(),
args: vec![u.clone()],
}))),
"tan" => chain(Expr::Bin {
op: BinOp::Pow,
left: Box::new(Expr::Call {
name: "cos".into(),
args: vec![u.clone()],
}),
right: Box::new(Expr::Num(-2.0)),
}),
"sqrt" => chain(Expr::Bin {
op: BinOp::Div,
left: Box::new(Expr::Num(1.0)),
right: Box::new(Expr::Bin {
op: BinOp::Mul,
left: Box::new(Expr::Num(2.0)),
right: Box::new(Expr::Call {
name: "sqrt".into(),
args: vec![u.clone()],
}),
}),
}),
"ln" | "log" => chain(Expr::Bin {
op: BinOp::Div,
left: Box::new(Expr::Num(1.0)),
right: Box::new(u.clone()),
}),
"exp" => chain(Expr::Call {
name: "exp".into(),
args: vec![u.clone()],
}),
"abs" => {
// sign(u)*u' — use u/abs(u) when u≠0
chain(Expr::Bin {
op: BinOp::Div,
left: Box::new(u.clone()),
right: Box::new(Expr::Call {
name: "abs".into(),
args: vec![u.clone()],
}),
})
}
_ => Expr::Num(0.0),
}
}
}
}
pub fn subs(e: &Expr, var: &str, value: &Expr) -> Expr {
simplify(&subs_raw(e, var, value))
}
fn subs_raw(e: &Expr, var: &str, value: &Expr) -> Expr {
match e {
Expr::Num(n) => Expr::Num(*n),
Expr::Var(v) => {
if v == var {
value.clone()
} else {
Expr::Var(v.clone())
}
}
Expr::UnaryNeg(x) => Expr::UnaryNeg(Box::new(subs_raw(x, var, value))),
Expr::Bin { op, left, right } => Expr::Bin {
op: *op,
left: Box::new(subs_raw(left, var, value)),
right: Box::new(subs_raw(right, var, value)),
},
Expr::Call { name, args } => Expr::Call {
name: name.clone(),
args: args.iter().map(|a| subs_raw(a, var, value)).collect(),
},
}
}
pub fn eval_f64(e: &Expr, env: &HashMap<String, f64>) -> Result<f64, String> {
match e {
Expr::Num(n) => Ok(*n),
Expr::Var(v) => env
.get(v)
.copied()
.ok_or_else(|| format!("unbound variable `{v}`")),
Expr::UnaryNeg(x) => Ok(-eval_f64(x, env)?),
Expr::Bin { op, left, right } => {
let a = eval_f64(left, env)?;
let b = eval_f64(right, env)?;
Ok(match op {
BinOp::Add => a + b,
BinOp::Sub => a - b,
BinOp::Mul => a * b,
BinOp::Div => {
if b == 0.0 {
return Err("division by zero".into());
}
a / b
}
BinOp::Pow => a.powf(b),
})
}
Expr::Call { name, args } => {
let mut xs = Vec::with_capacity(args.len());
for a in args {
xs.push(eval_f64(a, env)?);
}
eval_call_f64(name, &xs).ok_or_else(|| format!("unknown or arity-mismatch function `{name}`"))
}
}
}
fn eval_call_f64(name: &str, args: &[f64]) -> Option<f64> {
match (name, args) {
("sin", [x]) => Some(x.sin()),
("cos", [x]) => Some(x.cos()),
("tan", [x]) => Some(x.tan()),
("asin", [x]) => Some(x.asin()),
("acos", [x]) => Some(x.acos()),
("atan", [x]) => Some(x.atan()),
("sqrt", [x]) => Some(x.sqrt()),
("abs", [x]) => Some(x.abs()),
("ln" | "log", [x]) => Some(x.ln()),
("exp", [x]) => Some(x.exp()),
("floor", [x]) => Some(x.floor()),
("ceil", [x]) => Some(x.ceil()),
("pow", [a, b]) => Some(a.powf(*b)),
("min", [a, b]) => Some(a.min(*b)),
("max", [a, b]) => Some(a.max(*b)),
_ => None,
}
}
/// Solve `e = 0` for `var`. Quadratic/linear closed form; else numeric scan.
pub fn solve(e: &Expr, var: &str, xmin: f64, xmax: f64) -> Result<Vec<f64>, String> {
let e = expand(&simplify(e));
if let Some(roots) = try_polynomial_solve(&e, var) {
return Ok(roots);
}
numeric_roots(&e, var, xmin, xmax)
}
fn try_polynomial_solve(e: &Expr, var: &str) -> Option<Vec<f64>> {
let (a, b, c) = poly_coeffs_quadratic(e, var)?;
if a.abs() < 1e-12 {
if b.abs() < 1e-12 {
return if c.abs() < 1e-12 {
None // identity
} else {
Some(vec![])
};
}
return Some(vec![-c / b]);
}
let disc = b * b - 4.0 * a * c;
if disc < -1e-12 {
return Some(vec![]);
}
if disc.abs() <= 1e-12 {
return Some(vec![-b / (2.0 * a)]);
}
let s = disc.sqrt();
let mut roots = vec![(-b - s) / (2.0 * a), (-b + s) / (2.0 * a)];
roots.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal));
Some(roots)
}
/// Collect ax^2+bx+c if expression is a polynomial of degree ≤ 2 in `var`.
fn poly_coeffs_quadratic(e: &Expr, var: &str) -> Option<(f64, f64, f64)> {
let mut a = 0.0;
let mut b = 0.0;
let mut c = 0.0;
if !accum_poly(e, var, 1.0, &mut a, &mut b, &mut c) {
return None;
}
Some((a, b, c))
}
fn accum_poly(e: &Expr, var: &str, scale: f64, a: &mut f64, b: &mut f64, c: &mut f64) -> bool {
match e {
Expr::Num(n) => {
*c += scale * n;
true
}
Expr::Var(v) if v == var => {
*b += scale;
true
}
Expr::Var(_) => false,
Expr::UnaryNeg(x) => accum_poly(x, var, -scale, a, b, c),
Expr::Bin {
op: BinOp::Add,
left,
right,
} => accum_poly(left, var, scale, a, b, c) && accum_poly(right, var, scale, a, b, c),
Expr::Bin {
op: BinOp::Sub,
left,
right,
} => accum_poly(left, var, scale, a, b, c) && accum_poly(right, var, -scale, a, b, c),
Expr::Bin {
op: BinOp::Mul,
left,
right,
} => match (left.as_ref(), right.as_ref()) {
(Expr::Num(n), r) => accum_poly(r, var, scale * n, a, b, c),
(l, Expr::Num(n)) => accum_poly(l, var, scale * n, a, b, c),
(Expr::Var(v), Expr::Var(w)) if v == var && w == var => {
*a += scale;
true
}
(
Expr::Bin {
op: BinOp::Pow,
left: base,
right: exp,
},
other,
)
| (
other,
Expr::Bin {
op: BinOp::Pow,
left: base,
right: exp,
},
) => {
if let (Expr::Var(v), Expr::Num(2.0)) = (base.as_ref(), exp.as_ref()) {
if v == var {
if let Expr::Num(n) = other {
*a += scale * n;
return true;
}
}
}
false
}
_ => false,
},
Expr::Bin {
op: BinOp::Pow,
left,
right,
} => match (left.as_ref(), right.as_ref()) {
(Expr::Var(v), Expr::Num(2.0)) if v == var => {
*a += scale;
true
}
(Expr::Var(v), Expr::Num(1.0)) if v == var => {
*b += scale;
true
}
(Expr::Var(v), Expr::Num(0.0)) if v == var => {
*c += scale;
true
}
_ => false,
},
_ => false,
}
}
fn numeric_roots(e: &Expr, var: &str, xmin: f64, xmax: f64) -> Result<Vec<f64>, String> {
const STEPS: usize = 200;
let mut roots = Vec::new();
let mut env = HashMap::new();
let dx = (xmax - xmin) / STEPS as f64;
let mut x0 = xmin;
env.insert(var.to_string(), x0);
let mut y0 = eval_f64(e, &env)?;
for i in 1..=STEPS {
let x1 = xmin + dx * i as f64;
env.insert(var.to_string(), x1);
let y1 = eval_f64(e, &env)?;
if y0 == 0.0 {
push_unique(&mut roots, x0);
} else if y0.signum() != y1.signum() && y1 != 0.0 {
// bisection
let mut lo = x0;
let mut hi = x1;
let mut flo = y0;
for _ in 0..40 {
let mid = 0.5 * (lo + hi);
env.insert(var.to_string(), mid);
let fm = eval_f64(e, &env)?;
if fm == 0.0 || (hi - lo).abs() < 1e-10 {
push_unique(&mut roots, mid);
break;
}
if flo.signum() == fm.signum() {
lo = mid;
flo = fm;
} else {
hi = mid;
}
}
}
if i == STEPS && y1 == 0.0 {
push_unique(&mut roots, x1);
}
x0 = x1;
y0 = y1;
}
Ok(roots)
}
fn push_unique(xs: &mut Vec<f64>, x: f64) {
if xs.iter().any(|y| (y - x).abs() < 1e-6) {
return;
}
xs.push(x);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_and_diff_quadratic() {
let e = parse("x^2 - 2").unwrap();
let d = diff(&e, "x");
assert_eq!(d.as_display(), "2*x");
let roots = solve(&e, "x", -10.0, 10.0).unwrap();
assert_eq!(roots.len(), 2);
assert!((roots[0] + 2f64.sqrt()).abs() < 1e-6);
assert!((roots[1] - 2f64.sqrt()).abs() < 1e-6);
}
#[test]
fn eval_sin() {
let e = parse("sin(x)").unwrap();
let mut env = HashMap::new();
env.insert("x".into(), 0.0);
assert!((eval_f64(&e, &env).unwrap()).abs() < 1e-12);
}
}
+432
View File
@@ -0,0 +1,432 @@
//! SVG plot helpers for high-school graphs.
use std::collections::HashMap;
use super::{eval_f64, Expr};
const MAX_STEPS: usize = 2000;
const DEFAULT_STEPS: usize = 200;
const SVG_W: f64 = 520.0;
const SVG_H: f64 = 360.0;
const PAD: f64 = 36.0;
#[derive(Debug, Clone, Copy)]
pub struct PlotStyle {
pub grid: bool,
}
impl Default for PlotStyle {
fn default() -> Self {
Self { grid: true }
}
}
pub fn plot_function_svg(
expr: &Expr,
var: &str,
xmin: f64,
xmax: f64,
steps: usize,
style: PlotStyle,
) -> Result<String, String> {
if !(xmin.is_finite() && xmax.is_finite()) || xmax <= xmin {
return Err("plot needs finite min < max".into());
}
let steps = steps.clamp(2, MAX_STEPS);
let mut env = HashMap::new();
let mut pts: Vec<(f64, f64)> = Vec::with_capacity(steps + 1);
let mut ymin = f64::INFINITY;
let mut ymax = f64::NEG_INFINITY;
for i in 0..=steps {
let x = xmin + (xmax - xmin) * (i as f64) / (steps as f64);
env.insert(var.to_string(), x);
match eval_f64(expr, &env) {
Ok(y) if y.is_finite() => {
ymin = ymin.min(y);
ymax = ymax.max(y);
pts.push((x, y));
}
_ => {}
}
}
if pts.is_empty() {
return Err("plot produced no finite points".into());
}
if (ymax - ymin).abs() < 1e-12 {
ymin -= 1.0;
ymax += 1.0;
}
let pad_y = 0.05 * (ymax - ymin);
ymin -= pad_y;
ymax += pad_y;
let mut path = String::new();
for (i, (x, y)) in pts.iter().enumerate() {
let (sx, sy) = map_xy(*x, *y, xmin, xmax, ymin, ymax);
if i == 0 {
path.push_str(&format!("M {sx:.2} {sy:.2}"));
} else {
path.push_str(&format!(" L {sx:.2} {sy:.2}"));
}
}
let frame = draw_frame(xmin, xmax, ymin, ymax, style);
Ok(svg_wrap(
&format!(r#"{frame}<path d="{path}" class="curve"/>"#),
"function plot",
))
}
pub fn plot_points_svg(xs: &[f64], ys: &[f64], style: PlotStyle) -> Result<String, String> {
if xs.len() != ys.len() {
return Err("plot_points: xs and ys length mismatch".into());
}
if xs.is_empty() {
return Err("plot_points: empty series".into());
}
let xmin = xs.iter().cloned().fold(f64::INFINITY, f64::min);
let xmax = xs.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
let ymin = ys.iter().cloned().fold(f64::INFINITY, f64::min);
let ymax = ys.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
let (xmin, xmax) = pad_range(xmin, xmax);
let (ymin, ymax) = pad_range(ymin, ymax);
let mut dots = String::new();
for (x, y) in xs.iter().zip(ys.iter()) {
if !x.is_finite() || !y.is_finite() {
continue;
}
let (sx, sy) = map_xy(*x, *y, xmin, xmax, ymin, ymax);
dots.push_str(&format!(
r#"<circle cx="{sx:.2}" cy="{sy:.2}" r="3" class="pt"/>"#
));
}
let frame = draw_frame(xmin, xmax, ymin, ymax, style);
Ok(svg_wrap(&format!("{frame}{dots}"), "points plot"))
}
/// Standard conics via parametric sampling.
/// kind: circle | ellipse | hyperbola | parabola
pub fn plot_conic_svg(
kind: &str,
a: f64,
b: f64,
h: f64,
k: f64,
style: PlotStyle,
) -> Result<String, String> {
let steps = DEFAULT_STEPS;
let mut pts: Vec<(f64, f64)> = Vec::new();
match kind {
"circle" => {
let r = if a > 0.0 { a } else { b };
if r <= 0.0 {
return Err("circle needs positive radius (a)".into());
}
for i in 0..=steps {
let t = std::f64::consts::TAU * (i as f64) / (steps as f64);
pts.push((h + r * t.cos(), k + r * t.sin()));
}
}
"ellipse" => {
if a <= 0.0 || b <= 0.0 {
return Err("ellipse needs a>0, b>0".into());
}
for i in 0..=steps {
let t = std::f64::consts::TAU * (i as f64) / (steps as f64);
pts.push((h + a * t.cos(), k + b * t.sin()));
}
}
"hyperbola" => {
if a <= 0.0 || b <= 0.0 {
return Err("hyperbola needs a>0, b>0".into());
}
for branch in [-1.0_f64, 1.0] {
for i in 0..=steps {
let t = -2.0 + 4.0 * (i as f64) / (steps as f64);
pts.push((h + branch * a * t.cosh(), k + b * t.sinh()));
}
}
let mid = pts.len() / 2;
let (left, right) = pts.split_at(mid);
let xmin = pts.iter().map(|p| p.0).fold(f64::INFINITY, f64::min);
let xmax = pts.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max);
let ymin = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
let ymax = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max);
let (xmin, xmax) = pad_range(xmin, xmax);
let (ymin, ymax) = pad_range(ymin, ymax);
let p1 = polyline_path(left, xmin, xmax, ymin, ymax);
let p2 = polyline_path(right, xmin, xmax, ymin, ymax);
let frame = draw_frame(xmin, xmax, ymin, ymax, style);
return Ok(svg_wrap(
&format!(
r#"{frame}<path d="{p1}" class="curve"/><path d="{p2}" class="curve"/>"#
),
"hyperbola",
));
}
"parabola" => {
let scale = if a.abs() > 1e-12 { a } else { 1.0 };
for i in 0..=steps {
let t = -3.0 + 6.0 * (i as f64) / (steps as f64);
let x = h + t;
let y = k + (t * t) / (4.0 * scale.abs()) * scale.signum();
pts.push((x, y));
}
}
other => return Err(format!("unknown conic kind `{other}`")),
}
let xmin = pts.iter().map(|p| p.0).fold(f64::INFINITY, f64::min);
let xmax = pts.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max);
let ymin = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
let ymax = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max);
let (xmin, xmax) = pad_range(xmin, xmax);
let (ymin, ymax) = pad_range(ymin, ymax);
let path = polyline_path(&pts, xmin, xmax, ymin, ymax);
let frame = draw_frame(xmin, xmax, ymin, ymax, style);
Ok(svg_wrap(
&format!(r#"{frame}<path d="{path}" class="curve"/>"#),
kind,
))
}
fn pad_range(lo: f64, hi: f64) -> (f64, f64) {
if (hi - lo).abs() < 1e-12 {
(lo - 1.0, hi + 1.0)
} else {
let pad = 0.05 * (hi - lo);
(lo - pad, hi + pad)
}
}
fn polyline_path(pts: &[(f64, f64)], xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> String {
let mut path = String::new();
for (i, (x, y)) in pts.iter().enumerate() {
let (sx, sy) = map_xy(*x, *y, xmin, xmax, ymin, ymax);
if i == 0 {
path.push_str(&format!("M {sx:.2} {sy:.2}"));
} else {
path.push_str(&format!(" L {sx:.2} {sy:.2}"));
}
}
path
}
fn map_xy(x: f64, y: f64, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> (f64, f64) {
let w = SVG_W - 2.0 * PAD;
let h = SVG_H - 2.0 * PAD;
let sx = PAD + (x - xmin) / (xmax - xmin) * w;
let sy = PAD + (ymax - y) / (ymax - ymin) * h;
(sx, sy)
}
fn nice_step(span: f64, target: usize) -> f64 {
let target = target.max(2) as f64;
let raw = (span / target).abs().max(1e-12);
let exp = raw.log10().floor();
let mag = 10f64.powf(exp);
let norm = raw / mag;
let nice = if norm <= 1.5 {
1.0
} else if norm <= 3.0 {
2.0
} else if norm <= 7.0 {
5.0
} else {
10.0
};
nice * mag
}
fn tick_values(lo: f64, hi: f64, step: f64) -> Vec<f64> {
if step <= 0.0 || !step.is_finite() {
return Vec::new();
}
let start = (lo / step).ceil() * step;
let mut out = Vec::new();
let mut v = start;
let mut guard = 0;
while v <= hi + step * 1e-9 && guard < 200 {
if v >= lo - step * 1e-9 && v <= hi + step * 1e-9 {
if v.abs() < step * 1e-9 {
out.push(0.0);
} else {
out.push(v);
}
}
v += step;
guard += 1;
}
out
}
fn draw_frame(xmin: f64, xmax: f64, ymin: f64, ymax: f64, style: PlotStyle) -> String {
let left = PAD;
let right = SVG_W - PAD;
let top = PAD;
let bottom = SVG_H - PAD;
let (ox, _) = map_xy(0.0, 0.0, xmin, xmax, ymin, ymax);
let (_, oy) = map_xy(0.0, 0.0, xmin, xmax, ymin, ymax);
let axis_x_y = if ymin <= 0.0 && ymax >= 0.0 {
oy.clamp(top, bottom)
} else if ymax < 0.0 {
top
} else {
bottom
};
let axis_y_x = if xmin <= 0.0 && xmax >= 0.0 {
ox.clamp(left, right)
} else if xmax < 0.0 {
right
} else {
left
};
let mut s = String::new();
let x_step = nice_step(xmax - xmin, 8);
let y_step = nice_step(ymax - ymin, 6);
if style.grid {
for x in tick_values(xmin, xmax, x_step) {
let (sx, _) = map_xy(x, 0.0, xmin, xmax, ymin, ymax);
if sx < left - 0.5 || sx > right + 0.5 {
continue;
}
s.push_str(&format!(
r#"<line x1="{sx:.2}" y1="{top}" x2="{sx:.2}" y2="{bottom}" class="grid"/>"#
));
}
for y in tick_values(ymin, ymax, y_step) {
let (_, sy) = map_xy(0.0, y, xmin, xmax, ymin, ymax);
if sy < top - 0.5 || sy > bottom + 0.5 {
continue;
}
s.push_str(&format!(
r#"<line x1="{left}" y1="{sy:.2}" x2="{right}" y2="{sy:.2}" class="grid"/>"#
));
}
}
// Axes with arrowheads (positive direction).
s.push_str(&format!(
r#"<line x1="{left}" y1="{axis_x_y:.2}" x2="{right}" y2="{axis_x_y:.2}" class="axis" marker-end="url(#arrow)"/>"#
));
s.push_str(&format!(
r#"<line x1="{axis_y_x:.2}" y1="{bottom}" x2="{axis_y_x:.2}" y2="{top}" class="axis" marker-end="url(#arrow)"/>"#
));
// Axis end labels
s.push_str(&format!(
r#"<text x="{x:.2}" y="{y:.2}" class="axis-label">x</text>"#,
x = right + 4.0,
y = axis_x_y + 4.0,
));
s.push_str(&format!(
r#"<text x="{x:.2}" y="{y:.2}" class="axis-label">y</text>"#,
x = axis_y_x + 6.0,
y = top + 4.0,
));
// Tick labels along axes (skip 0 clutter when both axes cross).
for x in tick_values(xmin, xmax, x_step) {
if x.abs() < x_step * 1e-9 {
continue;
}
let (sx, _) = map_xy(x, 0.0, xmin, xmax, ymin, ymax);
if sx < left || sx > right {
continue;
}
s.push_str(&format!(
r#"<line x1="{sx:.2}" y1="{y1:.2}" x2="{sx:.2}" y2="{y2:.2}" class="tick"/>"#,
y1 = axis_x_y - 4.0,
y2 = axis_x_y + 4.0,
));
s.push_str(&format!(
r#"<text x="{sx:.2}" y="{ty:.2}" text-anchor="middle" class="tick-label">{label}</text>"#,
ty = (axis_x_y + 14.0).min(bottom + 14.0),
label = super::format_num(x),
));
}
for y in tick_values(ymin, ymax, y_step) {
if y.abs() < y_step * 1e-9 {
continue;
}
let (_, sy) = map_xy(0.0, y, xmin, xmax, ymin, ymax);
if sy < top || sy > bottom {
continue;
}
s.push_str(&format!(
r#"<line x1="{x1:.2}" y1="{sy:.2}" x2="{x2:.2}" y2="{sy:.2}" class="tick"/>"#,
x1 = axis_y_x - 4.0,
x2 = axis_y_x + 4.0,
));
s.push_str(&format!(
r#"<text x="{tx:.2}" y="{sy:.2}" text-anchor="end" dominant-baseline="middle" class="tick-label">{label}</text>"#,
tx = (axis_y_x - 8.0).max(4.0),
label = super::format_num(y),
));
}
// Origin mark when visible
if xmin <= 0.0 && xmax >= 0.0 && ymin <= 0.0 && ymax >= 0.0 {
s.push_str(&format!(
r#"<text x="{x:.2}" y="{y:.2}" class="tick-label">0</text>"#,
x = axis_y_x - 8.0,
y = axis_x_y + 14.0,
));
}
s
}
fn svg_wrap(body: &str, title: &str) -> String {
// r## so fill="#…" does not terminate the raw string at "#
format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" width="{w}" height="{h}" role="img" aria-label="{title}">
<defs>
<marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#4b5563"/>
</marker>
</defs>
<style>
.grid {{ stroke: #e5e7eb; stroke-width: 1; }}
.axis {{ stroke: #4b5563; stroke-width: 1.5; }}
.tick {{ stroke: #4b5563; stroke-width: 1; }}
.curve {{ fill: none; stroke: #1f6feb; stroke-width: 2; }}
.pt {{ fill: #1f6feb; }}
.axis-label {{ font: 12px ui-sans-serif, system-ui, sans-serif; fill: #374151; font-weight: 600; }}
.tick-label {{ font: 10px ui-sans-serif, system-ui, sans-serif; fill: #6b7280; }}
</style>
{body}
</svg>"##,
w = SVG_W,
h = SVG_H,
title = title,
body = body,
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::formula::parse;
#[test]
fn plot_has_arrows_and_grid_by_default() {
let e = parse("x^2").unwrap();
let svg = plot_function_svg(&e, "x", -2.0, 2.0, 40, PlotStyle::default()).unwrap();
assert!(svg.contains("marker-end=\"url(#arrow)\""));
assert!(svg.contains("class=\"grid\""));
assert!(svg.contains(">x</text>"));
assert!(svg.contains(">y</text>"));
}
#[test]
fn plot_can_disable_grid() {
let e = parse("x").unwrap();
let svg = plot_function_svg(&e, "x", -1.0, 1.0, 20, PlotStyle { grid: false }).unwrap();
assert!(!svg.contains("class=\"grid\""));
assert!(svg.contains("marker-end=\"url(#arrow)\""));
}
}
+243 -3
View File
@@ -2,7 +2,7 @@
use std::collections::HashMap;
use crate::host::{fs, json, net, sys, time, HostContext};
use crate::host::{fs, json, math, net, sys, time, HostContext};
use crate::value::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -33,6 +33,43 @@ pub enum HostFn {
HttpGet = 23,
HttpPost = 24,
UrlEncode = 25,
// math
Pi = 26,
EConst = 27,
Num = 28,
MathAdd = 29,
MathSub = 30,
MathMul = 31,
MathDiv = 32,
MathPow = 33,
MathNeg = 34,
MathSin = 35,
MathCos = 36,
MathTan = 37,
MathAsin = 38,
MathAcos = 39,
MathAtan = 40,
MathSqrt = 41,
MathAbs = 42,
MathLn = 43,
MathExp = 44,
MathFloor = 45,
MathCeil = 46,
MathMin = 47,
MathMax = 48,
Random = 49,
RandomInt = 50,
Seed = 51,
Formula = 52,
Simplify = 53,
Expand = 54,
Diff = 55,
Subs = 56,
Eval = 57,
Solve = 58,
Plot = 59,
PlotPoints = 60,
PlotConic = 61,
}
impl HostFn {
@@ -63,6 +100,42 @@ impl HostFn {
23 => Self::HttpGet,
24 => Self::HttpPost,
25 => Self::UrlEncode,
26 => Self::Pi,
27 => Self::EConst,
28 => Self::Num,
29 => Self::MathAdd,
30 => Self::MathSub,
31 => Self::MathMul,
32 => Self::MathDiv,
33 => Self::MathPow,
34 => Self::MathNeg,
35 => Self::MathSin,
36 => Self::MathCos,
37 => Self::MathTan,
38 => Self::MathAsin,
39 => Self::MathAcos,
40 => Self::MathAtan,
41 => Self::MathSqrt,
42 => Self::MathAbs,
43 => Self::MathLn,
44 => Self::MathExp,
45 => Self::MathFloor,
46 => Self::MathCeil,
47 => Self::MathMin,
48 => Self::MathMax,
49 => Self::Random,
50 => Self::RandomInt,
51 => Self::Seed,
52 => Self::Formula,
53 => Self::Simplify,
54 => Self::Expand,
55 => Self::Diff,
56 => Self::Subs,
57 => Self::Eval,
58 => Self::Solve,
59 => Self::Plot,
60 => Self::PlotPoints,
61 => Self::PlotConic,
_ => return None,
})
}
@@ -94,6 +167,44 @@ impl HostFn {
"host_http_get" => Self::HttpGet,
"host_http_post" => Self::HttpPost,
"host_url_encode" => Self::UrlEncode,
"host_pi" => Self::Pi,
"host_e" => Self::EConst,
"host_num" => Self::Num,
"host_math_add" => Self::MathAdd,
"host_math_sub" => Self::MathSub,
"host_math_mul" => Self::MathMul,
"host_math_div" => Self::MathDiv,
"host_math_pow" => Self::MathPow,
"host_math_neg" => Self::MathNeg,
"host_math_sin" => Self::MathSin,
"host_math_cos" => Self::MathCos,
"host_math_tan" => Self::MathTan,
"host_math_asin" => Self::MathAsin,
"host_math_acos" => Self::MathAcos,
"host_math_atan" => Self::MathAtan,
"host_math_sqrt" => Self::MathSqrt,
"host_math_abs" => Self::MathAbs,
"host_math_ln" => Self::MathLn,
"host_math_exp" => Self::MathExp,
"host_math_floor" => Self::MathFloor,
"host_math_ceil" => Self::MathCeil,
"host_math_min" => Self::MathMin,
"host_math_max" => Self::MathMax,
"host_random" => Self::Random,
"host_random_int" => Self::RandomInt,
"host_seed" => Self::Seed,
"host_formula" => Self::Formula,
"host_simplify" => Self::Simplify,
"host_expand" => Self::Expand,
"host_diff" => Self::Diff,
"host_subs" => Self::Subs,
"host_eval" => Self::Eval,
"host_solve" => Self::Solve,
// Friendly aliases so L1 `plot` / `绘图` get host optionals (`grid`, `path`, …)
// instead of thin wrappers that only forward required params.
"host_plot" | "plot" | "绘图" => Self::Plot,
"host_plot_points" | "plot_points" | "绘点列" => Self::PlotPoints,
"host_plot_conic" | "plot_conic" | "绘圆锥" => Self::PlotConic,
_ => return None,
})
}
@@ -129,10 +240,45 @@ impl HostFn {
Self::HttpGet => "host_http_get",
Self::HttpPost => "host_http_post",
Self::UrlEncode => "host_url_encode",
Self::Pi => "host_pi",
Self::EConst => "host_e",
Self::Num => "host_num",
Self::MathAdd => "host_math_add",
Self::MathSub => "host_math_sub",
Self::MathMul => "host_math_mul",
Self::MathDiv => "host_math_div",
Self::MathPow => "host_math_pow",
Self::MathNeg => "host_math_neg",
Self::MathSin => "host_math_sin",
Self::MathCos => "host_math_cos",
Self::MathTan => "host_math_tan",
Self::MathAsin => "host_math_asin",
Self::MathAcos => "host_math_acos",
Self::MathAtan => "host_math_atan",
Self::MathSqrt => "host_math_sqrt",
Self::MathAbs => "host_math_abs",
Self::MathLn => "host_math_ln",
Self::MathExp => "host_math_exp",
Self::MathFloor => "host_math_floor",
Self::MathCeil => "host_math_ceil",
Self::MathMin => "host_math_min",
Self::MathMax => "host_math_max",
Self::Random => "host_random",
Self::RandomInt => "host_random_int",
Self::Seed => "host_seed",
Self::Formula => "host_formula",
Self::Simplify => "host_simplify",
Self::Expand => "host_expand",
Self::Diff => "host_diff",
Self::Subs => "host_subs",
Self::Eval => "host_eval",
Self::Solve => "host_solve",
Self::Plot => "host_plot",
Self::PlotPoints => "host_plot_points",
Self::PlotConic => "host_plot_conic",
}
}
/// Required params first; see `optional_params` for trailing optionals.
pub fn required_params(self) -> &'static [&'static str] {
match self {
Self::ReadText | Self::Exists | Self::ListDir | Self::MakeDir | Self::Remove => {
@@ -152,6 +298,20 @@ impl HostFn {
Self::JsonGet => &["value", "key"],
Self::HttpGet => &["url"],
Self::HttpPost => &["url", "body"],
Self::Pi | Self::EConst | Self::Random => &[],
Self::Num | Self::MathNeg | Self::MathSin | Self::MathCos | Self::MathTan
| Self::MathAsin | Self::MathAcos | Self::MathAtan | Self::MathSqrt
| Self::MathAbs | Self::MathLn | Self::MathExp | Self::MathFloor | Self::MathCeil
| Self::Seed | Self::Formula | Self::Simplify | Self::Expand => &["value"],
Self::MathAdd | Self::MathSub | Self::MathMul | Self::MathDiv | Self::MathPow
| Self::MathMin | Self::MathMax => &["a", "b"],
Self::RandomInt => &["min", "max"],
Self::Diff => &["formula", "var"],
Self::Subs | Self::Eval => &["formula", "var", "value"],
Self::Solve => &["formula", "var"],
Self::Plot => &["formula", "var", "min", "max"],
Self::PlotPoints => &["xs", "ys"],
Self::PlotConic => &["kind", "a"],
}
}
@@ -160,6 +320,10 @@ impl HostFn {
Self::JsonStringify => &["indent"],
Self::HttpPost => &["content_type"],
Self::Exec => &["args"],
Self::Solve => &["min", "max"],
Self::Plot => &["steps", "path", "derivative", "grid"],
Self::PlotPoints => &["path", "grid"],
Self::PlotConic => &["b", "h", "k", "path", "grid"],
_ => &[],
}
}
@@ -172,7 +336,7 @@ impl HostFn {
}
pub fn call_host(
ctx: &HostContext,
ctx: &mut HostContext,
fn_id: HostFn,
bound: &HashMap<String, Value>,
) -> Result<Value, String> {
@@ -217,6 +381,82 @@ pub fn call_host(
bound.get("content_type"),
),
HostFn::UrlEncode => net::url_encode(require(bound, "text")?),
HostFn::Pi => math::pi(),
HostFn::EConst => math::e_const(),
HostFn::Num => math::to_num(require(bound, "value")?),
HostFn::MathAdd => math::binary_num("add", require(bound, "a")?, require(bound, "b")?),
HostFn::MathSub => math::binary_num("sub", require(bound, "a")?, require(bound, "b")?),
HostFn::MathMul => math::binary_num("mul", require(bound, "a")?, require(bound, "b")?),
HostFn::MathDiv => math::binary_num("div", require(bound, "a")?, require(bound, "b")?),
HostFn::MathPow => math::binary_num("pow", require(bound, "a")?, require(bound, "b")?),
HostFn::MathMin => math::binary_num("min", require(bound, "a")?, require(bound, "b")?),
HostFn::MathMax => math::binary_num("max", require(bound, "a")?, require(bound, "b")?),
HostFn::MathNeg => math::unary_num("neg", require(bound, "value")?),
HostFn::MathSin => math::unary_num("sin", require(bound, "value")?),
HostFn::MathCos => math::unary_num("cos", require(bound, "value")?),
HostFn::MathTan => math::unary_num("tan", require(bound, "value")?),
HostFn::MathAsin => math::unary_num("asin", require(bound, "value")?),
HostFn::MathAcos => math::unary_num("acos", require(bound, "value")?),
HostFn::MathAtan => math::unary_num("atan", require(bound, "value")?),
HostFn::MathSqrt => math::unary_num("sqrt", require(bound, "value")?),
HostFn::MathAbs => math::unary_num("abs", require(bound, "value")?),
HostFn::MathLn => math::unary_num("ln", require(bound, "value")?),
HostFn::MathExp => math::unary_num("exp", require(bound, "value")?),
HostFn::MathFloor => math::unary_num("floor", require(bound, "value")?),
HostFn::MathCeil => math::unary_num("ceil", require(bound, "value")?),
HostFn::Random => math::random(ctx),
HostFn::RandomInt => {
math::random_int(ctx, require(bound, "min")?, require(bound, "max")?)
}
HostFn::Seed => math::seed(ctx, require(bound, "value")?),
HostFn::Formula => math::formula_parse(require(bound, "value")?),
HostFn::Simplify => math::simplify(require(bound, "value")?),
HostFn::Expand => math::expand(require(bound, "value")?),
HostFn::Diff => math::diff(require(bound, "formula")?, require(bound, "var")?),
HostFn::Subs => math::subs(
require(bound, "formula")?,
require(bound, "var")?,
require(bound, "value")?,
),
HostFn::Eval => math::eval_at(
require(bound, "formula")?,
require(bound, "var")?,
require(bound, "value")?,
),
HostFn::Solve => math::solve(
require(bound, "formula")?,
require(bound, "var")?,
bound.get("min"),
bound.get("max"),
),
HostFn::Plot => math::plot(
ctx,
require(bound, "formula")?,
require(bound, "var")?,
require(bound, "min")?,
require(bound, "max")?,
bound.get("steps"),
bound.get("path"),
bound.get("derivative"),
bound.get("grid"),
),
HostFn::PlotPoints => math::plot_points(
ctx,
require(bound, "xs")?,
require(bound, "ys")?,
bound.get("path"),
bound.get("grid"),
),
HostFn::PlotConic => math::plot_conic(
ctx,
require(bound, "kind")?,
require(bound, "a")?,
bound.get("b"),
bound.get("h"),
bound.get("k"),
bound.get("path"),
bound.get("grid"),
),
}
}
+6
View File
@@ -60,6 +60,8 @@ fn json_to_value(v: &serde_json::Value) -> Result<Value, String> {
serde_json::Value::Number(n) => {
if let Some(i) = n.as_i64() {
Value::Int(i)
} else if let Some(f) = n.as_f64() {
Value::Num(f)
} else {
Value::Text(n.to_string())
}
@@ -87,6 +89,9 @@ fn value_to_json(v: &Value) -> Result<serde_json::Value, String> {
Value::None => serde_json::Value::Null,
Value::Bool(b) => serde_json::Value::Bool(*b),
Value::Int(n) => serde_json::Value::Number((*n).into()),
Value::Num(n) => serde_json::Number::from_f64(*n)
.map(serde_json::Value::Number)
.unwrap_or(serde_json::Value::Null),
Value::Text(s) => serde_json::Value::String(s.clone()),
Value::List(xs) => {
let mut arr = Vec::with_capacity(xs.len());
@@ -102,5 +107,6 @@ fn value_to_json(v: &Value) -> Result<serde_json::Value, String> {
}
serde_json::Value::Object(map)
}
Value::Formula(e) => serde_json::Value::String(e.as_display()),
})
}
+284
View File
@@ -0,0 +1,284 @@
//! Host entry points for math / formula / random / plot.
use std::collections::HashMap;
use crate::formula::{self, Expr};
use crate::host::fs;
use crate::host::{HostContext, PlotArtifact};
use crate::value::Value;
pub fn as_f64(v: &Value) -> Result<f64, String> {
match v {
Value::Num(n) => Ok(*n),
Value::Int(n) => Ok(*n as f64),
Value::Text(s) => s
.trim()
.parse::<f64>()
.map_err(|_| format!("cannot convert to num: {s:?}")),
_ => Err("expected num (or int/text)".into()),
}
}
fn opt<'a>(v: Option<&'a Value>) -> Option<&'a Value> {
match v {
None | Some(Value::None) => None,
Some(v) => Some(v),
}
}
pub fn as_text(v: &Value) -> Result<&str, String> {
match v {
Value::Text(s) => Ok(s.as_str()),
_ => Err("expected text".into()),
}
}
pub fn as_bool(v: &Value) -> bool {
v.truthy()
}
pub fn formula_from_value(v: &Value) -> Result<Expr, String> {
match v {
Value::Formula(e) => Ok(e.clone()),
Value::Text(s) => formula::parse(s),
Value::Num(n) => Ok(Expr::Num(*n)),
Value::Int(n) => Ok(Expr::Num(*n as f64)),
_ => Err("expected formula or expression text".into()),
}
}
fn num_val(n: f64) -> Value {
Value::Num(n)
}
pub fn pi() -> Result<Value, String> {
Ok(num_val(std::f64::consts::PI))
}
pub fn e_const() -> Result<Value, String> {
Ok(num_val(std::f64::consts::E))
}
pub fn to_num(v: &Value) -> Result<Value, String> {
Ok(num_val(as_f64(v)?))
}
pub fn unary_num(op: &str, x: &Value) -> Result<Value, String> {
let x = as_f64(x)?;
let y = match op {
"neg" => -x,
"sin" => x.sin(),
"cos" => x.cos(),
"tan" => x.tan(),
"asin" => x.asin(),
"acos" => x.acos(),
"atan" => x.atan(),
"sqrt" => x.sqrt(),
"abs" => x.abs(),
"ln" | "log" => x.ln(),
"exp" => x.exp(),
"floor" => x.floor(),
"ceil" => x.ceil(),
_ => return Err(format!("unknown unary math op `{op}`")),
};
Ok(num_val(y))
}
pub fn binary_num(op: &str, a: &Value, b: &Value) -> Result<Value, String> {
let a = as_f64(a)?;
let b = as_f64(b)?;
let y = match op {
"add" => a + b,
"sub" => a - b,
"mul" => a * b,
"div" => {
if b == 0.0 {
return Err("division by zero".into());
}
a / b
}
"pow" => a.powf(b),
"min" => a.min(b),
"max" => a.max(b),
_ => return Err(format!("unknown binary math op `{op}`")),
};
Ok(num_val(y))
}
pub fn seed(ctx: &mut HostContext, v: &Value) -> Result<Value, String> {
let n = as_f64(v)? as u64;
ctx.rng = n ^ 0xA5A5_A5A5_A5A5_A5A5;
if ctx.rng == 0 {
ctx.rng = 0xC0FFEE;
}
Ok(Value::None)
}
pub fn random(ctx: &mut HostContext) -> Result<Value, String> {
Ok(num_val(ctx.next_f64()))
}
pub fn random_int(ctx: &mut HostContext, lo: &Value, hi: &Value) -> Result<Value, String> {
let lo = as_f64(lo)? as i64;
let hi = as_f64(hi)? as i64;
if hi < lo {
return Err("random_int: max < min".into());
}
let span = (hi - lo + 1) as u64;
let r = ctx.next_u64() % span;
Ok(Value::Int(lo + r as i64))
}
pub fn formula_parse(text: &Value) -> Result<Value, String> {
let s = as_text(text)?;
Ok(Value::Formula(formula::parse(s)?))
}
pub fn simplify(v: &Value) -> Result<Value, String> {
Ok(Value::Formula(formula::simplify(&formula_from_value(v)?)))
}
pub fn expand(v: &Value) -> Result<Value, String> {
Ok(Value::Formula(formula::expand(&formula_from_value(v)?)))
}
pub fn diff(formula: &Value, var: &Value) -> Result<Value, String> {
let e = formula_from_value(formula)?;
let var = as_text(var)?;
Ok(Value::Formula(formula::diff(&e, var)))
}
pub fn subs(formula: &Value, var: &Value, value: &Value) -> Result<Value, String> {
let e = formula_from_value(formula)?;
let var = as_text(var)?;
let val = formula_from_value(value)?;
let out = formula::subs(&e, var, &val);
if let Expr::Num(n) = out {
Ok(num_val(n))
} else {
Ok(Value::Formula(out))
}
}
pub fn eval_at(formula: &Value, var: &Value, value: &Value) -> Result<Value, String> {
let e = formula_from_value(formula)?;
let var = as_text(var)?;
let x = as_f64(value)?;
let mut env = HashMap::new();
env.insert(var.to_string(), x);
Ok(num_val(formula::eval_f64(&e, &env)?))
}
pub fn solve(
formula: &Value,
var: &Value,
min: Option<&Value>,
max: Option<&Value>,
) -> Result<Value, String> {
let e = formula_from_value(formula)?;
let var = as_text(var)?;
let xmin = opt(min).map(as_f64).transpose()?.unwrap_or(-100.0);
let xmax = opt(max).map(as_f64).transpose()?.unwrap_or(100.0);
let roots = formula::solve(&e, var, xmin, xmax)?;
Ok(Value::List(roots.into_iter().map(num_val).collect()))
}
fn maybe_write_plot(
ctx: &mut HostContext,
path: Option<&Value>,
svg: String,
) -> Result<Value, String> {
let path_s = match opt(path) {
Some(v) => Some(as_text(v)?.to_string()),
None => None,
};
if let Some(ref p) = path_s {
fs::write_text(ctx, &Value::Text(p.clone()), &Value::Text(svg.clone()))?;
}
ctx.plots.push(PlotArtifact {
path: path_s,
svg: svg.clone(),
});
Ok(Value::Text(svg))
}
fn plot_style(grid: Option<&Value>) -> Result<formula::PlotStyle, String> {
let grid = match opt(grid) {
None => true,
Some(v) => as_bool(v),
};
Ok(formula::PlotStyle { grid })
}
pub fn plot(
ctx: &mut HostContext,
formula: &Value,
var: &Value,
min: &Value,
max: &Value,
steps: Option<&Value>,
path: Option<&Value>,
derivative: Option<&Value>,
grid: Option<&Value>,
) -> Result<Value, String> {
let mut e = formula_from_value(formula)?;
let var_s = as_text(var)?;
if opt(derivative).map(as_bool).unwrap_or(false) {
e = formula::diff(&e, var_s);
}
let xmin = as_f64(min)?;
let xmax = as_f64(max)?;
let steps = match opt(steps) {
Some(v) => as_f64(v)? as usize,
None => 200,
};
let style = plot_style(grid)?;
let svg = formula::plot_function_svg(&e, var_s, xmin, xmax, steps, style)?;
maybe_write_plot(ctx, path, svg)
}
pub fn plot_points(
ctx: &mut HostContext,
xs: &Value,
ys: &Value,
path: Option<&Value>,
grid: Option<&Value>,
) -> Result<Value, String> {
let xs = match xs {
Value::List(xs) => xs
.iter()
.map(as_f64)
.collect::<Result<Vec<_>, _>>()?,
_ => return Err("plot_points needs list xs".into()),
};
let ys = match ys {
Value::List(ys) => ys
.iter()
.map(as_f64)
.collect::<Result<Vec<_>, _>>()?,
_ => return Err("plot_points needs list ys".into()),
};
let style = plot_style(grid)?;
let svg = formula::plot_points_svg(&xs, &ys, style)?;
maybe_write_plot(ctx, path, svg)
}
pub fn plot_conic(
ctx: &mut HostContext,
kind: &Value,
a: &Value,
b: Option<&Value>,
h: Option<&Value>,
k: Option<&Value>,
path: Option<&Value>,
grid: Option<&Value>,
) -> Result<Value, String> {
let kind = as_text(kind)?;
let a = as_f64(a)?;
let b = opt(b).map(as_f64).transpose()?.unwrap_or(a);
let h = opt(h).map(as_f64).transpose()?.unwrap_or(0.0);
let k = opt(k).map(as_f64).transpose()?.unwrap_or(0.0);
let style = plot_style(grid)?;
let svg = formula::plot_conic_svg(kind, a, b, h, k, style)?;
maybe_write_plot(ctx, path, svg)
}
+57 -1
View File
@@ -1,4 +1,4 @@
//! L0.5 host primitives for official stdlib (`lib/fs`, `time`, …).
//! L0.5 host primitives for official stdlib (`lib/fs`, `time`, `math`, …).
//!
//! User docs should import L1 wrappers; these `host_*` names are the Rust surface.
//! Capabilities default **on** (importing a lib means you intend to use it).
@@ -7,6 +7,7 @@
mod dispatch;
mod fs;
mod json;
pub mod math;
mod net;
mod sys;
mod time;
@@ -34,6 +35,14 @@ impl Default for HostCaps {
}
}
/// SVG plot produced during a run (for CLI auto-write / view embed).
#[derive(Debug, Clone)]
pub struct PlotArtifact {
/// User-requested path, if any.
pub path: Option<String>,
pub svg: String,
}
#[derive(Debug, Clone)]
pub struct HostContext {
pub caps: HostCaps,
@@ -43,6 +52,9 @@ pub struct HostContext {
/// Soft mode: do not `process::exit`; honor sleep_limit (view / capture / export).
pub soft_side_effects: bool,
pub sleep_limit_ms: Option<u64>,
/// LCG state for `random` / `random_int`.
pub rng: u64,
pub plots: Vec<PlotArtifact>,
}
impl Default for HostContext {
@@ -54,6 +66,8 @@ impl Default for HostContext {
argv: Vec::new(),
soft_side_effects: false,
sleep_limit_ms: Some(30_000),
rng: 0xC0FF_EE42_CAFE_BABE,
plots: Vec::new(),
}
}
}
@@ -97,6 +111,23 @@ impl HostContext {
self.caps.net
}
pub fn next_u64(&mut self) -> u64 {
// SplitMix64-ish LCG step
self.rng = self
.rng
.wrapping_mul(6364136223846793005)
.wrapping_add(1);
let mut z = self.rng;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
z ^ (z >> 31)
}
pub fn next_f64(&mut self) -> f64 {
let x = self.next_u64() >> 11;
(x as f64) / ((1u64 << 53) as f64)
}
pub fn resolve_path(&self, rel: &str) -> Result<PathBuf, String> {
let p = Path::new(rel);
let abs = if p.is_absolute() {
@@ -124,3 +155,28 @@ impl HostContext {
Ok(abs)
}
}
/// Write auto-named plot files for CLI runs when `path` was omitted.
pub fn flush_auto_plots(source_path: Option<&Path>, plots: &[PlotArtifact]) -> Result<(), String> {
let mut auto_i = 0usize;
for plot in plots {
if plot.path.is_some() {
continue;
}
auto_i += 1;
let stem = source_path
.and_then(|p| p.file_stem())
.and_then(|s| s.to_str())
.unwrap_or("out");
let stem = stem.trim_end_matches(".mq");
let name = format!("{stem}-plot-{auto_i}.svg");
let dir = source_path
.and_then(|p| p.parent())
.unwrap_or_else(|| Path::new("."));
let dest = dir.join(&name);
std::fs::write(&dest, plot.svg.as_bytes())
.map_err(|e| format!("failed to write plot {}: {e}", dest.display()))?;
println!("plot: {}", dest.display());
}
Ok(())
}
+15 -3
View File
@@ -87,6 +87,10 @@ impl Interpreter {
self
}
pub fn take_plots(&mut self) -> Vec<crate::host::PlotArtifact> {
std::mem::take(&mut self.host.plots)
}
fn err(&self, message: impl Into<String>) -> anyhow::Error {
bail_at(self.path.as_deref(), self.current_span, message)
}
@@ -181,7 +185,7 @@ impl Interpreter {
stmt: &Stmt,
) -> Result<Option<Value>> {
match stmt {
Stmt::Assign { name, value, span } => {
Stmt::Assign { name, value, span, .. } => {
self.current_span = *span;
let v = self.eval_expr(module, fun, env, value)?;
if self.trace {
@@ -390,6 +394,7 @@ impl Interpreter {
}
Ok(Value::List(out))
}
Expr::Formula(e) => Ok(Value::Formula(e.clone())),
}
}
@@ -539,7 +544,7 @@ impl Interpreter {
return Err(self.err(format!("{} requires `{req}`", hf.name())));
}
}
return call_host(&self.host, hf, &bound).map_err(|m| self.err(m));
return call_host(&mut self.host, hf, &bound).map_err(|m| self.err(m));
}
_ => {}
}
@@ -680,7 +685,14 @@ fn eval_binary(op: BinaryOp, l: &Value, r: &Value) -> Result<Value> {
fn cmp_ord(l: &Value, r: &Value, f: impl Fn(std::cmp::Ordering) -> bool) -> Result<Value> {
match (l, r) {
(Value::Int(a), Value::Int(b)) => Ok(Value::Bool(f(a.cmp(b)))),
(Value::Num(a), Value::Num(b)) => Ok(Value::Bool(f(a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)))),
(Value::Int(a), Value::Num(b)) => {
Ok(Value::Bool(f((*a as f64).partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))))
}
(Value::Num(a), Value::Int(b)) => {
Ok(Value::Bool(f(a.partial_cmp(&(*b as f64)).unwrap_or(std::cmp::Ordering::Equal))))
}
(Value::Text(a), Value::Text(b)) => Ok(Value::Bool(f(a.cmp(b)))),
_ => bail!("comparison needs two ints or two texts"),
_ => bail!("comparison needs two ints/nums or two texts"),
}
}
+39 -14
View File
@@ -36,7 +36,7 @@ pub struct ClassifiedLine {
fn is_code_starter(c: char) -> bool {
matches!(
c,
'#' | '*' | '>' | '+' | '-' | '`' | '|' | '~'
'#' | '*' | '>' | '+' | '-' | '`' | '|' | '~' | '$'
) || c.is_ascii_digit()
}
@@ -72,26 +72,40 @@ pub fn classify_source(source: &str) -> Vec<ClassifiedLine> {
let mut out = Vec::with_capacity(lines.len());
let mut in_comment_paragraph = false;
let mut in_math_fence = 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 = match base {
LineKind::Blank => {
in_comment_paragraph = false;
LineKind::Blank
let kind = if in_math_fence {
if trimmed == "$$" {
in_math_fence = false;
}
LineKind::Comment => {
in_comment_paragraph = true;
LineKind::Comment
LineKind::Code
} else {
match base {
LineKind::Blank => {
in_comment_paragraph = false;
LineKind::Blank
}
LineKind::Comment => {
in_comment_paragraph = true;
LineKind::Comment
}
LineKind::Code if structural => {
in_comment_paragraph = false;
LineKind::Code
}
LineKind::Code if in_comment_paragraph => LineKind::Comment,
LineKind::Code => {
// Multi-line math fence opener (not same-line `$$…$$`).
if trimmed == "$$" {
in_math_fence = true;
}
LineKind::Code
}
}
LineKind::Code if structural => {
in_comment_paragraph = false;
LineKind::Code
}
LineKind::Code if in_comment_paragraph => LineKind::Comment,
LineKind::Code => LineKind::Code,
};
out.push(ClassifiedLine {
line_no: (i + 1) as u32,
@@ -186,4 +200,15 @@ mod tests {
assert!(lines.iter().any(|l| l.kind == LineKind::Comment));
assert!(lines.iter().any(|l| l.kind == LineKind::Code));
}
#[test]
fn math_fence_body_stays_code() {
let lines = classify_source("`f` =\n$$\nx^2 - 2\n$$\n");
assert!(
lines
.iter()
.all(|l| l.kind == LineKind::Code || l.kind == LineKind::Blank),
"expected fence body as Code, got {lines:?}"
);
}
}
+10 -1
View File
@@ -11,6 +11,7 @@ pub mod capture;
pub mod catalog;
pub mod debug;
pub mod diagnostics;
pub mod formula;
pub mod host;
pub mod input_feed;
pub mod interp;
@@ -24,7 +25,7 @@ use std::path::Path;
use anyhow::{bail, Result};
use crate::host::{HostCaps, HostContext};
use crate::host::{flush_auto_plots, HostCaps, HostContext};
use crate::ast::format_ast_dump;
use crate::bytecode::{compile_module, Vm};
use crate::capture::RunCapture;
@@ -178,6 +179,8 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
if opts.trace_eval {
eprintln!("=== marqdo: end trace-eval ===");
}
let plots = interp.take_plots();
flush_auto_plots(Some(path), &plots).map_err(|e| anyhow::anyhow!(e))?;
}
Backend::Bytecode => {
let program = compile_module(Some(path), &module)?;
@@ -196,6 +199,8 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
if opts.trace_eval {
eprintln!("=== marqdo: end trace-eval ===");
}
let plots = vm.take_plots();
flush_auto_plots(Some(path), &plots).map_err(|e| anyhow::anyhow!(e))?;
}
}
@@ -228,9 +233,11 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
.with_stdin(stdin_lines)
.with_host(host);
let value = interp.run_module(&module)?;
let plots = interp.take_plots();
Ok(RunCapture {
stdout: interp.captured_stdout,
value,
plots,
})
}
Backend::Bytecode => {
@@ -247,9 +254,11 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
.with_stdin(stdin_lines)
.with_host(host);
let value = vm.run(&program)?;
let plots = vm.take_plots();
Ok(RunCapture {
stdout: vm.captured_stdout,
value,
plots,
})
}
}
+175 -38
View File
@@ -206,6 +206,13 @@ impl<'a> Cursor<'a> {
bail!("{span}: unexpected frame line as statement");
}
if trimmed.starts_with("$$") {
bail!(
"{span}: formula fence must follow an empty assignment (`name` =); \
`$$:name` binding was removed"
);
}
// Bold return **…** (empty inner → None)
if trimmed.starts_with("**") && trimmed.ends_with("**") && trimmed.len() >= 4 {
let inner = &trimmed[2..trimmed.len() - 2];
@@ -220,7 +227,7 @@ impl<'a> Cursor<'a> {
// Italic statement *…*
if trimmed.starts_with('*') && trimmed.ends_with('*') && !trimmed.starts_with("**") {
let inner = &trimmed[1..trimmed.len() - 1];
return parse_assign_or_expr_stmt(inner, span);
return self.parse_italic_assign(inner, span);
}
// Call >
@@ -229,7 +236,7 @@ impl<'a> Cursor<'a> {
return Ok(Stmt::Call { call, span });
}
// Bare assign `` `x` = … `` possibly followed by table
// Bare assign `` `x` = … `` possibly followed by formula fence or table
if trimmed.starts_with('`') {
if let Some(stmt) = self.parse_backtick_assign(trimmed, span.clone())? {
return Ok(stmt);
@@ -239,6 +246,22 @@ impl<'a> Cursor<'a> {
Err(Diagnostic::new(None, span, format!("unrecognized statement: {trimmed}")).into())
}
fn parse_italic_assign(&mut self, inner: &str, span: Span) -> Result<Stmt> {
let Some((name, rhs)) = split_assign_inner(inner) else {
bail!("{span}: italic statement must be an assignment (`name` = …)");
};
if crate::aliases::is_reserved_keyword(&name) {
bail!("{span}: `{name}` is a reserved keyword");
}
let (value, end_line) = self.resolve_assign_rhs(&rhs, span)?;
Ok(Stmt::Assign {
name,
value,
span,
end_line,
})
}
fn parse_backtick_assign(&mut self, trimmed: &str, span: Span) -> Result<Option<Stmt>> {
// `name` = [rhs]
let Some(rest) = trimmed.strip_prefix('`') else {
@@ -255,23 +278,114 @@ impl<'a> Cursor<'a> {
if !after.starts_with('=') {
return Ok(None);
}
let rhs = after[1..].trim();
if rhs.is_empty() {
// Consume following table if present.
let list = self.consume_table()?;
return Ok(Some(Stmt::Assign {
name,
value: Expr::List(list.into_iter().map(Expr::Literal).collect()),
span,
}));
}
let rhs = after[1..].trim().to_string();
let (value, end_line) = self.resolve_assign_rhs(&rhs, span)?;
Ok(Some(Stmt::Assign {
name,
value: parse_value_or_interp(rhs)?,
value,
span,
end_line,
}))
}
/// RHS on the same line, or empty RHS → following `$$` fence or table.
/// Returns `(expr, inclusive end_line)`.
fn resolve_assign_rhs(&mut self, rhs: &str, span: Span) -> Result<(Expr, u32)> {
let rhs = rhs.trim();
if rhs.is_empty() {
self.skip_blanks();
if self.peek_is_formula_fence() {
return self.consume_formula_fence(span);
}
let start_i = self.i;
let list = self.consume_table()?;
let end_line = if self.i > start_i {
self.lines[self.i - 1].line_no
} else {
span.line
};
return Ok((
Expr::List(list.into_iter().map(Expr::Literal).collect()),
end_line,
));
}
if let Some(expr) = try_parse_inline_formula(rhs)? {
return Ok((expr, span.line));
}
if rhs.starts_with('>') {
return Ok((Expr::Call(call_after_gt(rhs[1..].trim())?), span.line));
}
Ok((parse_value_or_interp(rhs)?, span.line))
}
fn skip_blanks(&mut self) {
while let Some(l) = self.peek() {
if l.kind == LineKind::Blank {
self.i += 1;
} else {
break;
}
}
}
fn peek_is_formula_fence(&self) -> bool {
self.peek()
.map(|l| l.text.trim().starts_with("$$"))
.unwrap_or(false)
}
fn consume_formula_fence(&mut self, span: Span) -> Result<(Expr, u32)> {
let open = self
.bump()
.ok_or_else(|| anyhow::anyhow!("{span}: expected `$$` formula fence"))?;
let open_line = open.line_no;
let trimmed = open.text.trim();
if trimmed.starts_with("$$:") || trimmed.starts_with("$$ name=") {
bail!(
"{open_line}:1: `$$:name` / `$$ name=` binding was removed; \
use `name` = then a `$$…$$` fence"
);
}
// Single-line: $$body$$
if trimmed.starts_with("$$") && trimmed.ends_with("$$") && trimmed.len() > 4 {
let body = trimmed[2..trimmed.len() - 2].trim();
if body.is_empty() {
bail!("{open_line}:1: empty formula");
}
let expr = crate::formula::parse(body)
.map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?;
return Ok((Expr::Formula(expr), open_line));
}
if trimmed != "$$" {
bail!(
"{open_line}:1: expected `$$` fence opener after empty assignment, got: {trimmed}"
);
}
let mut body_lines: Vec<String> = Vec::new();
let mut closed = false;
let mut end_line = open_line;
while let Some(l) = self.peek() {
if l.text.trim() == "$$" {
end_line = l.line_no;
self.bump();
closed = true;
break;
}
body_lines.push(l.text.clone());
self.bump();
}
if !closed {
bail!("{open_line}:1: unclosed formula fence `$$`");
}
let text = body_lines.join("\n").trim().to_string();
if text.is_empty() {
bail!("{open_line}:1: empty formula");
}
let expr = crate::formula::parse(&text)
.map_err(|e| anyhow::anyhow!("{open_line}:1: formula: {e}"))?;
Ok((Expr::Formula(expr), end_line))
}
fn consume_table(&mut self) -> Result<Vec<Literal>> {
self.skip_noise();
let mut rows = Vec::new();
@@ -416,33 +530,36 @@ impl<'a> Cursor<'a> {
}
}
fn parse_assign_or_expr_stmt(inner: &str, span: Span) -> Result<Stmt> {
fn split_assign_inner(inner: &str) -> Option<(String, String)> {
let inner = inner.trim();
// `` `name` = … ``
if let Some(rest) = inner.strip_prefix('`') {
if let Some(end) = rest.find('`') {
let name = rest[..end].to_string();
if crate::aliases::is_reserved_keyword(&name) {
bail!("{span}: `{name}` is a reserved keyword");
}
let after = rest[end + 1..].trim_start();
if let Some(rhs) = after.strip_prefix('=') {
let rhs = rhs.trim();
// Inline call assign: `> fn …`
let value = if rhs.starts_with('>') {
Expr::Call(call_after_gt(rhs[1..].trim())?)
} else {
parse_value_or_interp(rhs)?
};
return Ok(Stmt::Assign {
name,
value,
span,
});
}
}
let rest = inner.strip_prefix('`')?;
let end = rest.find('`')?;
let name = rest[..end].to_string();
let after = rest[end + 1..].trim_start();
let rhs = after.strip_prefix('=')?.trim().to_string();
Some((name, rhs))
}
/// Same-line `$$body$$` → Formula; otherwise None (caller parses normally).
fn try_parse_inline_formula(rhs: &str) -> Result<Option<Expr>> {
let rhs = rhs.trim();
if !rhs.starts_with("$$") {
return Ok(None);
}
bail!("{span}: italic statement must be an assignment (`name` = …)")
if rhs.starts_with("$$:") || rhs.starts_with("$$ name=") {
bail!(
"`$$:name` / `$$ name=` binding was removed; use `name` = then a `$$…$$` fence"
);
}
if rhs.ends_with("$$") && rhs.len() > 4 {
let body = rhs[2..rhs.len() - 2].trim();
if body.is_empty() {
bail!("empty formula");
}
let expr = crate::formula::parse(body).map_err(|e| anyhow::anyhow!("formula: {e}"))?;
return Ok(Some(Expr::Formula(expr)));
}
bail!("incomplete inline formula (expected `$$…$$` on one line)");
}
fn parse_param_line(trimmed: &str) -> Option<String> {
@@ -588,4 +705,24 @@ mod tests {
let main = &m.functions[0];
assert!(main.body.iter().any(|s| matches!(s, Stmt::Branch { .. })));
}
#[test]
fn parse_formula_assign_fence() {
let src = "# main\n\n`f` =\n$$\nx^2 - 2\n$$\n\n> print text=`f`\n";
let m = parse_source(src).unwrap();
let body = &m.functions[0].body;
match &body[0] {
Stmt::Assign {
name,
value: Expr::Formula(e),
end_line,
..
} => {
assert_eq!(name, "f");
assert_eq!(e.as_display(), "x^2 - 2");
assert!(*end_line > 3, "end_line should cover the fence, got {end_line}");
}
other => panic!("expected formula assign, got {other:?}"),
}
}
}
+14 -1
View File
@@ -2,16 +2,22 @@
use std::fmt;
use crate::formula::Expr as FormulaExpr;
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
None,
Bool(bool),
Int(i64),
/// Floating-point number (`type` → `num`).
Num(f64),
Text(String),
/// Single-column table rows (v0); multi-column later.
List(Vec<Value>),
/// JSON object / string-keyed map (insertion order).
Map(Vec<(String, Value)>),
/// Parsed symbolic expression (`type` → `formula`).
Formula(FormulaExpr),
}
impl Value {
@@ -20,9 +26,11 @@ impl Value {
Value::None => false,
Value::Bool(b) => *b,
Value::Int(n) => *n != 0,
Value::Num(n) => *n != 0.0 && !n.is_nan(),
Value::Text(s) => !s.is_empty(),
Value::List(xs) => !xs.is_empty(),
Value::Map(xs) => !xs.is_empty(),
Value::Formula(_) => true,
}
}
@@ -32,9 +40,14 @@ impl Value {
Value::Bool(true) => "True".into(),
Value::Bool(false) => "False".into(),
Value::Int(n) => n.to_string(),
Value::Num(n) => crate::formula::format_num(*n),
Value::Text(s) => s.clone(),
Value::List(_) => "<list>".into(),
Value::List(xs) => {
let parts: Vec<String> = xs.iter().map(|v| v.as_display()).collect();
format!("[{}]", parts.join(", "))
}
Value::Map(_) => "<map>".into(),
Value::Formula(e) => e.as_display(),
}
}
}
+178 -35
View File
@@ -169,12 +169,49 @@ a:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
opacity: 1;
font-weight: 500;
}
.nav-root { margin: 0; padding: 0; list-style: none; }
.folder {
margin: 0.55rem 0 0.2rem;
border: none;
}
.folder > summary {
list-style: none;
cursor: pointer;
user-select: none;
color: var(--muted);
font-size: 0.72rem;
margin: 1rem 0.35rem 0.35rem;
font-weight: 600;
letter-spacing: 0.01em;
padding: 0.35rem 0.45rem;
border-radius: 8px;
display: flex;
align-items: center;
gap: 0.35rem;
transition: background 0.12s ease, color 0.12s ease;
}
.folder > summary::-webkit-details-marker { display: none; }
.folder > summary::before {
content: "";
width: 0;
height: 0;
border-style: solid;
border-width: 4px 0 4px 6px;
border-color: transparent transparent transparent var(--muted);
opacity: 0.85;
transition: transform 0.12s ease;
flex-shrink: 0;
}
.folder[open] > summary::before {
transform: rotate(90deg);
}
.folder > summary:hover {
background: var(--hover);
color: var(--ink);
}
.folder > ul {
list-style: none;
padding: 0.1rem 0 0.15rem 0.55rem;
margin: 0;
}
.panel-wrap {
min-width: 0;
@@ -231,7 +268,7 @@ section.block > h2 {
}
.stdin-form label {
font-size: 0.85rem;
color: var(--text);
color: var(--ink);
}
.stdin-form .hint {
color: var(--muted);
@@ -243,10 +280,10 @@ section.block > h2 {
font-family: var(--mono);
font-size: 0.9rem;
padding: 0.65rem 0.75rem;
border: 1px solid var(--border);
border: 1px solid var(--line);
border-radius: 8px;
background: var(--surface);
color: var(--text);
color: var(--ink);
resize: vertical;
min-height: 4.5rem;
}
@@ -254,14 +291,19 @@ section.block > h2 {
justify-self: start;
font: inherit;
font-size: 0.9rem;
padding: 0.45rem 0.9rem;
border: 1px solid var(--border);
font-weight: 600;
padding: 0.5rem 1rem;
border: 1px solid var(--ink);
border-radius: 8px;
background: var(--text);
color: var(--bg);
background: var(--ink);
color: #ffffff;
cursor: pointer;
}
.stdin-form button:hover { opacity: 0.88; }
.stdin-form button:focus-visible {
outline: 2px solid var(--focus);
outline-offset: 2px;
}
.structure {
background: var(--surface);
border: 1px solid var(--line);
@@ -342,6 +384,38 @@ section.block > h2 {
color: var(--ink);
font-weight: 500;
}
.formula-card .math-block {
display: inline-block;
margin: 0.25rem 0 0.1rem 0.25rem;
vertical-align: middle;
overflow-x: auto;
max-width: 100%;
}
.formula-card .katex-display {
margin: 0.2rem 0;
}
.plots {
display: grid;
gap: 1rem;
margin-top: 1rem;
justify-items: center;
}
.plot {
overflow: auto;
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 0.75rem;
width: 100%;
display: flex;
justify-content: center;
}
.plot svg {
display: block;
max-width: 100%;
height: auto;
margin-inline: auto;
}
.comment-text {
color: var(--muted);
font-size: 0.92rem;
@@ -439,6 +513,7 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
<link rel="icon" href="https://s3.cflmy.cn/logo/Logo.ico" type="image/x-icon"/>
<link rel="shortcut icon" href="https://s3.cflmy.cn/logo/Logo.ico" type="image/x-icon"/>
<link rel="apple-touch-icon" href="https://s3.cflmy.cn/logo/Logo.png"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css" crossorigin="anonymous"/>
<style>{css}</style>
</head>
<body>
@@ -470,6 +545,9 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
</main>
</div>
</div>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js" crossorigin="anonymous"
onload="renderMathInElement(document.body,{{delimiters:[{{left:'$$',right:'$$',display:true}},{{left:'\\(',right:'\\)',display:false}}],ignoredTags:['script','noscript','style','textarea','pre','code','kbd']}});"></script>
</body>
</html>
"##,
@@ -481,23 +559,22 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
}
pub fn nav_html(files: &[PathBuf], active: Option<&str>, links: &LinkMode) -> String {
let mut out = String::from("<h2>Files</h2><ul>");
let mut last_folder = String::new();
let mut out = String::from("<h2>Files</h2>");
let mut last_folder: Option<String> = None;
for f in files {
let rel = f.to_string_lossy().replace('\\', "/");
let folder = Path::new(&rel)
.parent()
.map(|p| p.to_string_lossy().to_string())
.map(|p| p.to_string_lossy().replace('\\', "/"))
.unwrap_or_default();
if folder != last_folder {
if !folder.is_empty() {
out.push_str(&format!(
"</ul><div class=\"folder\">{}</div><ul>",
escape(&folder)
));
}
last_folder = folder;
if last_folder.as_deref() != Some(folder.as_str()) {
close_nav_group(&mut out, last_folder.as_deref());
open_nav_group(&mut out, &folder, active);
last_folder = Some(folder);
}
let name = Path::new(&rel)
.file_name()
.and_then(|s| s.to_str())
@@ -514,7 +591,8 @@ pub fn nav_html(files: &[PathBuf], active: Option<&str>, links: &LinkMode) -> St
escape(name)
));
}
out.push_str("</ul>");
close_nav_group(&mut out, last_folder.as_deref());
// index link for static pages
if matches!(links, LinkMode::Static { from: Some(_) }) {
let home = href_index(links);
@@ -529,6 +607,37 @@ pub fn nav_html(files: &[PathBuf], active: Option<&str>, links: &LinkMode) -> St
out
}
fn close_nav_group(out: &mut String, folder: Option<&str>) {
match folder {
None => {}
Some("") => out.push_str("</ul>"),
Some(_) => out.push_str("</ul></details>"),
}
}
fn open_nav_group(out: &mut String, folder: &str, active: Option<&str>) {
if folder.is_empty() {
out.push_str("<ul class=\"nav-root\">");
return;
}
let contains_active = active.is_some_and(|a| {
Path::new(a)
.parent()
.map(|p| p.to_string_lossy().replace('\\', "/") == folder)
.unwrap_or(false)
});
// Index (no active): keep folders open for browsing; else open only the active folder.
let open_attr = if active.is_none() || contains_active {
" open"
} else {
""
};
out.push_str(&format!(
"<details class=\"folder\"{open_attr}><summary>{}</summary><ul>",
escape(folder)
));
}
fn href_file(links: &LinkMode, target_rel: &str) -> String {
match links {
LinkMode::Live => format!("/file?path={}", urlencoding_encode(target_rel)),
@@ -620,27 +729,47 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
} else {
escape(&vm.stderr)
};
let stdin_panel = match links {
LinkMode::Live => format!(
r#"<form class="stdin-form" method="get" action="/file">
let stdin_panel = if vm.input_prompts.is_empty() {
String::new()
} else {
let placeholder = vm.input_prompts.join("\n");
let rows = vm.input_prompts.len().clamp(2, 8);
match links {
LinkMode::Live => {
let hint = if vm.input_prompts.iter().any(|p| !p.is_empty()) {
format!(
"prompts: {}",
escape(&vm.input_prompts.join(" · "))
)
} else {
"one line per <code>input</code>".into()
};
format!(
r#"<form class="stdin-form" method="get" action="/file">
<input type="hidden" name="path" value="{path}"/>
<label for="stdin">Preset input <span class="hint">one line per <code>input</code>; overrides frontmatter <code>stdin:</code> / <code>输入:</code></span></label>
<textarea id="stdin" name="stdin" rows="3" placeholder="Alice">{stdin}</textarea>
<label for="stdin">Preset input <span class="hint">{hint}</span></label>
<textarea id="stdin" name="stdin" rows="{rows}" placeholder="{placeholder}">{stdin}</textarea>
<button type="submit">Run with input</button>
</form>"#,
path = escape(rel),
stdin = escape(&vm.preset_stdin),
),
LinkMode::Static { .. } => {
if vm.preset_stdin.is_empty() {
String::new()
} else {
format!(
r#"<p class="hint">Demo stdin from frontmatter (static export cannot re-run interactively):</p>
<pre class="source" style="margin-bottom:0.75rem">{stdin}</pre>"#,
path = escape(rel),
hint = hint,
rows = rows,
placeholder = escape(&placeholder),
stdin = escape(&vm.preset_stdin),
)
}
LinkMode::Static { .. } => {
if vm.preset_stdin.is_empty() {
String::new()
} else {
format!(
r#"<p class="hint">Demo stdin (static export cannot re-run interactively); prompts: {prompts}</p>
<pre class="source" style="margin-bottom:0.75rem">{stdin}</pre>"#,
prompts = escape(&vm.input_prompts.join(" · ")),
stdin = escape(&vm.preset_stdin),
)
}
}
}
};
let title = Path::new(rel)
@@ -648,6 +777,18 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
.and_then(|s| s.to_str())
.unwrap_or(rel)
.trim_end_matches(".mq.md");
let plots_html = if vm.plots.is_empty() {
String::new()
} else {
let mut s = String::from(r#"<div class="plots">"#);
for svg in &vm.plots {
s.push_str(r#"<div class="plot">"#);
s.push_str(svg);
s.push_str("</div>");
}
s.push_str("</div>");
s
};
let main = format!(
r#"
<h1 class="page">{title}<span class="status-pill {status}">{status_label}</span></h1>
@@ -660,6 +801,7 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
<h2>Execution</h2>
{stdin_panel}
<div class="out {status}">{out}</div>
{plots}
</section>
<section class="block">
<h2>Source</h2>
@@ -673,6 +815,7 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
structure = vm.structure_html,
stdin_panel = stdin_panel,
out = out_text,
plots = plots_html,
source = escape(&vm.source),
);
layout(rel, &nav, &main)
+23 -8
View File
@@ -16,7 +16,7 @@ use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
use crate::input_feed::{effective_stdin, split_stdin_text};
use crate::view::html::{escape, page_file, page_index, LinkMode};
use crate::view::render::{render_module_structure, FileViewModel};
use crate::view::render::{collect_input_prompts, render_module_structure, FileViewModel};
use crate::{run_file_capture, RunOptions};
pub struct ViewOptions {
@@ -167,11 +167,18 @@ pub(crate) fn build_file_view(
live: bool,
) -> Result<FileViewModel> {
let source = fs::read_to_string(abs).with_context(|| format!("read {}", abs.display()))?;
let structure = match crate::load::load_module(abs) {
Ok(module) => render_module_structure(&module, &source),
Err(e) => format!(
"<div class=\"err\">parse/load error: {}</div>",
escape(&tidy_user_error(&format!("{e:#}"), abs, rel))
// Structure shows this file only — do not merge imported lib bodies into the tree.
let (structure, input_prompts) = match crate::parse::parse_source(&source) {
Ok(module) => (
render_module_structure(&module, &source),
collect_input_prompts(&module),
),
Err(e) => (
format!(
"<div class=\"err\">parse/load error: {}</div>",
escape(&tidy_user_error(&format!("{e:#}"), abs, rel))
),
Vec::new(),
),
};
let effective = effective_stdin(&source, stdin_lines);
@@ -181,12 +188,18 @@ pub(crate) fn build_file_view(
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) = match run_file_capture(abs, &opts) {
Ok(cap) => (cap.stdout, String::new(), true),
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(),
),
};
Ok(FileViewModel {
@@ -197,6 +210,8 @@ pub(crate) fn build_file_view(
stderr,
ok,
preset_stdin: effective.join("\n"),
input_prompts,
plots,
})
}
+1
View File
@@ -30,6 +30,7 @@ pub fn write_static(opts: OutputOptions) -> Result<()> {
vm.stdout.clear();
vm.stderr = "execution skipped (--no-exec)".into();
vm.ok = true;
vm.plots.clear();
}
let links = LinkMode::Static {
from: Some(rel.clone()),
+245 -8
View File
@@ -20,6 +20,123 @@ pub struct FileViewModel {
pub ok: bool,
/// Text shown in the live-view preset stdin box.
pub preset_stdin: String,
/// 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<String>,
/// SVG plots from math lib (embedded in Execution).
pub plots: Vec<String>,
}
/// Collect prompt strings from every `input` / `输入` call in the module (pre-order).
pub fn collect_input_prompts(module: &Module) -> Vec<String> {
let mut out = Vec::new();
for fun in &module.functions {
collect_input_prompts_fun(fun, &mut out);
}
out
}
fn collect_input_prompts_fun(fun: &Function, out: &mut Vec<String>) {
for stmt in &fun.body {
collect_input_prompts_stmt(stmt, out);
}
for child in &fun.children {
collect_input_prompts_fun(child, out);
}
}
fn collect_input_prompts_stmt(stmt: &Stmt, out: &mut Vec<String>) {
match stmt {
Stmt::Assign { value, .. } | Stmt::Return { value, .. } => {
collect_input_prompts_expr(value, out);
}
Stmt::Call { call, .. } => {
push_input_prompt(call, out);
for a in &call.args {
match a {
Arg::Positional(e) | Arg::Named { value: e, .. } => {
collect_input_prompts_expr(e, out);
}
}
}
}
Stmt::Branch { arms, .. } => {
for arm in arms {
if let Some(c) = &arm.condition {
collect_input_prompts_expr(c, out);
}
for s in &arm.body {
collect_input_prompts_stmt(s, out);
}
}
}
Stmt::While {
condition, body, ..
} => {
collect_input_prompts_expr(condition, out);
for s in body {
collect_input_prompts_stmt(s, out);
}
}
Stmt::ForEach { body, .. } => {
for s in body {
collect_input_prompts_stmt(s, out);
}
}
}
}
fn collect_input_prompts_expr(expr: &Expr, out: &mut Vec<String>) {
match expr {
Expr::Call(call) => {
push_input_prompt(call, out);
for a in &call.args {
match a {
Arg::Positional(e) | Arg::Named { value: e, .. } => {
collect_input_prompts_expr(e, out);
}
}
}
}
Expr::Unary { expr, .. } => collect_input_prompts_expr(expr, out),
Expr::Binary { left, right, .. } => {
collect_input_prompts_expr(left, out);
collect_input_prompts_expr(right, out);
}
Expr::List(items) => {
for e in items {
collect_input_prompts_expr(e, out);
}
}
Expr::Literal(_) | Expr::Var(_) | Expr::Interp(_) | Expr::Formula(_) => {}
}
}
fn push_input_prompt(call: &CallExpr, out: &mut Vec<String>) {
if crate::aliases::canonical_builtin(&call.callee) != Some("input") {
return;
}
for a in &call.args {
if let Arg::Named { name, value } = a {
if crate::aliases::canonical_param("input", name) == "prompt" {
out.push(prompt_expr_text(value));
return;
}
}
}
if let Some(Arg::Positional(value)) = call.args.first() {
out.push(prompt_expr_text(value));
return;
}
out.push(String::new());
}
fn prompt_expr_text(expr: &Expr) -> String {
match expr {
Expr::Literal(Literal::Text(t)) => t.clone(),
Expr::Literal(lit) => lit_display(lit),
other => expr_display(other),
}
}
pub fn render_module_structure(module: &Module, source: &str) -> String {
@@ -209,9 +326,8 @@ fn stmt_start(stmt: &Stmt) -> u32 {
fn stmt_end_line(stmt: &Stmt) -> u32 {
match stmt {
Stmt::Assign { span, .. } | Stmt::Return { span, .. } | Stmt::Call { span, .. } => {
span.line + 1
}
Stmt::Assign { end_line, .. } => end_line + 1,
Stmt::Return { span, .. } | Stmt::Call { span, .. } => span.line + 1,
Stmt::Branch { arms, span, .. } => {
let mut end = span.line + 1;
for arm in arms {
@@ -234,11 +350,25 @@ fn stmt_end_line(stmt: &Stmt) -> u32 {
fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine]) -> (String, u32) {
let end = stmt_end_line(stmt);
let html = match stmt {
Stmt::Assign { name, value, .. } => format!(
"<div class=\"card\"><span class=\"badge\">bind</span><code class=\"expr\">`{}` = {}</code></div>",
escape(name),
escape(&expr_display(value))
),
Stmt::Assign {
name,
value: Expr::Formula(e),
..
} => {
let tex = escape(&formula_ascii_to_tex(&e.as_display()));
format!(
"<div class=\"card formula-card\"><span class=\"badge\">formula</span> \
<code class=\"expr\">`{}` =</code> \
<div class=\"math-block\">$${}$$</div></div>",
escape(name),
tex
)
}
Stmt::Assign { name, value, .. } => format!(
"<div class=\"card\"><span class=\"badge\">bind</span> <code class=\"expr\">`{}` = {}</code></div>",
escape(name),
escape(&expr_display(value))
),
Stmt::Return { value, .. } => format!(
"<div class=\"card ret-card\"><span class=\"badge\">return</span><code class=\"expr\">{}</code></div>",
escape(&expr_display(value))
@@ -388,9 +518,67 @@ fn expr_prec(expr: &Expr, parent_prec: u8) -> String {
let parts: Vec<String> = items.iter().map(|e| expr_prec(e, 0)).collect();
format!("[{}]", parts.join(", "))
}
Expr::Formula(e) => format!("$$ {} $$", e.as_display()),
}
}
/// Best-effort ASCII formula → TeX for KaTeX in view Structure.
fn formula_ascii_to_tex(ascii: &str) -> String {
let mut out = String::new();
let chars: Vec<char> = ascii.chars().collect();
let mut i = 0usize;
while i < chars.len() {
let c = chars[i];
if c == '*' {
// multiplication: a*b → a \cdot b
out.push_str(r" \cdot ");
i += 1;
continue;
}
if c == '^' {
out.push('^');
i += 1;
if i < chars.len() && chars[i] == '(' {
out.push('{');
i += 1;
let start = i;
let mut depth = 1i32;
while i < chars.len() && depth > 0 {
match chars[i] {
'(' => depth += 1,
')' => depth -= 1,
_ => {}
}
if depth > 0 {
i += 1;
}
}
out.push_str(&chars[start..i].iter().collect::<String>());
if i < chars.len() && chars[i] == ')' {
i += 1;
}
out.push('}');
} else if i < chars.len() {
out.push('{');
out.push(chars[i]);
out.push('}');
i += 1;
}
continue;
}
// TeX specials that may appear in identifiers rarely
match c {
'{' | '}' | '%' | '&' | '#' | '$' => {
out.push('\\');
out.push(c);
}
_ => out.push(c),
}
i += 1;
}
out
}
fn wrap(inner: String, prec: u8, parent_prec: u8) -> String {
if prec < parent_prec {
format!("({inner})")
@@ -476,4 +664,53 @@ mod tests {
assert!(html.contains("<code>code</code>"), "{html}");
assert!(!html.contains("[仓库](https://github.com/cflmy/marqdo)"));
}
#[test]
fn collect_input_prompts_from_fixture() {
let src = include_str!("../../tests/keywords/input.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let prompts = collect_input_prompts(&module);
assert_eq!(prompts, vec!["Name:".to_string()]);
}
#[test]
fn collect_input_prompts_absent_without_input() {
let src = include_str!("../../tests/structure/hello.mq.md");
let module = crate::parse::parse_source(src).unwrap();
assert!(collect_input_prompts(&module).is_empty());
}
#[test]
fn structure_omits_imported_lib_bodies() {
let src = "---\ntitle: t\n> lib/text.mq.md\n---\n\n# main\n\n> print text=hi\n";
let local = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&local, src);
assert!(html.contains("badge\">import"), "{html}");
assert!(html.contains("lib/text.mq.md"), "{html}");
assert!(html.contains("main"), "{html}");
assert!(!html.contains("trim"), "{html}");
assert_eq!(local.functions.len(), 1);
assert_eq!(local.functions[0].name, "main");
}
#[test]
fn structure_formula_assign_not_comment() {
let src = include_str!("../../tests/lib/math-formula.mq.md");
let module = crate::parse::parse_source(src).unwrap();
let html = render_module_structure(&module, src);
assert!(html.contains("badge\">formula"), "{html}");
assert!(html.contains("math-block"), "{html}");
assert!(html.contains("$$"), "{html}");
assert!(
!html.contains("comment-text\">x^2 - 2")
&& !html.contains("comment-text\"><p>x^2 - 2"),
"formula fence leaked into comments: {html}"
);
}
#[test]
fn formula_ascii_to_tex_pow_and_mul() {
assert_eq!(formula_ascii_to_tex("x^2 - 2"), "x^{2} - 2");
assert_eq!(formula_ascii_to_tex("2*x"), r"2 \cdot x");
}
}
+57
View File
@@ -543,6 +543,12 @@ fn view_output_writes_html() {
assert!(index.contains("#ffffff") || index.contains("--surface: #ffffff"));
assert!(index.contains("nav-toggle"));
assert!(!index.contains("Run with input"), "static export should omit live stdin form");
let page = std::fs::read_to_string(dir.join("pages").join("hello.mq.md.html")).unwrap();
assert!(page.contains("katex.min.css"), "view layout should load KaTeX");
assert!(
!page.contains("name=\"stdin\""),
"hello has no input; no preset form"
);
assert!(dir.join("pages").join("hello.mq.md.html").exists());
}
@@ -579,6 +585,57 @@ fn lib_net_encode() {
assert_out("tests/lib/net-encode.mq.md", "a+b");
}
#[test]
fn lib_math_formula() {
assert_out(
"tests/lib/math-formula.mq.md",
"formula\n2*x\n[-1.4142135624, 1.4142135624]\n7",
);
}
#[test]
fn lib_math_formula_chain() {
assert_out(
"tests/lib/math-formula-chain.mq.md",
"formula\n3*2*x\n12",
);
}
#[test]
fn lib_math_random() {
assert_out("tests/lib/math-random.mq.md", "4\n7\n4");
}
#[test]
fn lib_math_zh_num() {
assert_out("tests/lib/数学-数值.mq.md", "num\n0");
}
#[test]
fn lib_math_plot() {
let path = "tests/lib/math-plot.mq.md";
let (code, stdout, stderr) = run(&["run", path]);
assert_eq!(code, 0, "{path} stderr={stderr}");
assert!(
stdout.lines().next() == Some("text"),
"{path} stdout={stdout}"
);
assert!(
stdout.contains("plot:"),
"{path} missing plot: line in {stdout}"
);
let _ = std::fs::remove_file("tests/lib/math-plot-plot-1.svg");
}
#[test]
fn bytecode_lib_math_formula() {
assert_out_backend(
"tests/lib/math-formula.mq.md",
"bytecode",
"formula\n2*x\n[-1.4142135624, 1.4142135624]\n7",
);
}
#[test]
fn bytecode_lib_json() {
assert_out_backend(
+25
View File
@@ -0,0 +1,25 @@
---
title: math formula chain
> lib/math.mq.md
---
# main
`f` =
$$
x^3
$$
*`df` = > diff formula=`f` var=x *
*`ty` = > type `df` *
> print text=`ty`
*`df2` = > diff formula=`df` var=x *
> print text=`df2`
*`y` = > eval formula=`df` var=x value=2 *
> print text=`y`
+27
View File
@@ -0,0 +1,27 @@
---
title: math formula pipeline
> lib/math.mq.md
---
# main
`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`
+17
View File
@@ -0,0 +1,17 @@
---
title: math plot svg
> lib/math.mq.md
---
# main
`f` =
$$
x^2
$$
*`svg` = > plot formula=`f` var=x min=-2 max=2 *
*`ok` = > type `svg` *
> print text=`ok`
+22
View File
@@ -0,0 +1,22 @@
---
title: math random seed
> lib/math.mq.md
---
# main
> seed value=42
*`a` = > random_int min=1 max=10 *
*`b` = > random_int min=1 max=10 *
> seed value=42
*`c` = > random_int min=1 max=10 *
> print text=`a`
> print text=`b`
> print text=`c`
+16
View File
@@ -0,0 +1,16 @@
---
title: math num + zh
> lib/数学.mq.md
---
# main
*`p` = > 圆周率 *
*`t` = > type `p` *
> print text=`t`
*`s` = > 正弦 value=0 *
> print text=`s`