A fairly major refactor / simplification.
This commit is contained in:
49
src/syntax/simplify.rs
Normal file
49
src/syntax/simplify.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use crate::syntax::ast::{Program, Statement, Expression};
|
||||
|
||||
impl Program {
|
||||
pub fn simplify(mut self) -> Self {
|
||||
let mut new_statements = Vec::new();
|
||||
let mut gensym_index = 1;
|
||||
|
||||
for stmt in self.statements.drain(..) {
|
||||
match stmt {
|
||||
Statement::Print(_, _) => new_statements.push(stmt),
|
||||
Statement::Binding(_, _, Expression::Reference(_, _)) => new_statements.push(stmt),
|
||||
Statement::Binding(_, _, Expression::Value(_, _)) => new_statements.push(stmt),
|
||||
Statement::Binding(loc, name, value) => {
|
||||
let (mut prereqs, new_value) = value.rebind(&name, &mut gensym_index);
|
||||
new_statements.append(&mut prereqs);
|
||||
new_statements.push(Statement::Binding(loc, name, new_value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.statements = new_statements;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Expression {
|
||||
fn rebind(self, base_name: &str, gensym_index: &mut usize) -> (Vec<Statement>, Expression) {
|
||||
match self {
|
||||
Expression::Value(_, _) => (vec![], self),
|
||||
Expression::Reference(_, _) => (vec![], self),
|
||||
Expression::Primitive(loc, prim, mut expressions) => {
|
||||
let mut prereqs = Vec::new();
|
||||
let mut new_exprs = Vec::new();
|
||||
|
||||
for expr in expressions.drain(..) {
|
||||
let (mut cur_prereqs, arg) = expr.rebind(base_name, gensym_index);
|
||||
prereqs.append(&mut cur_prereqs);
|
||||
new_exprs.push(arg);
|
||||
}
|
||||
|
||||
let new_name = format!("<{}:{}>", base_name, *gensym_index);
|
||||
*gensym_index += 1;
|
||||
prereqs.push(Statement::Binding(loc.clone(), new_name.clone(), Expression::Primitive(loc.clone(), prim, new_exprs)));
|
||||
|
||||
(prereqs, Expression::Reference(loc, new_name))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user