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 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),
|
|
|
|
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)),
|
|
|
|
&StringLiteral(ref s) => Expr::Lit(Lit::StringLit(s.clone())),
|
|
|
|
&BoolLiteral(ref b) => Expr::Lit(Lit::Bool(*b)),
|
|
|
|
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
|
|
|
}
|