use std::rc::Rc; use crate::ast::*; use crate::symbol_table::{Symbol, SymbolSpec, SymbolTable}; use crate::builtin::{BinOp, PrefixOp}; #[derive(Debug)] pub struct ReducedAST(pub Vec); #[derive(Debug, Clone)] pub enum Stmt { PreBinding { name: Rc, func: Func, }, Binding { name: Rc, constant: bool, expr: Expr, }, Expr(Expr), Noop, } #[derive(Debug, Clone)] pub enum Expr { Unit, Lit(Lit), Tuple(Vec), Func(Func), Val(Rc), Constructor { type_name: Rc, name: Rc, tag: usize, arity: usize, }, Call { f: Box, args: Vec, }, Assign { val: Box, expr: Box, }, Conditional { cond: Box, then_clause: Vec, else_clause: Vec, }, ConditionalTargetSigilValue, CaseMatch { cond: Box, alternatives: Vec }, UnimplementedSigilValue } pub type BoundVars = Vec>>; //remember that order matters here #[derive(Debug, Clone)] pub struct Alternative { pub tag: Option, pub subpatterns: Vec>, pub guard: Option, pub bound_vars: BoundVars, pub item: Vec, } #[derive(Debug, Clone)] pub struct Subpattern { pub tag: Option, pub subpatterns: Vec>, pub bound_vars: BoundVars, pub guard: Option, } #[derive(Debug, Clone)] pub enum Lit { Nat(u64), Int(i64), Float(f64), Bool(bool), StringLit(Rc), } #[derive(Debug, Clone)] pub enum Func { BuiltIn(Rc), UserDefined { name: Option>, params: Vec>, body: Vec, } } impl AST { pub fn reduce(&self, symbol_table: &SymbolTable) -> ReducedAST { let mut output = vec![]; for statement in self.0.iter() { output.push(statement.node().reduce(symbol_table)); } ReducedAST(output) } } impl Statement { fn reduce(&self, symbol_table: &SymbolTable) -> Stmt { use crate::ast::Statement::*; match self { ExpressionStatement(expr) => Stmt::Expr(expr.node().reduce(symbol_table)), Declaration(decl) => decl.reduce(symbol_table), } } } fn reduce_block(block: &Block, symbol_table: &SymbolTable) -> Vec { block.iter().map(|stmt| stmt.node().reduce(symbol_table)).collect() } impl Expression { fn reduce(&self, symbol_table: &SymbolTable) -> Expr { use crate::ast::ExpressionType::*; let ref input = self.0; match input { NatLiteral(n) => Expr::Lit(Lit::Nat(*n)), FloatLiteral(f) => Expr::Lit(Lit::Float(*f)), StringLiteral(s) => Expr::Lit(Lit::StringLit(s.clone())), BoolLiteral(b) => Expr::Lit(Lit::Bool(*b)), BinExp(binop, lhs, rhs) => binop.reduce(symbol_table, lhs, rhs), PrefixExp(op, arg) => op.reduce(symbol_table, arg), Value(name) => match symbol_table.lookup_by_name(name) { Some(Symbol { spec: SymbolSpec::DataConstructor { index, type_args, type_name}, .. }) => Expr::Constructor { type_name: type_name.clone(), name: name.clone(), tag: index.clone(), arity: type_args.len(), }, _ => Expr::Val(name.clone()), }, Call { f, arguments } => Expr::Call { f: Box::new(f.reduce(symbol_table)), args: arguments.iter().map(|arg| arg.node().reduce(symbol_table)).collect(), }, TupleLiteral(exprs) => Expr::Tuple(exprs.iter().map(|e| e.node().reduce(symbol_table)).collect()), IfExpression { discriminator, body } => reduce_if_expression(discriminator, body, symbol_table), Lambda { params, body, .. } => reduce_lambda(params, body, symbol_table), NamedStruct { .. } => Expr::UnimplementedSigilValue, Index { .. } => Expr::UnimplementedSigilValue, WhileExpression { .. } => Expr::UnimplementedSigilValue, ForExpression { .. } => Expr::UnimplementedSigilValue, ListLiteral { .. } => Expr::UnimplementedSigilValue, } } } fn reduce_lambda(params: &Vec, body: &Block, symbol_table: &SymbolTable) -> Expr { Expr::Func(Func::UserDefined { name: None, params: params.iter().map(|param| param.0.clone()).collect(), body: reduce_block(body, symbol_table), }) } fn reduce_if_expression(discriminator: &Discriminator, body: &IfExpressionBody, symbol_table: &SymbolTable) -> Expr { let cond = Box::new(match *discriminator { Discriminator::Simple(ref expr) => expr.reduce(symbol_table), Discriminator::BinOp(ref _expr, ref _binop) => panic!("Can't yet handle binop discriminators") }); match *body { IfExpressionBody::SimpleConditional(ref then_clause, ref else_clause) => { let then_clause = reduce_block(then_clause, symbol_table); let else_clause = match else_clause { None => vec![], Some(stmts) => reduce_block(stmts, symbol_table), }; Expr::Conditional { cond, then_clause, else_clause } }, IfExpressionBody::SimplePatternMatch(ref pat, ref then_clause, ref else_clause) => { let then_clause = reduce_block(then_clause, symbol_table); let else_clause = match else_clause { None => vec![], Some(stmts) => reduce_block(stmts, symbol_table), }; let alternatives = vec![ pat.to_alternative(then_clause, symbol_table), Alternative { tag: None, subpatterns: vec![], bound_vars: vec![], guard: None, item: else_clause }, ]; Expr::CaseMatch { cond, alternatives, } }, IfExpressionBody::GuardList(ref guard_arms) => { let mut alternatives = vec![]; for arm in guard_arms { match arm.guard { Guard::Pat(ref p) => { let item = reduce_block(&arm.body, symbol_table); let alt = p.to_alternative(item, symbol_table); alternatives.push(alt); }, Guard::HalfExpr(HalfExpr { op: _, expr: _ }) => { return Expr::UnimplementedSigilValue } } } Expr::CaseMatch { cond, alternatives } } } } /* ig var pat * x is SomeBigOldEnum(_, x, Some(t)) */ fn handle_symbol(symbol: Option<&Symbol>, inner_patterns: &Vec, symbol_table: &SymbolTable) -> Subpattern { use self::Pattern::*; let tag = symbol.map(|symbol| match symbol.spec { SymbolSpec::DataConstructor { index, .. } => index.clone(), _ => panic!("Symbol is not a data constructor - this should've been caught in type-checking"), }); let bound_vars = inner_patterns.iter().map(|p| match p { Literal(PatternLiteral::VarPattern(var)) => Some(var.clone()), _ => None, }).collect(); let subpatterns = inner_patterns.iter().map(|p| match p { Ignored => None, Literal(PatternLiteral::VarPattern(_)) => None, Literal(other) => Some(other.to_subpattern(symbol_table)), tp @ TuplePattern(_) => Some(tp.to_subpattern(symbol_table)), ts @ TupleStruct(_, _) => Some(ts.to_subpattern(symbol_table)), Record(..) => unimplemented!(), }).collect(); let guard = None; /* let guard_equality_exprs: Vec = subpatterns.iter().map(|p| match p { Literal(lit) => match lit { _ => unimplemented!() }, _ => unimplemented!() }).collect(); */ Subpattern { tag, subpatterns, guard, bound_vars, } } impl Pattern { fn to_alternative(&self, item: Vec, symbol_table: &SymbolTable) -> Alternative { let s = self.to_subpattern(symbol_table); Alternative { tag: s.tag, subpatterns: s.subpatterns, bound_vars: s.bound_vars, guard: s.guard, item } } fn to_subpattern(&self, symbol_table: &SymbolTable) -> Subpattern { use self::Pattern::*; match self { TupleStruct(name, inner_patterns) => { let symbol = symbol_table.lookup_by_name(name).expect(&format!("Symbol {} not found", name)); handle_symbol(Some(symbol), inner_patterns, symbol_table) }, TuplePattern(inner_patterns) => handle_symbol(None, inner_patterns, symbol_table), Record(_name, _pairs) => { unimplemented!() }, Ignored => Subpattern { tag: None, subpatterns: vec![], guard: None, bound_vars: vec![] }, Literal(lit) => lit.to_subpattern(symbol_table), } } } impl PatternLiteral { fn to_subpattern(&self, symbol_table: &SymbolTable) -> Subpattern { use self::PatternLiteral::*; match self { NumPattern { neg, num } => { let comparison = Expr::Lit(match (neg, num) { (false, ExpressionType::NatLiteral(n)) => Lit::Nat(*n), (false, ExpressionType::FloatLiteral(f)) => Lit::Float(*f), (true, ExpressionType::NatLiteral(n)) => Lit::Int(-1*(*n as i64)), (true, ExpressionType::FloatLiteral(f)) => Lit::Float(-1.0*f), _ => panic!("This should never happen") }); let guard = Some(Expr::Call { f: Box::new(Expr::Func(Func::BuiltIn(Rc::new("==".to_string())))), args: vec![comparison, Expr::ConditionalTargetSigilValue], }); Subpattern { tag: None, subpatterns: vec![], guard, bound_vars: vec![], } }, StringPattern(s) => { let guard = Some(Expr::Call { f: Box::new(Expr::Func(Func::BuiltIn(Rc::new("==".to_string())))), args: vec![Expr::Lit(Lit::StringLit(s.clone())), Expr::ConditionalTargetSigilValue] }); Subpattern { tag: None, subpatterns: vec![], guard, bound_vars: vec![], } }, BoolPattern(b) => { let guard = Some(if *b { Expr::ConditionalTargetSigilValue } else { Expr::Call { f: Box::new(Expr::Func(Func::BuiltIn(Rc::new("!".to_string())))), args: vec![Expr::ConditionalTargetSigilValue] } }); Subpattern { tag: None, subpatterns: vec![], guard, bound_vars: vec![], } }, VarPattern(var) => match symbol_table.lookup_by_name(var) { Some(symbol) => handle_symbol(Some(symbol), &vec![], symbol_table), None => Subpattern { tag: None, subpatterns: vec![], guard: None, bound_vars: vec![Some(var.clone())], } } } } } impl Declaration { fn reduce(&self, symbol_table: &SymbolTable) -> Stmt { use self::Declaration::*; use crate::ast::Signature; match self { Binding {name, constant, expr, .. } => Stmt::Binding { name: name.clone(), constant: *constant, expr: expr.reduce(symbol_table) }, FuncDecl(Signature { name, params, .. }, statements) => Stmt::PreBinding { name: name.clone(), func: Func::UserDefined { name: Some(name.clone()), params: params.iter().map(|param| param.0.clone()).collect(), body: reduce_block(&statements, symbol_table), } }, TypeDecl { .. } => Stmt::Noop, TypeAlias(_, _) => Stmt::Noop, Interface { .. } => Stmt::Noop, Impl { .. } => Stmt::Expr(Expr::UnimplementedSigilValue), _ => Stmt::Expr(Expr::UnimplementedSigilValue) } } } impl BinOp { fn reduce(&self, symbol_table: &SymbolTable, lhs: &Box>, rhs: &Box>) -> Expr { if **self.sigil() == "=" { Expr::Assign { val: Box::new(lhs.node().reduce(symbol_table)), expr: Box::new(rhs.node().reduce(symbol_table)), } } else { let f = Box::new(Expr::Func(Func::BuiltIn(self.sigil().clone()))); Expr::Call { f, args: vec![lhs.node().reduce(symbol_table), rhs.node().reduce(symbol_table)]} } } } impl PrefixOp { fn reduce(&self, symbol_table: &SymbolTable, arg: &Box>) -> Expr { let f = Box::new(Expr::Func(Func::BuiltIn(self.sigil().clone()))); Expr::Call { f, args: vec![arg.node().reduce(symbol_table)]} } }