3个不稳定版本
0.2.0 | 2023年6月12日 |
---|---|
0.1.1 | 2023年5月30日 |
0.1.0 | 2023年5月17日 |
在过程宏中排名第1413
每月下载量33次
17KB
319 行
astmaker
在Rust中快速构建抽象语法树和遍历模型。
示例
此示例创建了一个简单数学表达式的AST和一个解释器来评估结果
use astmaker::{ast, model};
#[derive(Debug, Clone, PartialEq)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
}
#[derive(Debug, Clone, PartialEq)]
pub enum UnOp {
Add,
Sub,
}
ast!{
location = ();
pub node Expression =
| BinOp -> Node<BinaryOperation>
| UnOp -> Node<UnaryOperation>
| Num -> Node<Number>
;
pub node BinaryOperation = {
lhs: Node<Expression>,
op: BinOp,
rhs: Node<Expression>,
}
pub node UnaryOperation = {
op: UnOp,
expr: Node<Expression>,
}
pub node Number = {
value: f64,
}
}
pub struct Interpreter;
model!{
impl Interpreter -> f64 {
where Expression => {
match node.data.as_mut() {
Expression::BinOp(child_node) => context.visit(child_node),
Expression::UnOp(child_node) => context.visit(child_node),
Expression::Num(child_node) => context.visit(child_node),
}
},
where BinaryOperation => {
let lhs = context.visit(&mut node.data.lhs);
let rhs = context.visit(&mut node.data.rhs);
match node.data.op {
BinOp::Add => lhs + rhs,
BinOp::Sub => lhs - rhs,
BinOp::Mul => lhs * rhs,
BinOp::Div => lhs / rhs,
}
},
where UnaryOperation => {
let val = context.visit(&mut node.data.expr);
match node.data.op {
UnOp::Add => val,
UnOp::Sub => -val,
}
},
where Number => node.data.value,
}
}
#[test]
fn eval() {
let mut tree = Node::new((), Expression::BinOp(
Node::new((), BinaryOperation {
lhs: Node::new((), Expression::Num(
Node::new((), Number { value: 1.0 })
)),
op: BinOp::Add,
rhs: Node::new((), Expression::Num(
Node::new((), Number { value: 2.0 })
))
})
));
let mut interpreter = Interpreter;
assert_eq!(interpreter.visit(&mut tree), 3.0);
}
路线图
- 📝 文档
- ✨ 泛型支持
- ✨ 生命周期支持
- 👷 Github工作流程用于构建、测试和发布crate
授权
本项目按照MIT许可证授权。
依赖项
~310–770KB
~18K SLoC