schala/schala-lang/src/ast_reducing.rs

90 lines
1.9 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-10 23:41:51 -07:00
impl AST {
pub fn reduce(&self) -> Result<ReducedAST, String> {
use parsing::Statement::*;
let mut output = vec![];
for statement in self.0.iter() {
match statement {
&ExpressionStatement(ref expr) => output.push(expr.reduce()?),
&Declaration(ref decl) => output.push(decl.reduce()?),
}
2018-05-09 02:49:49 -07:00
}
2018-05-10 23:41:51 -07:00
Ok(ReducedAST(output))
2018-05-09 02:49:49 -07:00
}
}
2018-05-09 02:27:57 -07:00
2018-05-10 23:41:51 -07:00
impl Expression {
fn reduce(&self) -> Result<Stmt, String> {
use parsing::ExpressionType::*;
let ref input = self.0;
let output_expr = match input {
&IntLiteral(ref n) => Expr::Lit(Lit::Int(*n)),
&FloatLiteral(ref f) => Expr::Lit(Lit::Float(*f)),
&StringLiteral(ref s) => Expr::Lit(Lit::StringLit(s.clone())),
&BoolLiteral(ref b) => Expr::Lit(Lit::Bool(*b)),
&BinExp(ref binop, ref lhs, ref rhs) => binop.reduce(lhs, rhs)?,
&PrefixExp(ref op, ref arg) => op.reduce(arg)?,
e => return Err(format!("{:?} not implemented in reduction", e))
};
Ok(Stmt::Expr(output_expr))
}
2018-05-09 02:49:49 -07:00
}
2018-05-10 23:41:51 -07:00
impl Declaration {
fn reduce(&self) -> Result<Stmt, String> {
Ok(Stmt::Expr(Expr::Lit(Lit::Int(0))))
}
2018-05-09 02:27:57 -07:00
}
2018-05-09 17:02:10 -07:00
2018-05-10 23:41:51 -07:00
impl BinOp {
fn reduce(&self, lhs: &Box<Expression>, rhs: &Box<Expression>) -> Result<Expr, String> {
2018-05-09 17:02:10 -07:00
Err(format!("NOTDONE"))
2018-05-10 23:41:51 -07:00
}
2018-05-09 17:02:10 -07:00
}
2018-05-10 23:41:51 -07:00
impl PrefixOp {
fn reduce(&self, arg: &Box<Expression>) -> Result<Expr, String> {
2018-05-09 17:02:10 -07:00
Err(format!("NOTDONE"))
2018-05-10 23:41:51 -07:00
}
2018-05-09 17:02:10 -07:00
}