rhai/src/optimize.rs

378 lines
12 KiB
Rust
Raw Normal View History

2020-03-11 16:43:10 +01:00
use crate::engine::KEYWORD_DUMP_AST;
2020-03-09 14:57:07 +01:00
use crate::parser::{Expr, Stmt};
2020-03-13 11:12:41 +01:00
struct State {
changed: bool,
constants: Vec<(String, Expr)>,
}
impl State {
pub fn new() -> Self {
State {
changed: false,
constants: vec![],
}
}
pub fn set_dirty(&mut self) {
self.changed = true;
}
pub fn is_dirty(&self) -> bool {
self.changed
}
pub fn contains_constant(&self, name: &str) -> bool {
self.constants.iter().any(|(n, _)| n == name)
}
pub fn restore_constants(&mut self, len: usize) {
self.constants.truncate(len)
}
pub fn push_constant(&mut self, name: &str, value: Expr) {
self.constants.push((name.to_string(), value))
}
pub fn find_constant(&self, name: &str) -> Option<&Expr> {
for (n, expr) in self.constants.iter().rev() {
if n == name {
return Some(expr);
}
}
None
}
}
fn optimize_stmt(stmt: Stmt, state: &mut State, preserve_result: bool) -> Stmt {
2020-03-09 14:57:07 +01:00
match stmt {
2020-03-12 16:46:52 +01:00
Stmt::IfElse(expr, stmt1, None) if stmt1.is_noop() => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-12 16:46:52 +01:00
let pos = expr.position();
2020-03-13 11:12:41 +01:00
let expr = optimize_expr(*expr, state);
2020-03-12 16:46:52 +01:00
match expr {
Expr::False(_) | Expr::True(_) => Stmt::Noop(stmt1.position()),
expr => {
let stmt = Stmt::Expr(Box::new(expr));
if preserve_result {
Stmt::Block(vec![stmt, *stmt1], pos)
} else {
stmt
}
}
}
}
2020-03-09 14:57:07 +01:00
Stmt::IfElse(expr, stmt1, None) => match *expr {
Expr::False(pos) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
Stmt::Noop(pos)
}
2020-03-13 11:12:41 +01:00
Expr::True(_) => optimize_stmt(*stmt1, state, true),
2020-03-10 04:22:41 +01:00
expr => Stmt::IfElse(
2020-03-13 11:12:41 +01:00
Box::new(optimize_expr(expr, state)),
Box::new(optimize_stmt(*stmt1, state, true)),
2020-03-09 14:57:07 +01:00
None,
),
},
Stmt::IfElse(expr, stmt1, Some(stmt2)) => match *expr {
2020-03-13 11:12:41 +01:00
Expr::False(_) => optimize_stmt(*stmt2, state, true),
Expr::True(_) => optimize_stmt(*stmt1, state, true),
2020-03-10 04:22:41 +01:00
expr => Stmt::IfElse(
2020-03-13 11:12:41 +01:00
Box::new(optimize_expr(expr, state)),
Box::new(optimize_stmt(*stmt1, state, true)),
match optimize_stmt(*stmt2, state, true) {
2020-03-12 16:46:52 +01:00
stmt if stmt.is_noop() => None,
stmt => Some(Box::new(stmt)),
},
2020-03-09 14:57:07 +01:00
),
},
Stmt::While(expr, stmt) => match *expr {
Expr::False(pos) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
Stmt::Noop(pos)
}
2020-03-13 11:12:41 +01:00
Expr::True(_) => Stmt::Loop(Box::new(optimize_stmt(*stmt, state, false))),
2020-03-10 04:22:41 +01:00
expr => Stmt::While(
2020-03-13 11:12:41 +01:00
Box::new(optimize_expr(expr, state)),
Box::new(optimize_stmt(*stmt, state, false)),
2020-03-09 14:57:07 +01:00
),
},
2020-03-13 11:12:41 +01:00
Stmt::Loop(stmt) => Stmt::Loop(Box::new(optimize_stmt(*stmt, state, false))),
2020-03-09 14:57:07 +01:00
Stmt::For(id, expr, stmt) => Stmt::For(
id,
2020-03-13 11:12:41 +01:00
Box::new(optimize_expr(*expr, state)),
Box::new(optimize_stmt(*stmt, state, false)),
2020-03-09 14:57:07 +01:00
),
Stmt::Let(id, Some(expr), pos) => {
2020-03-13 11:12:41 +01:00
Stmt::Let(id, Some(Box::new(optimize_expr(*expr, state))), pos)
2020-03-09 14:57:07 +01:00
}
Stmt::Let(_, None, _) => stmt,
Stmt::Block(statements, pos) => {
let orig_len = statements.len();
2020-03-13 11:12:41 +01:00
let orig_constants = state.constants.len();
2020-03-09 14:57:07 +01:00
let mut result: Vec<_> = statements
.into_iter() // For each statement
2020-03-13 11:12:41 +01:00
.map(|stmt| {
if let Stmt::Const(name, value, pos) = stmt {
state.push_constant(&name, *value);
state.set_dirty();
Stmt::Noop(pos) // No need to keep constants
} else {
optimize_stmt(stmt, state, preserve_result) // Optimize the statement
}
})
2020-03-11 16:43:10 +01:00
.enumerate()
2020-03-13 11:12:41 +01:00
.filter(|(i, stmt)| stmt.is_op() || (preserve_result && *i == orig_len - 1)) // Remove no-op's but leave the last one if we need the result
.map(|(_, stmt)| stmt)
2020-03-09 14:57:07 +01:00
.collect();
2020-03-11 16:43:10 +01:00
// Remove all raw expression statements that are pure except for the very last statement
let last_stmt = if preserve_result { result.pop() } else { None };
2020-03-10 04:22:41 +01:00
2020-03-11 16:43:10 +01:00
result.retain(|stmt| match stmt {
Stmt::Expr(expr) if expr.is_pure() => false,
_ => true,
});
if let Some(stmt) = last_stmt {
result.push(stmt);
}
// Remove all let statements at the end of a block - the new variables will go away anyway.
// But be careful only remove ones that have no initial values or have values that are pure expressions,
// otherwise there may be side effects.
let mut removed = false;
while let Some(expr) = result.pop() {
match expr {
Stmt::Let(_, None, _) => removed = true,
Stmt::Let(_, Some(val_expr), _) if val_expr.is_pure() => removed = true,
_ => {
result.push(expr);
break;
}
}
}
if preserve_result {
if removed {
result.push(Stmt::Noop(pos))
}
result = result
.into_iter()
.rev()
.enumerate()
2020-03-13 11:12:41 +01:00
.map(|(i, s)| optimize_stmt(s, state, i == 0)) // Optimize all other statements again
2020-03-11 16:43:10 +01:00
.rev()
.collect();
2020-03-10 04:22:41 +01:00
}
2020-03-13 11:12:41 +01:00
if orig_len != result.len() {
state.set_dirty();
}
state.restore_constants(orig_constants);
2020-03-09 14:57:07 +01:00
match result[..] {
2020-03-11 16:43:10 +01:00
// No statements in block - change to No-op
2020-03-09 14:57:07 +01:00
[] => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-10 04:22:41 +01:00
Stmt::Noop(pos)
}
2020-03-11 16:43:10 +01:00
// Only one statement - promote
2020-03-09 14:57:07 +01:00
[_] => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
result.remove(0)
}
_ => Stmt::Block(result, pos),
}
}
2020-03-13 11:12:41 +01:00
Stmt::Expr(expr) => Stmt::Expr(Box::new(optimize_expr(*expr, state))),
2020-03-09 14:57:07 +01:00
2020-03-13 11:12:41 +01:00
Stmt::ReturnWithVal(Some(expr), is_return, pos) => {
Stmt::ReturnWithVal(Some(Box::new(optimize_expr(*expr, state))), is_return, pos)
}
2020-03-09 14:57:07 +01:00
2020-03-11 16:43:10 +01:00
stmt => stmt,
2020-03-09 14:57:07 +01:00
}
}
2020-03-13 11:12:41 +01:00
fn optimize_expr(expr: Expr, state: &mut State) -> Expr {
2020-03-09 14:57:07 +01:00
match expr {
2020-03-13 11:12:41 +01:00
Expr::Stmt(stmt, pos) => match optimize_stmt(*stmt, state, true) {
2020-03-09 14:57:07 +01:00
Stmt::Noop(_) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
Expr::Unit(pos)
}
Stmt::Expr(expr) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
*expr
}
stmt => Expr::Stmt(Box::new(stmt), pos),
},
Expr::Assignment(id, expr, pos) => {
2020-03-13 11:12:41 +01:00
Expr::Assignment(id, Box::new(optimize_expr(*expr, state)), pos)
2020-03-09 14:57:07 +01:00
}
Expr::Dot(lhs, rhs, pos) => Expr::Dot(
2020-03-13 11:12:41 +01:00
Box::new(optimize_expr(*lhs, state)),
Box::new(optimize_expr(*rhs, state)),
2020-03-09 14:57:07 +01:00
pos,
),
2020-03-11 04:03:18 +01:00
#[cfg(not(feature = "no_index"))]
Expr::Index(lhs, rhs, pos) => match (*lhs, *rhs) {
(Expr::Array(mut items, _), Expr::IntegerConstant(i, _))
2020-03-11 16:43:10 +01:00
if i >= 0 && (i as usize) < items.len() && items.iter().all(|x| x.is_pure()) =>
{
2020-03-11 16:43:10 +01:00
// Array where everything is a pure - promote the indexed item.
// All other items can be thrown away.
2020-03-13 11:12:41 +01:00
state.set_dirty();
items.remove(i as usize)
}
(lhs, rhs) => Expr::Index(
2020-03-13 11:12:41 +01:00
Box::new(optimize_expr(lhs, state)),
Box::new(optimize_expr(rhs, state)),
pos,
),
},
2020-03-11 04:03:18 +01:00
#[cfg(feature = "no_index")]
Expr::Index(_, _, _) => panic!("encountered an index expression during no_index!"),
#[cfg(not(feature = "no_index"))]
2020-03-09 14:57:07 +01:00
Expr::Array(items, pos) => {
let orig_len = items.len();
2020-03-09 14:57:07 +01:00
let items: Vec<_> = items
.into_iter()
2020-03-13 11:12:41 +01:00
.map(|expr| optimize_expr(expr, state))
2020-03-09 14:57:07 +01:00
.collect();
2020-03-13 11:12:41 +01:00
if orig_len != items.len() {
state.set_dirty();
}
2020-03-09 14:57:07 +01:00
Expr::Array(items, pos)
}
2020-03-11 04:03:18 +01:00
#[cfg(feature = "no_index")]
Expr::Array(_, _) => panic!("encountered an array during no_index!"),
2020-03-09 14:57:07 +01:00
Expr::And(lhs, rhs) => match (*lhs, *rhs) {
(Expr::True(_), rhs) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
rhs
}
(Expr::False(pos), _) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
Expr::False(pos)
}
(lhs, Expr::True(_)) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
lhs
}
(lhs, rhs) => Expr::And(
2020-03-13 11:12:41 +01:00
Box::new(optimize_expr(lhs, state)),
Box::new(optimize_expr(rhs, state)),
2020-03-09 14:57:07 +01:00
),
},
Expr::Or(lhs, rhs) => match (*lhs, *rhs) {
(Expr::False(_), rhs) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
rhs
}
(Expr::True(pos), _) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
Expr::True(pos)
}
(lhs, Expr::False(_)) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
lhs
}
(lhs, rhs) => Expr::Or(
2020-03-13 11:12:41 +01:00
Box::new(optimize_expr(lhs, state)),
Box::new(optimize_expr(rhs, state)),
2020-03-09 14:57:07 +01:00
),
},
2020-03-11 16:43:10 +01:00
2020-03-12 05:39:33 +01:00
Expr::FunctionCall(id, args, def_value, pos) if id == KEYWORD_DUMP_AST => {
Expr::FunctionCall(id, args, def_value, pos)
}
2020-03-09 14:57:07 +01:00
Expr::FunctionCall(id, args, def_value, pos) => {
let orig_len = args.len();
2020-03-09 14:57:07 +01:00
2020-03-13 11:12:41 +01:00
let args: Vec<_> = args.into_iter().map(|a| optimize_expr(a, state)).collect();
2020-03-09 14:57:07 +01:00
2020-03-13 11:12:41 +01:00
if orig_len != args.len() {
state.set_dirty();
}
2020-03-09 14:57:07 +01:00
Expr::FunctionCall(id, args, def_value, pos)
}
2020-03-11 16:43:10 +01:00
2020-03-13 11:12:41 +01:00
Expr::Variable(ref name, _) if state.contains_constant(name) => {
state.set_dirty();
// Replace constant with value
state
.find_constant(name)
.expect("can't find constant in scope!")
.clone()
}
2020-03-11 16:43:10 +01:00
expr => expr,
2020-03-09 14:57:07 +01:00
}
}
2020-03-11 16:43:10 +01:00
pub(crate) fn optimize(statements: Vec<Stmt>) -> Vec<Stmt> {
let mut result = statements;
2020-03-09 14:57:07 +01:00
loop {
2020-03-13 11:12:41 +01:00
let mut state = State::new();
let num_statements = result.len();
2020-03-09 14:57:07 +01:00
2020-03-11 16:43:10 +01:00
result = result
2020-03-09 14:57:07 +01:00
.into_iter()
2020-03-11 16:43:10 +01:00
.enumerate()
.map(|(i, stmt)| {
2020-03-13 11:12:41 +01:00
if let Stmt::Const(name, value, _) = &stmt {
// Load constants
state.push_constant(name, value.as_ref().clone());
stmt // Keep it in the top scope
} else {
// Keep all variable declarations at this level
// and always keep the last return value
let keep = stmt.is_var() || i == num_statements - 1;
optimize_stmt(stmt, &mut state, keep)
}
2020-03-11 16:43:10 +01:00
})
2020-03-09 14:57:07 +01:00
.collect();
2020-03-13 11:12:41 +01:00
if !state.is_dirty() {
2020-03-09 14:57:07 +01:00
break;
}
}
2020-03-12 16:46:52 +01:00
// Eliminate code that is pure but always keep the last statement
2020-03-11 16:43:10 +01:00
let last_stmt = result.pop();
2020-03-12 16:46:52 +01:00
// Remove all pure statements at top level
result.retain(|stmt| match stmt {
Stmt::Expr(expr) if expr.is_pure() => false,
_ => true,
});
2020-03-11 16:43:10 +01:00
if let Some(stmt) = last_stmt {
result.push(stmt); // Add back the last statement
}
result
2020-03-09 14:57:07 +01:00
}