AST 中间表示
AST 是 SciExpr 的核心 IR。输入统一解析为 AST,输出从 AST 渲染。
节点类型
顶层
typescript
interface ExpressionRoot {
kind: 'root'
type: ExpressionKind // math | molecule | chemical-equation | matrix | text | mixed
children: ExpressionNode[]
}数学 (9 种)
| 节点 | kind | LaTeX |
|---|---|---|
| 分数 | frac | \frac{1}{2} |
| 上下标 | script | x^2, x_i |
| 根式 | radical | \sqrt{x} |
| 定界符 | delimiter | (x), [x] |
| 符号 | symbol | \alpha, \infty |
| 矩阵 | matrix | \begin{pmatrix} |
| 重音 | accent | \hat{x} |
| 大运算符 | largeop | \sum, \int |
| 颜色 | color | \color{red}{x} |
化学 (4 种)
| 节点 | kind |
|---|---|
| 元素 | chem-element |
| 化学键 | chem-bond |
| 反应式 | chem-reaction |
| 基团 | chem-group |
遍历
typescript
import { traverseAST, collectNodes } from '@sciexpr/core'
traverseAST(root, {
visitSymbol(node) { console.log(node.value) },
visitDefault(node) { console.log(node.kind) },
})
const symbols = collectNodes(root, n => n.kind === 'symbol')序列化
typescript
import { serializeAST, deserializeAST } from '@sciexpr/core'
const json = serializeAST(root)
const ast = deserializeAST(json)