rhai/src/optimize.rs

751 lines
27 KiB
Rust
Raw Normal View History

2020-04-12 17:00:06 +02:00
use crate::any::Dynamic;
2020-04-21 17:01:10 +02:00
use crate::calc_fn_hash;
2020-03-17 03:27:43 +01:00
use crate::engine::{
2020-05-11 07:36:50 +02:00
Engine, FunctionsLib, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_PRINT, KEYWORD_TYPE_OF,
2020-03-17 03:27:43 +01:00
};
2020-05-11 07:36:50 +02:00
use crate::fn_native::FnCallArgs;
2020-05-13 13:21:42 +02:00
use crate::module::Module;
use crate::packages::PackagesCollection;
use crate::parser::{map_dynamic_to_expr, Expr, FnDef, ReturnType, Stmt, AST};
2020-04-09 12:45:49 +02:00
use crate::result::EvalAltResult;
2020-03-25 04:27:18 +01:00
use crate::scope::{Entry as ScopeEntry, EntryType as ScopeEntryType, Scope};
use crate::token::Position;
use crate::utils::StaticVec;
2020-03-09 14:57:07 +01:00
2020-03-17 19:26:11 +01:00
use crate::stdlib::{
2020-03-18 11:41:18 +01:00
boxed::Box,
iter::empty,
mem,
2020-03-18 11:41:18 +01:00
string::{String, ToString},
vec,
vec::Vec,
2020-03-17 19:26:11 +01:00
};
2020-03-18 03:36:50 +01:00
/// Level of optimization performed.
2020-04-03 13:42:01 +02:00
///
/// Not available under the `no_optimize` feature.
#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)]
pub enum OptimizationLevel {
2020-03-18 03:36:50 +01:00
/// No optimization performed.
None,
2020-03-18 03:36:50 +01:00
/// Only perform simple optimizations without evaluating functions.
Simple,
/// Full optimizations performed, including evaluating functions.
2020-03-18 03:36:50 +01:00
/// Take care that this may cause side effects as it essentially assumes that all functions are pure.
Full,
}
2020-04-10 06:16:39 +02:00
impl OptimizationLevel {
/// Is the `OptimizationLevel` None.
pub fn is_none(self) -> bool {
self == Self::None
}
/// Is the `OptimizationLevel` Full.
pub fn is_full(self) -> bool {
self == Self::Full
}
}
2020-03-18 03:36:50 +01:00
/// Mutable state throughout an optimization pass.
struct State<'a> {
2020-03-18 03:36:50 +01:00
/// Has the AST been changed during this pass?
2020-03-13 11:12:41 +01:00
changed: bool,
2020-03-18 03:36:50 +01:00
/// Collection of constants to use for eager function evaluations.
2020-03-13 11:12:41 +01:00
constants: Vec<(String, Expr)>,
2020-03-18 03:36:50 +01:00
/// An `Engine` instance for eager function evaluation.
2020-04-16 17:31:48 +02:00
engine: &'a Engine,
/// Library of script-defined functions.
fn_lib: &'a [(&'a str, usize)],
/// Optimization level.
optimization_level: OptimizationLevel,
2020-03-13 11:12:41 +01:00
}
2020-04-01 03:51:33 +02:00
impl<'a> State<'a> {
/// Create a new State.
pub fn new(
2020-04-16 17:31:48 +02:00
engine: &'a Engine,
fn_lib: &'a [(&'a str, usize)],
level: OptimizationLevel,
) -> Self {
2020-04-01 03:51:33 +02:00
Self {
changed: false,
constants: vec![],
engine,
fn_lib,
optimization_level: level,
2020-04-01 03:51:33 +02:00
}
}
2020-03-18 03:36:50 +01:00
/// Reset the state from dirty to clean.
pub fn reset(&mut self) {
self.changed = false;
}
2020-03-18 03:36:50 +01:00
/// Set the AST state to be dirty (i.e. changed).
2020-03-13 11:12:41 +01:00
pub fn set_dirty(&mut self) {
self.changed = true;
}
2020-03-18 03:36:50 +01:00
/// Is the AST dirty (i.e. changed)?
2020-03-13 11:12:41 +01:00
pub fn is_dirty(&self) -> bool {
self.changed
}
2020-03-18 03:36:50 +01:00
/// Does a constant exist?
2020-03-13 11:12:41 +01:00
pub fn contains_constant(&self, name: &str) -> bool {
self.constants.iter().any(|(n, _)| n == name)
}
2020-03-18 03:36:50 +01:00
/// Prune the list of constants back to a specified size.
2020-03-13 11:12:41 +01:00
pub fn restore_constants(&mut self, len: usize) {
self.constants.truncate(len)
}
2020-03-18 03:36:50 +01:00
/// Add a new constant to the list.
2020-03-13 11:12:41 +01:00
pub fn push_constant(&mut self, name: &str, value: Expr) {
2020-05-11 17:48:50 +02:00
self.constants.push((name.into(), value))
2020-03-13 11:12:41 +01:00
}
2020-03-18 03:36:50 +01:00
/// Look up a constant from the list.
2020-03-13 11:12:41 +01:00
pub fn find_constant(&self, name: &str) -> Option<&Expr> {
for (n, expr) in self.constants.iter().rev() {
if n == name {
return Some(expr);
}
}
None
}
}
2020-04-09 12:45:49 +02:00
/// Call a registered function
fn call_fn(
packages: &PackagesCollection,
2020-05-13 13:21:42 +02:00
global_module: &Module,
2020-04-09 12:45:49 +02:00
fn_name: &str,
args: &mut FnCallArgs,
pos: Position,
) -> Result<Option<Dynamic>, Box<EvalAltResult>> {
2020-04-09 12:45:49 +02:00
// Search built-in's and external functions
let hash = calc_fn_hash(empty(), fn_name, args.iter().map(|a| a.type_id()));
2020-05-13 13:21:42 +02:00
global_module
.get_fn(hash)
2020-05-13 14:22:05 +02:00
.or_else(|| packages.get_fn(hash))
.map(|func| func.call(args))
2020-04-09 12:45:49 +02:00
.transpose()
.map_err(|err| err.new_position(pos))
2020-04-09 12:45:49 +02:00
}
2020-03-18 03:36:50 +01:00
/// Optimize a statement.
fn optimize_stmt<'a>(stmt: Stmt, state: &mut State<'a>, preserve_result: bool) -> Stmt {
2020-03-09 14:57:07 +01:00
match stmt {
2020-03-18 03:36:50 +01:00
// if expr { Noop }
Stmt::IfThenElse(x) if matches!(x.1, Stmt::Noop(_)) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-12 16:46:52 +01:00
let pos = x.0.position();
let expr = optimize_expr(x.0, state);
2020-03-12 16:46:52 +01:00
2020-03-18 03:36:50 +01:00
if preserve_result {
// -> { expr, Noop }
let mut statements = StaticVec::new();
statements.push(Stmt::Expr(Box::new(expr)));
statements.push(x.1);
Stmt::Block(Box::new((statements, pos)))
2020-03-14 16:41:15 +01:00
} else {
2020-03-18 03:36:50 +01:00
// -> expr
Stmt::Expr(Box::new(expr))
2020-03-12 16:46:52 +01:00
}
}
2020-03-18 03:36:50 +01:00
// if expr { if_block }
Stmt::IfThenElse(x) if x.2.is_none() => match x.0 {
2020-03-18 03:36:50 +01:00
// if false { if_block } -> Noop
2020-03-09 14:57:07 +01:00
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-18 03:36:50 +01:00
// if true { if_block } -> if_block
Expr::True(_) => optimize_stmt(x.1, state, true),
2020-03-18 03:36:50 +01:00
// if expr { if_block }
expr => Stmt::IfThenElse(Box::new((
optimize_expr(expr, state),
optimize_stmt(x.1, state, true),
2020-03-09 14:57:07 +01:00
None,
))),
2020-03-09 14:57:07 +01:00
},
2020-03-18 03:36:50 +01:00
// if expr { if_block } else { else_block }
Stmt::IfThenElse(x) if x.2.is_some() => match x.0 {
2020-03-18 03:36:50 +01:00
// if false { if_block } else { else_block } -> else_block
Expr::False(_) => optimize_stmt(x.2.unwrap(), state, true),
2020-03-18 03:36:50 +01:00
// if true { if_block } else { else_block } -> if_block
Expr::True(_) => optimize_stmt(x.1, state, true),
2020-03-18 03:36:50 +01:00
// if expr { if_block } else { else_block }
expr => Stmt::IfThenElse(Box::new((
optimize_expr(expr, state),
optimize_stmt(x.1, state, true),
match optimize_stmt(x.2.unwrap(), state, true) {
Stmt::Noop(_) => None, // Noop -> no else block
stmt => Some(stmt),
2020-03-12 16:46:52 +01:00
},
))),
2020-03-09 14:57:07 +01:00
},
2020-03-18 03:36:50 +01:00
// while expr { block }
Stmt::While(x) => match x.0 {
2020-03-18 03:36:50 +01:00
// while false { block } -> Noop
2020-03-09 14:57:07 +01:00
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-18 03:36:50 +01:00
// while true { block } -> loop { block }
Expr::True(_) => Stmt::Loop(Box::new(optimize_stmt(x.1, state, false))),
2020-03-18 03:36:50 +01:00
// while expr { block }
expr => match optimize_stmt(x.1, state, false) {
2020-03-18 03:36:50 +01:00
// while expr { break; } -> { expr; }
2020-03-17 10:33:37 +01:00
Stmt::Break(pos) => {
// Only a single break statement - turn into running the guard expression once
state.set_dirty();
let mut statements = StaticVec::new();
statements.push(Stmt::Expr(Box::new(optimize_expr(expr, state))));
2020-03-17 10:33:37 +01:00
if preserve_result {
statements.push(Stmt::Noop(pos))
}
Stmt::Block(Box::new((statements, pos)))
2020-03-17 10:33:37 +01:00
}
2020-03-18 03:36:50 +01:00
// while expr { block }
stmt => Stmt::While(Box::new((optimize_expr(expr, state), stmt))),
2020-03-17 10:33:37 +01:00
},
},
2020-03-18 03:36:50 +01:00
// loop { block }
Stmt::Loop(block) => match optimize_stmt(*block, state, false) {
// loop { break; } -> Noop
2020-03-17 10:33:37 +01:00
Stmt::Break(pos) => {
// Only a single break statement
state.set_dirty();
Stmt::Noop(pos)
}
2020-03-18 03:36:50 +01:00
// loop { block }
2020-03-17 10:33:37 +01:00
stmt => Stmt::Loop(Box::new(stmt)),
2020-03-09 14:57:07 +01:00
},
2020-03-18 03:36:50 +01:00
// for id in expr { block }
Stmt::For(x) => Stmt::For(Box::new((
x.0,
optimize_expr(x.1, state),
optimize_stmt(x.2, state, false),
))),
2020-03-18 03:36:50 +01:00
// let id = expr;
2020-05-09 18:19:13 +02:00
Stmt::Let(x) if x.1.is_some() => {
Stmt::Let(Box::new((x.0, Some(optimize_expr(x.1.unwrap(), state)))))
}
2020-03-18 03:36:50 +01:00
// let id;
stmt @ Stmt::Let(_) => stmt,
2020-05-05 04:39:12 +02:00
// import expr as id;
2020-05-09 18:19:13 +02:00
Stmt::Import(x) => Stmt::Import(Box::new((optimize_expr(x.0, state), x.1))),
2020-03-18 03:36:50 +01:00
// { block }
Stmt::Block(mut x) => {
let orig_len = x.0.len(); // Original number of statements in the block, for change detection
2020-03-18 03:36:50 +01:00
let orig_constants_len = state.constants.len(); // Original number of constants in the state, for restore later
let pos = x.1;
2020-03-09 14:57:07 +01:00
2020-03-18 03:36:50 +01:00
// Optimize each statement in the block
let mut result: Vec<_> =
x.0.iter_mut()
.map(|stmt| match stmt {
// Add constant into the state
Stmt::Const(v) => {
let ((name, pos), expr) = v.as_mut();
state.push_constant(name, mem::take(expr));
state.set_dirty();
Stmt::Noop(*pos) // No need to keep constants
}
// Optimize the statement
_ => optimize_stmt(mem::take(stmt), state, preserve_result),
})
.collect();
2020-03-09 14:57:07 +01:00
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-17 10:33:37 +01:00
result.retain(|stmt| !stmt.is_pure());
2020-03-11 16:43:10 +01:00
if let Some(stmt) = last_stmt {
result.push(stmt);
}
2020-05-05 04:39:12 +02:00
// Remove all let/import statements at the end of a block - the new variables will go away anyway.
2020-03-11 16:43:10 +01:00
// 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(x) if x.1.is_none() => removed = true,
Stmt::Let(x) if x.1.is_some() => removed = x.1.unwrap().is_pure(),
Stmt::Import(x) => removed = x.0.is_pure(),
2020-03-11 16:43:10 +01:00
_ => {
result.push(expr);
break;
}
}
}
if preserve_result {
if removed {
result.push(Stmt::Noop(pos))
}
2020-03-18 03:36:50 +01:00
// Optimize all the statements again
2020-03-11 16:43:10 +01:00
result = result
.into_iter()
.rev()
.enumerate()
2020-03-18 03:36:50 +01:00
.map(|(i, s)| optimize_stmt(s, state, i == 0))
2020-03-11 16:43:10 +01:00
.rev()
.collect();
2020-03-10 04:22:41 +01:00
}
2020-03-17 10:33:37 +01:00
// Remove everything following the the first return/throw
let mut dead_code = false;
result.retain(|stmt| {
if dead_code {
return false;
}
match stmt {
Stmt::ReturnWithVal(_) | Stmt::Break(_) => {
2020-03-17 10:33:37 +01:00
dead_code = true;
}
_ => (),
}
true
});
2020-03-18 03:36:50 +01:00
// Change detection
2020-03-13 11:12:41 +01:00
if orig_len != result.len() {
state.set_dirty();
}
2020-03-18 03:36:50 +01:00
// Pop the stack and remove all the local constants
state.restore_constants(orig_constants_len);
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-05-05 04:39:12 +02:00
// Only one let/import statement - leave it alone
[Stmt::Let(_)] | [Stmt::Import(_)] => Stmt::Block(Box::new((result.into(), 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(Box::new((result.into(), pos))),
2020-03-09 14:57:07 +01:00
}
}
2020-03-18 03:36:50 +01:00
// expr;
2020-03-13 11:12:41 +01:00
Stmt::Expr(expr) => Stmt::Expr(Box::new(optimize_expr(*expr, state))),
2020-03-18 03:36:50 +01:00
// return expr;
2020-05-09 18:19:13 +02:00
Stmt::ReturnWithVal(x) if x.1.is_some() => {
Stmt::ReturnWithVal(Box::new((x.0, Some(optimize_expr(x.1.unwrap(), state)))))
}
2020-03-18 03:36:50 +01:00
// All other statements - skip
2020-03-11 16:43:10 +01:00
stmt => stmt,
2020-03-09 14:57:07 +01:00
}
}
2020-03-18 03:36:50 +01:00
/// Optimize an expression.
fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr {
2020-03-18 03:36:50 +01:00
// These keywords are handled specially
2020-03-19 12:53:42 +01:00
const DONT_EVAL_KEYWORDS: [&str; 3] = [KEYWORD_PRINT, KEYWORD_DEBUG, KEYWORD_EVAL];
2020-03-17 03:27:43 +01:00
2020-03-09 14:57:07 +01:00
match expr {
2020-03-18 03:36:50 +01:00
// ( stmt )
Expr::Stmt(x) => match optimize_stmt(x.0, state, true) {
2020-03-18 03:36:50 +01:00
// ( Noop ) -> ()
2020-03-09 14:57:07 +01:00
Stmt::Noop(_) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
Expr::Unit(x.1)
2020-03-09 14:57:07 +01:00
}
2020-03-18 03:36:50 +01:00
// ( expr ) -> expr
2020-03-09 14:57:07 +01:00
Stmt::Expr(expr) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
*expr
}
2020-03-18 03:36:50 +01:00
// ( stmt )
stmt => Expr::Stmt(Box::new((stmt, x.1))),
2020-03-09 14:57:07 +01:00
},
2020-03-18 03:36:50 +01:00
// id = expr
Expr::Assignment(x) => match x.1 {
2020-03-18 03:36:50 +01:00
//id = id2 = expr2
Expr::Assignment(x2) => match (x.0, x2.0) {
2020-03-18 03:36:50 +01:00
// var = var = expr2 -> var = expr2
(Expr::Variable(a), Expr::Variable(b))
if a.1.is_none() && b.1.is_none() && a.0 == b.0 && a.3 == b.3 =>
2020-05-04 11:43:54 +02:00
{
2020-03-14 04:51:45 +01:00
// Assignment to the same variable - fold
state.set_dirty();
Expr::Assignment(Box::new((Expr::Variable(a), optimize_expr(x2.1, state), x.2)))
2020-03-14 04:51:45 +01:00
}
2020-03-18 03:36:50 +01:00
// id1 = id2 = expr2
(id1, id2) => {
Expr::Assignment(Box::new((
id1, Expr::Assignment(Box::new((id2, optimize_expr(x2.1, state), x2.2))), x.2,
)))
}
2020-03-14 04:51:45 +01:00
},
2020-03-18 03:36:50 +01:00
// id = expr
expr => Expr::Assignment(Box::new((x.0, optimize_expr(expr, state), x.2))),
2020-03-14 04:51:45 +01:00
},
2020-03-18 03:36:50 +01:00
// lhs.rhs
#[cfg(not(feature = "no_object"))]
Expr::Dot(x) => match (x.0, x.1) {
// map.string
(Expr::Map(mut m), Expr::Property(p)) if m.0.iter().all(|(_, x)| x.is_pure()) => {
let ((prop, _, _), _) = p.as_ref();
// Map literal where everything is pure - promote the indexed item.
// All other items can be thrown away.
state.set_dirty();
let pos = m.1;
m.0.iter_mut().find(|((name, _), _)| name == prop)
.map(|(_, expr)| mem::take(expr).set_position(pos))
.unwrap_or_else(|| Expr::Unit(pos))
}
// lhs.rhs
(lhs, rhs) => Expr::Dot(Box::new((optimize_expr(lhs, state), optimize_expr(rhs, state), x.2)))
}
2020-03-11 04:03:18 +01:00
2020-03-18 03:36:50 +01:00
// lhs[rhs]
#[cfg(not(feature = "no_index"))]
Expr::Index(x) => match (x.0, x.1) {
2020-03-18 03:36:50 +01:00
// array[int]
(Expr::Array(mut a), Expr::IntegerConstant(i))
if i.0 >= 0 && (i.0 as usize) < a.0.len() && a.0.iter().all(Expr::is_pure) =>
{
// Array literal where everything is pure - promote the indexed item.
2020-03-11 16:43:10 +01:00
// All other items can be thrown away.
2020-03-13 11:12:41 +01:00
state.set_dirty();
a.0.get(i.0 as usize).set_position(a.1)
}
// map[string]
(Expr::Map(mut m), Expr::StringConstant(s)) if m.0.iter().all(|(_, x)| x.is_pure()) => {
// Map literal where everything is pure - promote the indexed item.
// All other items can be thrown away.
state.set_dirty();
let pos = m.1;
m.0.iter_mut().find(|((name, _), _)| name == &s.0)
.map(|(_, expr)| mem::take(expr).set_position(pos))
.unwrap_or_else(|| Expr::Unit(pos))
}
2020-03-18 03:36:50 +01:00
// string[int]
(Expr::StringConstant(s), Expr::IntegerConstant(i)) if i.0 >= 0 && (i.0 as usize) < s.0.chars().count() => {
// String literal indexing - get the character
state.set_dirty();
Expr::CharConstant(Box::new((s.0.chars().nth(i.0 as usize).expect("should get char"), s.1)))
}
2020-03-18 03:36:50 +01:00
// lhs[rhs]
(lhs, rhs) => Expr::Index(Box::new((optimize_expr(lhs, state), optimize_expr(rhs, state), x.2))),
},
2020-03-18 03:36:50 +01:00
// [ items .. ]
#[cfg(not(feature = "no_index"))]
Expr::Array(mut a) => Expr::Array(Box::new((a.0
.iter_mut().map(|expr| optimize_expr(mem::take(expr), state))
.collect(), a.1))),
2020-03-29 17:53:35 +02:00
// [ items .. ]
#[cfg(not(feature = "no_object"))]
Expr::Map(mut m) => Expr::Map(Box::new((m.0
.iter_mut().map(|((key, pos), expr)| ((mem::take(key), *pos), optimize_expr(mem::take(expr), state)))
.collect(), m.1))),
2020-04-06 11:47:34 +02:00
// lhs in rhs
Expr::In(x) => match (x.0, x.1) {
2020-04-06 11:47:34 +02:00
// "xxx" in "xxxxx"
(Expr::StringConstant(a), Expr::StringConstant(b)) => {
2020-04-06 11:47:34 +02:00
state.set_dirty();
if b.0.contains(&a.0) { Expr::True(a.1) } else { Expr::False(a.1) }
2020-04-06 11:47:34 +02:00
}
// 'x' in "xxxxx"
(Expr::CharConstant(a), Expr::StringConstant(b)) => {
2020-04-06 11:47:34 +02:00
state.set_dirty();
if b.0.contains(a.0) { Expr::True(a.1) } else { Expr::False(a.1) }
2020-04-06 11:47:34 +02:00
}
// "xxx" in #{...}
(Expr::StringConstant(a), Expr::Map(b)) => {
2020-04-06 11:47:34 +02:00
state.set_dirty();
2020-05-09 18:19:13 +02:00
if b.0.iter().find(|((name, _), _)| name == &a.0).is_some() {
Expr::True(a.1)
2020-04-06 11:47:34 +02:00
} else {
Expr::False(a.1)
2020-04-06 11:47:34 +02:00
}
}
// 'x' in #{...}
(Expr::CharConstant(a), Expr::Map(b)) => {
2020-04-06 11:47:34 +02:00
state.set_dirty();
let ch = a.0.to_string();
2020-04-06 11:47:34 +02:00
2020-05-09 18:19:13 +02:00
if b.0.iter().find(|((name, _), _)| name == &ch).is_some() {
Expr::True(a.1)
2020-04-06 11:47:34 +02:00
} else {
Expr::False(a.1)
2020-04-06 11:47:34 +02:00
}
}
// lhs in rhs
(lhs, rhs) => Expr::In(Box::new((optimize_expr(lhs, state), optimize_expr(rhs, state), x.2))),
2020-04-06 11:47:34 +02:00
},
2020-03-18 03:36:50 +01:00
// lhs && rhs
Expr::And(x) => match (x.0, x.1) {
2020-03-18 03:36:50 +01:00
// true && rhs -> rhs
2020-03-09 14:57:07 +01:00
(Expr::True(_), rhs) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
rhs
}
2020-03-18 03:36:50 +01:00
// false && rhs -> false
2020-03-09 14:57:07 +01:00
(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)
}
2020-03-18 03:36:50 +01:00
// lhs && true -> lhs
2020-03-09 14:57:07 +01:00
(lhs, Expr::True(_)) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-18 03:36:50 +01:00
optimize_expr(lhs, state)
2020-03-09 14:57:07 +01:00
}
2020-03-18 03:36:50 +01:00
// lhs && rhs
(lhs, rhs) => Expr::And(Box::new((optimize_expr(lhs, state), optimize_expr(rhs, state), x.2))),
2020-03-09 14:57:07 +01:00
},
2020-03-18 03:36:50 +01:00
// lhs || rhs
Expr::Or(x) => match (x.0, x.1) {
2020-03-18 03:36:50 +01:00
// false || rhs -> rhs
2020-03-09 14:57:07 +01:00
(Expr::False(_), rhs) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-09 14:57:07 +01:00
rhs
}
2020-03-18 03:36:50 +01:00
// true || rhs -> true
2020-03-09 14:57:07 +01:00
(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)
}
2020-03-18 03:36:50 +01:00
// lhs || false
2020-03-09 14:57:07 +01:00
(lhs, Expr::False(_)) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-18 03:36:50 +01:00
optimize_expr(lhs, state)
2020-03-09 14:57:07 +01:00
}
2020-03-18 03:36:50 +01:00
// lhs || rhs
(lhs, rhs) => Expr::Or(Box::new((optimize_expr(lhs, state), optimize_expr(rhs, state), x.2))),
2020-03-09 14:57:07 +01:00
},
2020-03-11 16:43:10 +01:00
2020-04-01 03:51:33 +02:00
// Do not call some special keywords
2020-05-09 18:19:13 +02:00
Expr::FnCall(mut x) if DONT_EVAL_KEYWORDS.contains(&(x.0).0.as_ref())=> {
x.3 = x.3.iter_mut().map(|a| optimize_expr(mem::take(a), state)).collect();
Expr::FnCall(x)
}
2020-03-19 12:53:42 +01:00
2020-03-18 03:36:50 +01:00
// Eagerly call functions
Expr::FnCall(mut x)
if x.1.is_none() // Non-qualified
&& state.optimization_level == OptimizationLevel::Full // full optimizations
&& x.3.iter().all(|expr| expr.is_constant()) // all arguments are constants
2020-03-17 03:27:43 +01:00
=> {
2020-05-09 18:19:13 +02:00
let ((name, pos), _, _, args, def_value) = x.as_mut();
// First search in script-defined functions (can override built-in)
2020-05-09 18:19:13 +02:00
if state.fn_lib.iter().find(|(id, len)| *id == name && *len == args.len()).is_some() {
// A script-defined function overrides the built-in function - do not make the call
x.3 = x.3.iter_mut().map(|a| optimize_expr(mem::take(a), state)).collect();
return Expr::FnCall(x);
}
2020-05-09 18:19:13 +02:00
let mut arg_values: Vec<_> = args.iter().map(Expr::get_constant_value).collect();
2020-04-12 17:00:06 +02:00
let mut call_args: Vec<_> = arg_values.iter_mut().collect();
2020-03-17 03:27:43 +01:00
// Save the typename of the first argument if it is `type_of()`
// This is to avoid `call_args` being passed into the closure
2020-05-09 18:19:13 +02:00
let arg_for_type_of = if name == KEYWORD_TYPE_OF && call_args.len() == 1 {
2020-03-18 03:36:50 +01:00
state.engine.map_type_name(call_args[0].type_name())
2020-03-17 03:27:43 +01:00
} else {
""
};
2020-05-13 13:21:42 +02:00
call_fn(&state.engine.packages, &state.engine.global_module, name, &mut call_args, *pos).ok()
2020-04-09 12:45:49 +02:00
.and_then(|result|
result.or_else(|| {
if !arg_for_type_of.is_empty() {
// Handle `type_of()`
Some(arg_for_type_of.to_string().into())
2020-04-09 12:45:49 +02:00
} else {
// Otherwise use the default value, if any
2020-05-09 18:19:13 +02:00
def_value.clone()
2020-04-09 12:45:49 +02:00
}
2020-05-09 18:19:13 +02:00
}).and_then(|result| map_dynamic_to_expr(result, *pos))
.map(|expr| {
state.set_dirty();
expr
2020-03-17 03:27:43 +01:00
})
).unwrap_or_else(|| {
2020-04-09 12:45:49 +02:00
// Optimize function call arguments
x.3 = x.3.iter_mut().map(|a| optimize_expr(mem::take(a), state)).collect();
Expr::FnCall(x)
})
}
2020-03-19 12:53:42 +01:00
2020-03-18 03:36:50 +01:00
// id(args ..) -> optimize function call arguments
Expr::FnCall(mut x) => {
x.3 = x.3.iter_mut().map(|a| optimize_expr(mem::take(a), state)).collect();
Expr::FnCall(x)
}
2020-03-19 12:53:42 +01:00
2020-03-18 03:36:50 +01:00
// constant-name
2020-05-09 18:19:13 +02:00
Expr::Variable(x) if x.1.is_none() && state.contains_constant(&(x.0).0) => {
let (name, pos) = x.0;
2020-03-13 11:12:41 +01:00
state.set_dirty();
// Replace constant with value
2020-05-09 18:19:13 +02:00
state.find_constant(&name).expect("should find constant in scope!").clone().set_position(pos)
2020-03-13 11:12:41 +01:00
}
2020-03-19 12:53:42 +01:00
2020-03-18 03:36:50 +01:00
// All other expressions - skip
2020-03-11 16:43:10 +01:00
expr => expr,
2020-03-09 14:57:07 +01:00
}
}
2020-04-10 06:16:39 +02:00
fn optimize<'a>(
statements: Vec<Stmt>,
2020-04-16 17:31:48 +02:00
engine: &Engine,
scope: &Scope,
fn_lib: &'a [(&'a str, usize)],
level: OptimizationLevel,
) -> Vec<Stmt> {
// If optimization level is None then skip optimizing
if level == OptimizationLevel::None {
return statements;
}
// Set up the state
let mut state = State::new(engine, fn_lib, level);
2020-03-18 03:36:50 +01:00
// Add constants from the scope into the state
scope
.iter()
2020-03-25 04:27:18 +01:00
.filter(|ScopeEntry { typ, expr, .. }| {
// Get all the constants with definite constant expressions
2020-03-25 04:27:18 +01:00
*typ == ScopeEntryType::Constant
2020-04-27 15:14:34 +02:00
&& expr.as_ref().map(|v| v.is_constant()).unwrap_or(false)
})
.for_each(|ScopeEntry { name, expr, .. }| {
state.push_constant(
name.as_ref(),
2020-04-27 15:14:34 +02:00
(**expr.as_ref().expect("should be Some(expr)")).clone(),
)
});
let orig_constants_len = state.constants.len();
2020-03-11 16:43:10 +01:00
let mut result = statements;
2020-03-18 03:36:50 +01:00
// Optimization loop
2020-03-09 14:57:07 +01:00
loop {
state.reset();
state.restore_constants(orig_constants_len);
2020-03-09 14:57:07 +01:00
let num_statements = result.len();
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)| {
match &stmt {
2020-05-09 18:19:13 +02:00
Stmt::Const(v) => {
2020-04-11 12:09:03 +02:00
// Load constants
2020-05-09 18:19:13 +02:00
let ((name, _), expr) = v.as_ref();
state.push_constant(&name, expr.clone());
2020-04-11 12:09:03 +02:00
stmt // Keep it in the global scope
}
_ => {
// Keep all variable declarations at this level
// and always keep the last return value
2020-05-05 04:39:12 +02:00
let keep = match stmt {
Stmt::Let(_) | Stmt::Import(_) => true,
2020-05-05 04:39:12 +02:00
_ => i == num_statements - 1,
};
2020-04-11 12:09:03 +02:00
optimize_stmt(stmt, &mut state, keep)
}
2020-03-13 11:12:41 +01:00
}
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();
// Remove all pure statements at global level
2020-03-18 11:41:18 +01:00
result.retain(|stmt| !stmt.is_pure());
2020-03-11 16:43:10 +01:00
2020-03-18 11:41:18 +01:00
// Add back the last statement unless it is a lone No-op
2020-03-11 16:43:10 +01:00
if let Some(stmt) = last_stmt {
2020-03-24 09:57:35 +01:00
if !result.is_empty() || !matches!(stmt, Stmt::Noop(_)) {
2020-03-18 11:41:18 +01:00
result.push(stmt);
}
2020-03-11 16:43:10 +01:00
}
result
2020-03-09 14:57:07 +01:00
}
2020-03-18 03:36:50 +01:00
/// Optimize an AST.
2020-03-18 11:41:18 +01:00
pub fn optimize_into_ast(
engine: &Engine,
scope: &Scope,
statements: Vec<Stmt>,
functions: Vec<FnDef>,
level: OptimizationLevel,
) -> AST {
2020-04-10 06:16:39 +02:00
#[cfg(feature = "no_optimize")]
const level: OptimizationLevel = OptimizationLevel::None;
#[cfg(not(feature = "no_function"))]
let fn_lib: Vec<_> = functions
.iter()
.map(|fn_def| (fn_def.name.as_str(), fn_def.params.len()))
.collect();
#[cfg(feature = "no_function")]
const fn_lib: &[(&str, usize)] = &[];
#[cfg(not(feature = "no_function"))]
let lib = FunctionsLib::from_iter(functions.iter().cloned().map(|mut fn_def| {
if !level.is_none() {
let pos = fn_def.body.position();
// Optimize the function body
let mut body = optimize(vec![fn_def.body], engine, &Scope::new(), &fn_lib, level);
// {} -> Noop
fn_def.body = match body.pop().unwrap_or_else(|| Stmt::Noop(pos)) {
// { return val; } -> val
Stmt::ReturnWithVal(x) if x.1.is_some() && (x.0).0 == ReturnType::Return => {
Stmt::Expr(Box::new(x.1.unwrap()))
}
// { return; } -> ()
Stmt::ReturnWithVal(x) if x.1.is_none() && (x.0).0 == ReturnType::Return => {
Stmt::Expr(Box::new(Expr::Unit((x.0).1)))
}
// All others
stmt => stmt,
};
}
fn_def
}));
#[cfg(feature = "no_function")]
let lib: FunctionsLib = Default::default();
2020-05-05 09:00:10 +02:00
AST::new(
match level {
OptimizationLevel::None => statements,
OptimizationLevel::Simple | OptimizationLevel::Full => {
optimize(statements, engine, &scope, &fn_lib, level)
}
},
2020-05-05 09:00:10 +02:00
lib,
)
}