schala/schala-lang/src/ast_reducing.rs

79 lines
1.8 KiB
Rust
Raw Normal View History

2018-05-09 02:27:57 -07:00
use std::rc::Rc;
2018-05-09 02:02:17 -07:00
2018-05-09 02:49:49 -07:00
use parsing::{AST, Expression, Declaration};
2018-05-09 17:02:10 -07:00
use builtin::{BinOp, PrefixOp};
2018-05-09 02:27:57 -07:00
2018-05-09 02:49:49 -07:00
#[derive(Debug)]
2018-05-09 02:27:57 -07:00
pub struct ReducedAST(pub Vec<Stmt>);
2018-05-09 02:49:49 -07:00
#[derive(Debug)]
2018-05-09 02:27:57 -07:00
pub enum Stmt {
Binding {
name: Rc<String>,
expr: Expr,
},
Expr(Expr),
}
2018-05-09 02:49:49 -07:00
#[derive(Debug)]
2018-05-09 02:27:57 -07:00
pub enum Expr {
2018-05-09 03:04:01 -07:00
Lit(Lit),
2018-05-09 02:27:57 -07:00
Func(Func),
Call {
f: Func,
args: Vec<Expr>,
},
}
2018-05-09 02:49:49 -07:00
#[derive(Debug)]
2018-05-09 02:27:57 -07:00
pub enum Lit {
Int(u64),
2018-05-09 17:02:10 -07:00
Float(f64),
2018-05-09 02:27:57 -07:00
Bool(bool),
StringLit(Rc<String>),
}
2018-05-09 02:49:49 -07:00
#[derive(Debug)]
2018-05-09 02:27:57 -07:00
pub struct Func {
params: Vec<Rc<String>>,
body: Vec<Stmt>,
}
2018-05-09 02:49:49 -07:00
pub fn perform_ast_reduction(ast: &AST) -> Result<ReducedAST, String> {
use parsing::Statement::*;
let mut output = vec![];
for statement in ast.0.iter() {
match statement {
&ExpressionStatement(ref expr) => output.push(reduce_expr(expr)?),
&Declaration(ref decl) => output.push(reduce_decl(decl)?),
}
}
Ok(ReducedAST(output))
}
2018-05-09 02:27:57 -07:00
2018-05-09 02:49:49 -07:00
fn reduce_expr(expr: &Expression) -> Result<Stmt, String> {
2018-05-09 03:04:01 -07:00
use parsing::ExpressionType::*;
let ref input = expr.0;
let output_expr = match input {
&IntLiteral(ref n) => Expr::Lit(Lit::Int(*n)),
2018-05-09 17:02:10 -07:00
&FloatLiteral(ref f) => Expr::Lit(Lit::Float(*f)),
2018-05-09 03:04:01 -07:00
&StringLiteral(ref s) => Expr::Lit(Lit::StringLit(s.clone())),
&BoolLiteral(ref b) => Expr::Lit(Lit::Bool(*b)),
2018-05-09 17:02:10 -07:00
&BinExp(ref binop, ref lhs, ref rhs) => reduce_binop(binop, lhs, rhs)?,
&PrefixExp(ref op, ref arg) => reduce_prefix(op, arg)?,
2018-05-09 03:04:01 -07:00
e => return Err(format!("{:?} not implemented in reduction", e))
};
Ok(Stmt::Expr(output_expr))
2018-05-09 02:49:49 -07:00
}
fn reduce_decl(expr: &Declaration) -> Result<Stmt, String> {
2018-05-09 03:04:01 -07:00
Ok(Stmt::Expr(Expr::Lit(Lit::Int(0))))
2018-05-09 02:27:57 -07:00
}
2018-05-09 17:02:10 -07:00
fn reduce_binop(binop: &BinOp, lhs: &Box<Expression>, rhs: &Box<Expression>) -> Result<Expr, String> {
Err(format!("NOTDONE"))
}
fn reduce_prefix(op: &PrefixOp, arg: &Box<Expression>) -> Result<Expr, String> {
Err(format!("NOTDONE"))
}