rhai/src/optimize.rs

961 lines
34 KiB
Rust
Raw Normal View History

2020-11-25 02:36:06 +01:00
//! Module implementing the [`AST`] optimizer.
2020-11-16 16:10:14 +01:00
use crate::ast::{Expr, ScriptFnDef, Stmt};
use crate::dynamic::AccessMode;
2020-12-26 06:05:57 +01:00
use crate::engine::{Imports, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_PRINT, KEYWORD_TYPE_OF};
use crate::fn_call::run_builtin_binary_op;
2020-10-29 04:37:51 +01:00
use crate::parser::map_dynamic_to_expr;
2020-03-17 19:26:11 +01:00
use crate::stdlib::{
2020-03-18 11:41:18 +01:00
boxed::Box,
2020-11-13 11:32:18 +01:00
hash::{Hash, Hasher},
iter::empty,
2020-11-12 05:37:42 +01:00
mem,
2020-03-18 11:41:18 +01:00
string::{String, ToString},
vec,
vec::Vec,
2020-03-17 19:26:11 +01:00
};
2020-11-16 16:10:14 +01:00
use crate::token::is_valid_identifier;
use crate::utils::get_hasher;
2020-11-20 09:52:28 +01:00
use crate::{calc_native_fn_hash, Dynamic, Engine, Module, Position, Scope, StaticVec, AST};
2020-03-18 03:36:50 +01:00
/// Level of optimization performed.
#[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 {
2020-11-25 02:36:06 +01:00
/// Is the `OptimizationLevel` [`None`][OptimizationLevel::None]?
2020-11-28 09:58:02 +01:00
#[allow(dead_code)]
2020-10-08 16:25:50 +02:00
#[inline(always)]
2020-04-10 06:16:39 +02:00
pub fn is_none(self) -> bool {
self == Self::None
}
2020-11-25 02:36:06 +01:00
/// Is the `OptimizationLevel` [`Simple`][OptimizationLevel::Simple]?
2020-11-28 09:58:02 +01:00
#[allow(dead_code)]
2020-10-08 16:25:50 +02:00
#[inline(always)]
2020-05-31 06:36:31 +02:00
pub fn is_simple(self) -> bool {
self == Self::Simple
}
2020-11-25 02:36:06 +01:00
/// Is the `OptimizationLevel` [`Full`][OptimizationLevel::Full]?
2020-11-28 09:58:02 +01:00
#[allow(dead_code)]
2020-10-08 16:25:50 +02:00
#[inline(always)]
2020-04-10 06:16:39 +02:00
pub fn is_full(self) -> bool {
self == Self::Full
}
}
2020-03-18 03:36:50 +01:00
/// Mutable state throughout an optimization pass.
#[derive(Debug, Clone)]
struct State<'a> {
2020-11-25 02:36:06 +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.
variables: Vec<(String, AccessMode, Expr)>,
2021-01-12 16:52:50 +01:00
/// Activate constants propagation?
propagate_constants: bool,
2020-11-25 02:36:06 +01:00
/// An [`Engine`] instance for eager function evaluation.
2020-04-16 17:31:48 +02:00
engine: &'a Engine,
2020-12-26 06:05:57 +01:00
/// Collection of sub-modules.
mods: Imports,
2020-11-25 02:36:06 +01:00
/// [Module] containing script-defined functions.
2020-10-20 04:54:32 +02:00
lib: &'a [&'a Module],
/// 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.
2020-10-08 16:25:50 +02:00
#[inline(always)]
2020-10-20 04:54:32 +02:00
pub fn new(engine: &'a Engine, lib: &'a [&'a Module], level: OptimizationLevel) -> Self {
2020-04-01 03:51:33 +02:00
Self {
changed: false,
variables: vec![],
2021-01-12 16:52:50 +01:00
propagate_constants: true,
2020-04-01 03:51:33 +02:00
engine,
2020-12-26 06:05:57 +01:00
mods: (&engine.global_sub_modules).into(),
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.
2020-10-08 16:25:50 +02:00
#[inline(always)]
pub fn reset(&mut self) {
self.changed = false;
}
2020-11-25 02:36:06 +01:00
/// Set the [`AST`] state to be dirty (i.e. changed).
2020-10-08 16:25:50 +02:00
#[inline(always)]
2020-03-13 11:12:41 +01:00
pub fn set_dirty(&mut self) {
self.changed = true;
}
2020-11-25 02:36:06 +01:00
/// Is the [`AST`] dirty (i.e. changed)?
2020-10-08 16:25:50 +02:00
#[inline(always)]
2020-03-13 11:12:41 +01:00
pub fn is_dirty(&self) -> bool {
self.changed
}
2020-03-18 03:36:50 +01:00
/// Prune the list of constants back to a specified size.
2020-10-08 16:25:50 +02:00
#[inline(always)]
pub fn restore_var(&mut self, len: usize) {
self.variables.truncate(len)
2020-03-13 11:12:41 +01:00
}
2020-03-18 03:36:50 +01:00
/// Add a new constant to the list.
2020-10-08 16:25:50 +02:00
#[inline(always)]
pub fn push_var(&mut self, name: &str, access: AccessMode, value: Expr) {
self.variables.push((name.into(), access, 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-10-08 16:25:50 +02:00
#[inline]
2020-03-13 11:12:41 +01:00
pub fn find_constant(&self, name: &str) -> Option<&Expr> {
2021-01-12 16:52:50 +01:00
if !self.propagate_constants {
return None;
}
for (n, access, expr) in self.variables.iter().rev() {
2020-03-13 11:12:41 +01:00
if n == name {
return if access.is_read_only() {
Some(expr)
} else {
None
};
2020-03-13 11:12:41 +01:00
}
}
None
}
}
2020-04-09 12:45:49 +02:00
/// Call a registered function
2020-05-24 05:57:46 +02:00
fn call_fn_with_constant_arguments(
2020-05-23 12:59:28 +02:00
state: &State,
2020-04-09 12:45:49 +02:00
fn_name: &str,
2020-05-24 05:57:46 +02:00
arg_values: &mut [Dynamic],
2020-06-01 09:25:22 +02:00
) -> Option<Dynamic> {
2020-04-09 12:45:49 +02:00
// Search built-in's and external functions
2020-10-28 15:18:44 +01:00
let hash_fn = calc_native_fn_hash(empty(), fn_name, arg_values.iter().map(|a| a.type_id()));
2020-05-23 12:59:28 +02:00
state
.engine
2020-07-31 06:11:16 +02:00
.call_native_fn(
2020-11-07 16:33:21 +01:00
&mut Default::default(),
&mut Default::default(),
state.lib,
2020-05-23 12:59:28 +02:00
fn_name,
2020-12-24 09:32:43 +01:00
hash_fn.unwrap(),
2020-05-24 05:57:46 +02:00
arg_values.iter_mut().collect::<StaticVec<_>>().as_mut(),
false,
true,
2020-12-12 04:15:09 +01:00
Position::NONE,
2020-11-02 16:54:19 +01:00
None,
2020-05-23 12:59:28 +02:00
)
2020-07-31 06:11:16 +02:00
.ok()
.map(|(v, _)| v)
2020-04-09 12:45:49 +02:00
}
2020-12-26 16:21:16 +01:00
/// Optimize a block of [statements][Stmt].
2020-11-12 05:37:42 +01:00
fn optimize_stmt_block(
mut statements: Vec<Stmt>,
pos: Position,
state: &mut State,
preserve_result: bool,
count_promote_as_dirty: bool,
) -> Stmt {
let orig_len = statements.len(); // Original number of statements in the block, for change detection
let orig_constants_len = state.variables.len(); // Original number of constants in the state, for restore later
2021-01-12 16:52:50 +01:00
let orig_propagate_constants = state.propagate_constants;
2020-11-12 05:37:42 +01:00
// Optimize each statement in the block
2021-01-12 16:52:50 +01:00
statements.iter_mut().for_each(|stmt| {
match stmt {
// Add constant literals into the state
Stmt::Const(var_def, Some(value_expr), _, _) => {
optimize_expr(value_expr, state);
if value_expr.is_constant() {
state.push_var(&var_def.name, AccessMode::ReadOnly, value_expr.clone());
}
}
Stmt::Const(var_def, None, _, _) => {
state.push_var(&var_def.name, AccessMode::ReadOnly, Expr::Unit(var_def.pos));
}
// Add variables into the state
Stmt::Let(var_def, expr, _, _) => {
if let Some(value_expr) = expr {
optimize_expr(value_expr, state);
}
state.push_var(
&var_def.name,
AccessMode::ReadWrite,
Expr::Unit(var_def.pos),
);
}
// Optimize the statement
_ => optimize_stmt(stmt, state, preserve_result),
}
2020-11-12 05:37:42 +01:00
});
// Remove all raw expression statements that are pure except for the very last statement
let last_stmt = if preserve_result {
statements.pop()
} else {
None
};
statements.retain(|stmt| !stmt.is_pure());
if let Some(stmt) = last_stmt {
statements.push(stmt);
}
// Remove all let/import 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) = statements.pop() {
match expr {
Stmt::Let(_, expr, _, _) | Stmt::Const(_, expr, _, _) => {
removed = expr.as_ref().map(Expr::is_pure).unwrap_or(true)
}
2020-11-12 05:37:42 +01:00
#[cfg(not(feature = "no_module"))]
Stmt::Import(expr, _, _) => removed = expr.is_pure(),
_ => {
statements.push(expr);
break;
}
}
}
if preserve_result {
if removed {
statements.push(Stmt::Noop(pos))
}
// Optimize all the statements again
let num_statements = statements.len();
statements
.iter_mut()
.enumerate()
.for_each(|(i, stmt)| optimize_stmt(stmt, state, i == num_statements));
}
// Remove everything following the the first return/throw
let mut dead_code = false;
statements.retain(|stmt| {
if dead_code {
return false;
}
match stmt {
2020-11-14 15:55:23 +01:00
Stmt::Return(_, _, _) | Stmt::Break(_) => dead_code = true,
2020-11-12 05:37:42 +01:00
_ => (),
}
true
});
// Change detection
if orig_len != statements.len() {
state.set_dirty();
}
// Pop the stack and remove all the local constants
state.restore_var(orig_constants_len);
2020-11-12 05:37:42 +01:00
2021-01-12 16:52:50 +01:00
state.propagate_constants = orig_propagate_constants;
2020-11-12 05:37:42 +01:00
match &statements[..] {
// No statements in block - change to No-op
[] => {
state.set_dirty();
Stmt::Noop(pos)
}
// Only one let statement - leave it alone
[x] if matches!(x, Stmt::Let(_, _, _, _)) => Stmt::Block(statements, pos),
// Only one const statement - leave it alone
[x] if matches!(x, Stmt::Const(_, _, _, _)) => Stmt::Block(statements, pos),
2020-11-12 05:37:42 +01:00
// Only one import statement - leave it alone
#[cfg(not(feature = "no_module"))]
[x] if matches!(x, Stmt::Import(_, _, _)) => Stmt::Block(statements, pos),
// Only one statement - promote
[_] => {
if count_promote_as_dirty {
state.set_dirty();
}
statements.remove(0)
}
_ => Stmt::Block(statements, pos),
}
}
2020-12-26 16:21:16 +01:00
/// Optimize a [statement][Stmt].
2020-11-12 05:37:42 +01:00
fn optimize_stmt(stmt: &mut Stmt, state: &mut State, preserve_result: bool) {
2020-03-09 14:57:07 +01:00
match stmt {
2020-11-03 06:08:19 +01:00
// expr op= expr
2020-11-20 15:23:37 +01:00
Stmt::Assignment(x, _) => match x.0 {
2020-11-12 05:37:42 +01:00
Expr::Variable(_) => optimize_expr(&mut x.2, state),
_ => {
optimize_expr(&mut x.0, state);
optimize_expr(&mut x.2, state);
2020-11-03 06:08:19 +01:00
}
},
2020-11-14 16:43:36 +01:00
2020-10-27 11:18:19 +01:00
// if false { if_block } -> Noop
Stmt::If(Expr::BoolConstant(false, pos), x, _) if x.1.is_none() => {
2020-10-27 11:18:19 +01:00
state.set_dirty();
2020-11-12 05:37:42 +01:00
*stmt = Stmt::Noop(*pos);
2020-10-27 11:18:19 +01:00
}
// if true { if_block } -> if_block
Stmt::If(Expr::BoolConstant(true, _), x, _) if x.1.is_none() => {
2020-11-12 05:37:42 +01:00
*stmt = mem::take(&mut x.0);
optimize_stmt(stmt, state, true);
}
2020-03-18 03:36:50 +01:00
// if expr { Noop }
2020-11-20 15:23:37 +01:00
Stmt::If(condition, x, _) if x.1.is_none() && matches!(x.0, Stmt::Noop(_)) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-03-12 16:46:52 +01:00
2020-10-27 11:18:19 +01:00
let pos = condition.position();
2020-11-12 05:37:42 +01:00
let mut expr = mem::take(condition);
optimize_expr(&mut expr, state);
2020-03-12 16:46:52 +01:00
2020-11-12 05:37:42 +01:00
*stmt = if preserve_result {
2020-03-18 03:36:50 +01:00
// -> { expr, Noop }
2021-01-21 03:32:05 +01:00
Stmt::Block(vec![Stmt::Expr(expr), mem::take(&mut x.0)], pos)
2020-03-14 16:41:15 +01:00
} else {
2020-03-18 03:36:50 +01:00
// -> expr
2020-10-27 11:18:19 +01:00
Stmt::Expr(expr)
2020-11-12 05:37:42 +01:00
};
2020-03-12 16:46:52 +01:00
}
2020-03-18 03:36:50 +01:00
// if expr { if_block }
2020-11-20 15:23:37 +01:00
Stmt::If(condition, x, _) if x.1.is_none() => {
2020-11-12 05:37:42 +01:00
optimize_expr(condition, state);
optimize_stmt(&mut x.0, state, true);
}
2020-10-27 11:18:19 +01:00
// if false { if_block } else { else_block } -> else_block
Stmt::If(Expr::BoolConstant(false, _), x, _) if x.1.is_some() => {
2020-11-12 05:37:42 +01:00
*stmt = mem::take(x.1.as_mut().unwrap());
optimize_stmt(stmt, state, true);
2020-10-27 11:18:19 +01:00
}
// if true { if_block } else { else_block } -> if_block
Stmt::If(Expr::BoolConstant(true, _), x, _) => {
2020-11-12 05:37:42 +01:00
*stmt = mem::take(&mut x.0);
optimize_stmt(stmt, state, true);
}
2020-03-18 03:36:50 +01:00
// if expr { if_block } else { else_block }
2020-11-20 15:23:37 +01:00
Stmt::If(condition, x, _) => {
2020-11-12 05:37:42 +01:00
optimize_expr(condition, state);
optimize_stmt(&mut x.0, state, true);
if let Some(else_block) = x.1.as_mut() {
optimize_stmt(else_block, state, true);
match else_block {
Stmt::Noop(_) => x.1 = None, // Noop -> no else block
_ => (),
}
}
}
2020-10-27 11:18:19 +01:00
2020-11-14 16:43:36 +01:00
// switch const { ... }
Stmt::Switch(expr, x, pos) if expr.is_constant() => {
let value = expr.get_constant_value().unwrap();
let hasher = &mut get_hasher();
value.hash(hasher);
let hash = hasher.finish();
state.set_dirty();
let table = &mut x.0;
if let Some(stmt) = table.get_mut(&hash) {
optimize_stmt(stmt, state, true);
*expr = Expr::Stmt(Box::new(vec![mem::take(stmt)].into()), *pos);
} else if let Some(def_stmt) = x.1.as_mut() {
optimize_stmt(def_stmt, state, true);
*expr = Expr::Stmt(Box::new(vec![mem::take(def_stmt)].into()), *pos);
} else {
*expr = Expr::Unit(*pos);
}
}
// switch
Stmt::Switch(expr, x, _) => {
optimize_expr(expr, state);
x.0.values_mut()
.for_each(|stmt| optimize_stmt(stmt, state, true));
if let Some(def_stmt) = x.1.as_mut() {
optimize_stmt(def_stmt, state, true);
match def_stmt {
Stmt::Noop(_) | Stmt::Expr(Expr::Unit(_)) => x.1 = None,
_ => (),
}
}
}
2020-10-27 11:18:19 +01:00
// while false { block } -> Noop
Stmt::While(Expr::BoolConstant(false, pos), _, _) => {
2020-10-27 11:18:19 +01:00
state.set_dirty();
2020-11-12 05:37:42 +01:00
*stmt = Stmt::Noop(*pos)
2020-10-27 11:18:19 +01:00
}
2020-03-18 03:36:50 +01:00
// while expr { block }
2020-11-12 05:37:42 +01:00
Stmt::While(condition, block, _) => {
optimize_stmt(block, state, false);
optimize_expr(condition, state);
match **block {
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();
2021-01-21 03:32:05 +01:00
let mut statements = vec![Stmt::Expr(mem::take(condition))];
2020-03-17 10:33:37 +01:00
if preserve_result {
statements.push(Stmt::Noop(pos))
}
2020-11-12 05:37:42 +01:00
*stmt = Stmt::Block(statements, pos);
2020-03-17 10:33:37 +01:00
}
2020-11-12 05:37:42 +01:00
_ => (),
2020-10-27 11:18:19 +01:00
}
}
2020-11-20 15:23:37 +01:00
// do { block } while false | do { block } until true -> { block }
Stmt::Do(block, Expr::BoolConstant(true, _), false, _)
| Stmt::Do(block, Expr::BoolConstant(false, _), true, _) => {
state.set_dirty();
optimize_stmt(block.as_mut(), state, false);
*stmt = mem::take(block.as_mut());
}
// do { block } while|until expr
Stmt::Do(block, condition, _, _) => {
optimize_stmt(block.as_mut(), state, false);
optimize_expr(condition, state);
2020-11-12 05:37:42 +01:00
}
2020-03-18 03:36:50 +01:00
// for id in expr { block }
2020-11-20 15:23:37 +01:00
Stmt::For(iterable, x, _) => {
2020-11-12 05:37:42 +01:00
optimize_expr(iterable, state);
optimize_stmt(&mut x.1, state, false);
2020-10-27 12:23:43 +01:00
}
2020-03-18 03:36:50 +01:00
// let id = expr;
2020-11-20 15:23:37 +01:00
Stmt::Let(_, Some(expr), _, _) => optimize_expr(expr, state),
2020-03-18 03:36:50 +01:00
// let id;
2020-11-12 05:37:42 +01:00
Stmt::Let(_, None, _, _) => (),
2020-10-20 17:16:03 +02:00
// import expr as var;
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_module"))]
2020-11-20 15:23:37 +01:00
Stmt::Import(expr, _, _) => optimize_expr(expr, state),
2020-03-18 03:36:50 +01:00
// { block }
2020-10-27 11:18:19 +01:00
Stmt::Block(statements, pos) => {
2020-11-12 05:37:42 +01:00
*stmt = optimize_stmt_block(mem::take(statements), *pos, state, preserve_result, true);
2020-03-09 14:57:07 +01:00
}
2020-10-20 17:16:03 +02:00
// try { block } catch ( var ) { block }
2020-11-06 09:27:40 +01:00
Stmt::TryCatch(x, _, _) if x.0.is_pure() => {
2020-10-20 17:16:03 +02:00
// If try block is pure, there will never be any exceptions
state.set_dirty();
2020-10-28 12:11:17 +01:00
let pos = x.0.position();
2020-11-12 05:37:42 +01:00
optimize_stmt(&mut x.0, state, preserve_result);
let mut statements = match mem::take(&mut x.0) {
2020-10-28 12:11:17 +01:00
Stmt::Block(statements, _) => statements,
stmt => vec![stmt],
};
2020-10-20 17:16:03 +02:00
statements.push(Stmt::Noop(pos));
2020-11-12 05:37:42 +01:00
*stmt = Stmt::Block(statements, pos);
2020-10-20 17:16:03 +02:00
}
// try { block } catch ( var ) { block }
2020-11-20 15:23:37 +01:00
Stmt::TryCatch(x, _, _) => {
2020-11-12 05:37:42 +01:00
optimize_stmt(&mut x.0, state, false);
optimize_stmt(&mut x.2, state, false);
2020-10-27 11:18:19 +01:00
}
2020-11-04 06:11:37 +01:00
// {}
2020-11-04 04:49:02 +01:00
Stmt::Expr(Expr::Stmt(x, pos)) if x.is_empty() => {
2020-10-28 07:10:48 +01:00
state.set_dirty();
2020-11-12 05:37:42 +01:00
*stmt = Stmt::Noop(*pos);
2020-11-04 04:49:02 +01:00
}
2020-11-04 06:11:37 +01:00
// {...};
Stmt::Expr(Expr::Stmt(x, pos)) => {
2020-11-04 04:49:02 +01:00
state.set_dirty();
2020-11-12 05:37:42 +01:00
*stmt = Stmt::Block(mem::take(x).into_vec(), *pos);
2020-10-28 07:10:48 +01:00
}
// expr;
2020-11-20 15:23:37 +01:00
Stmt::Expr(expr) => optimize_expr(expr, state),
2020-03-18 03:36:50 +01:00
// return expr;
2020-11-14 15:55:23 +01:00
Stmt::Return(_, Some(ref mut expr), _) => optimize_expr(expr, state),
2020-11-12 05:37:42 +01:00
2020-03-18 03:36:50 +01:00
// All other statements - skip
2020-11-12 05:37:42 +01:00
_ => (),
2020-03-09 14:57:07 +01:00
}
}
2020-12-26 16:21:16 +01:00
/// Optimize an [expression][Expr].
2020-11-12 05:37:42 +01:00
fn optimize_expr(expr: &mut Expr, state: &mut State) {
2020-03-18 03:36:50 +01:00
// These keywords are handled specially
const DONT_EVAL_KEYWORDS: &[&str] = &[
2020-11-22 08:41:55 +01:00
KEYWORD_PRINT, // side effects
KEYWORD_DEBUG, // side effects
KEYWORD_EVAL, // arbitrary scripts
];
2020-03-17 03:27:43 +01:00
2020-03-09 14:57:07 +01:00
match expr {
2020-11-04 04:49:02 +01:00
// {}
2020-11-12 05:37:42 +01:00
Expr::Stmt(x, pos) if x.is_empty() => { state.set_dirty(); *expr = Expr::Unit(*pos) }
// { stmt; ... } - do not count promotion as dirty because it gets turned back into an array
Expr::Stmt(x, pos) => match optimize_stmt_block(mem::take(x).into_vec(), *pos, state, true, false) {
// {}
Stmt::Noop(_) => { state.set_dirty(); *expr = Expr::Unit(*pos); }
// { stmt, .. }
Stmt::Block(statements, _) => *x = Box::new(statements.into()),
// { expr }
Stmt::Expr(inner) => { state.set_dirty(); *expr = inner; }
2020-10-28 07:10:48 +01:00
// { stmt }
2020-11-12 05:37:42 +01:00
stmt => x.push(stmt),
2020-11-04 04:49:02 +01:00
}
2020-03-18 03:36:50 +01:00
// lhs.rhs
#[cfg(not(feature = "no_object"))]
2020-11-12 05:37:42 +01:00
Expr::Dot(x, _) => match (&mut x.lhs, &mut x.rhs) {
// map.string
2020-10-31 16:26:21 +01:00
(Expr::Map(m, pos), Expr::Property(p)) if m.iter().all(|(_, x)| x.is_pure()) => {
2020-12-25 04:02:29 +01:00
let prop = &p.2.name;
// Map literal where everything is pure - promote the indexed item.
// All other items can be thrown away.
state.set_dirty();
2020-11-12 05:37:42 +01:00
*expr = mem::take(m).into_iter().find(|(x, _)| &x.name == prop)
.map(|(_, mut expr)| { expr.set_position(*pos); expr })
.unwrap_or_else(|| Expr::Unit(*pos));
}
2020-11-03 06:08:19 +01:00
// var.rhs
2020-11-12 05:37:42 +01:00
(Expr::Variable(_), rhs) => optimize_expr(rhs, state),
// lhs.rhs
2020-11-12 05:37:42 +01:00
(lhs, rhs) => { optimize_expr(lhs, state); optimize_expr(rhs, state); }
}
2020-03-11 04:03:18 +01:00
2020-03-18 03:36:50 +01:00
// lhs[rhs]
#[cfg(not(feature = "no_index"))]
2020-11-12 05:37:42 +01:00
Expr::Index(x, _) => match (&mut x.lhs, &mut x.rhs) {
2020-03-18 03:36:50 +01:00
// array[int]
2020-11-12 05:37:42 +01:00
(Expr::Array(a, pos), Expr::IntegerConstant(i, _))
if *i >= 0 && (*i as usize) < a.len() && a.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();
2020-11-12 05:37:42 +01:00
let mut result = a.remove(*i as usize);
result.set_position(*pos);
*expr = result;
}
// map[string]
2020-11-13 03:43:54 +01:00
(Expr::Map(m, pos), Expr::StringConstant(s, _)) if m.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();
2020-11-13 03:43:54 +01:00
*expr = mem::take(m).into_iter().find(|(x, _)| x.name == *s)
2020-11-12 05:37:42 +01:00
.map(|(_, mut expr)| { expr.set_position(*pos); expr })
.unwrap_or_else(|| Expr::Unit(*pos));
}
2020-03-18 03:36:50 +01:00
// string[int]
2020-11-13 03:43:54 +01:00
(Expr::StringConstant(s, pos), Expr::IntegerConstant(i, _)) if *i >= 0 && (*i as usize) < s.chars().count() => {
// String literal indexing - get the character
state.set_dirty();
2020-11-13 03:43:54 +01:00
*expr = Expr::CharConstant(s.chars().nth(*i as usize).unwrap(), *pos);
}
2020-11-03 06:08:19 +01:00
// var[rhs]
2020-11-12 05:37:42 +01:00
(Expr::Variable(_), rhs) => optimize_expr(rhs, state),
2020-03-18 03:36:50 +01:00
// lhs[rhs]
2020-11-12 05:37:42 +01:00
(lhs, rhs) => { optimize_expr(lhs, state); optimize_expr(rhs, state); }
},
2020-11-14 12:04:49 +01:00
// [ constant .. ]
#[cfg(not(feature = "no_index"))]
2020-11-15 05:07:35 +01:00
Expr::Array(_, _) if expr.is_constant() => {
2020-11-14 12:04:49 +01:00
state.set_dirty();
2020-11-15 05:07:35 +01:00
*expr = Expr::DynamicConstant(Box::new(expr.get_constant_value().unwrap()), expr.position());
2020-11-14 12:04:49 +01:00
}
2020-03-18 03:36:50 +01:00
// [ items .. ]
#[cfg(not(feature = "no_index"))]
2020-11-15 05:07:35 +01:00
Expr::Array(x, _) => x.iter_mut().for_each(|expr| optimize_expr(expr, state)),
2020-11-14 12:04:49 +01:00
// #{ key:constant, .. }
#[cfg(not(feature = "no_object"))]
2020-11-15 05:07:35 +01:00
Expr::Map(_, _) if expr.is_constant()=> {
2020-11-14 12:04:49 +01:00
state.set_dirty();
2020-11-15 05:07:35 +01:00
*expr = Expr::DynamicConstant(Box::new(expr.get_constant_value().unwrap()), expr.position());
2020-11-14 12:04:49 +01:00
}
2020-11-12 05:37:42 +01:00
// #{ key:value, .. }
2020-03-29 17:53:35 +02:00
#[cfg(not(feature = "no_object"))]
2020-11-15 05:07:35 +01:00
Expr::Map(x, _) => x.iter_mut().for_each(|(_, expr)| optimize_expr(expr, state)),
2020-04-06 11:47:34 +02:00
// lhs in rhs
2020-11-12 05:37:42 +01:00
Expr::In(x, _) => match (&mut x.lhs, &mut x.rhs) {
2020-04-06 11:47:34 +02:00
// "xxx" in "xxxxx"
2020-11-13 03:43:54 +01:00
(Expr::StringConstant(a, pos), Expr::StringConstant(b, _)) => {
2020-04-06 11:47:34 +02:00
state.set_dirty();
*expr = Expr::BoolConstant( b.contains(a.as_str()), *pos);
2020-04-06 11:47:34 +02:00
}
// 'x' in "xxxxx"
2020-11-13 03:43:54 +01:00
(Expr::CharConstant(a, pos), Expr::StringConstant(b, _)) => {
2020-04-06 11:47:34 +02:00
state.set_dirty();
*expr = Expr::BoolConstant(b.contains(*a), *pos);
2020-04-06 11:47:34 +02:00
}
// "xxx" in #{...}
2020-11-13 03:43:54 +01:00
(Expr::StringConstant(a, pos), Expr::Map(b, _)) => {
2020-04-06 11:47:34 +02:00
state.set_dirty();
*expr = Expr::BoolConstant(b.iter().find(|(x, _)| x.name == *a).is_some(), *pos);
2020-04-06 11:47:34 +02:00
}
// 'x' in #{...}
2020-10-31 16:26:21 +01:00
(Expr::CharConstant(a, pos), Expr::Map(b, _)) => {
2020-04-06 11:47:34 +02:00
state.set_dirty();
2020-10-31 07:13:45 +01:00
let ch = a.to_string();
*expr = Expr::BoolConstant(b.iter().find(|(x, _)| x.name == &ch).is_some(), *pos);
2020-04-06 11:47:34 +02:00
}
// lhs in rhs
2020-11-12 05:37:42 +01:00
(lhs, rhs) => { optimize_expr(lhs, state); optimize_expr(rhs, state); }
2020-04-06 11:47:34 +02:00
},
2020-03-18 03:36:50 +01:00
// lhs && rhs
2020-11-12 05:37:42 +01:00
Expr::And(x, _) => match (&mut x.lhs, &mut x.rhs) {
2020-03-18 03:36:50 +01:00
// true && rhs -> rhs
(Expr::BoolConstant(true, _), rhs) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-11-12 05:37:42 +01:00
optimize_expr(rhs, state);
*expr = mem::take(rhs);
2020-03-09 14:57:07 +01:00
}
2020-03-18 03:36:50 +01:00
// false && rhs -> false
(Expr::BoolConstant(false, pos), _) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
*expr = Expr::BoolConstant(false, *pos);
2020-03-09 14:57:07 +01:00
}
2020-03-18 03:36:50 +01:00
// lhs && true -> lhs
(lhs, Expr::BoolConstant(true, _)) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-11-12 05:37:42 +01:00
optimize_expr(lhs, state);
*expr = mem::take(lhs);
2020-03-09 14:57:07 +01:00
}
2020-03-18 03:36:50 +01:00
// lhs && rhs
2020-11-12 05:37:42 +01:00
(lhs, rhs) => { optimize_expr(lhs, state); optimize_expr(rhs, state); }
2020-03-09 14:57:07 +01:00
},
2020-03-18 03:36:50 +01:00
// lhs || rhs
2020-11-12 05:37:42 +01:00
Expr::Or(ref mut x, _) => match (&mut x.lhs, &mut x.rhs) {
2020-03-18 03:36:50 +01:00
// false || rhs -> rhs
(Expr::BoolConstant(false, _), rhs) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-11-12 05:37:42 +01:00
optimize_expr(rhs, state);
*expr = mem::take(rhs);
2020-03-09 14:57:07 +01:00
}
2020-03-18 03:36:50 +01:00
// true || rhs -> true
(Expr::BoolConstant(true, pos), _) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
*expr = Expr::BoolConstant(true, *pos);
2020-03-09 14:57:07 +01:00
}
2020-03-18 03:36:50 +01:00
// lhs || false
(lhs, Expr::BoolConstant(false, _)) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-11-12 05:37:42 +01:00
optimize_expr(lhs, state);
*expr = mem::take(lhs);
2020-03-09 14:57:07 +01:00
}
2020-03-18 03:36:50 +01:00
// lhs || rhs
2020-11-12 05:37:42 +01:00
(lhs, rhs) => { optimize_expr(lhs, state); optimize_expr(rhs, state); }
2020-03-09 14:57:07 +01:00
},
2020-03-11 16:43:10 +01:00
2021-01-12 16:52:50 +01:00
// eval!
Expr::FnCall(x, _) if x.name == KEYWORD_EVAL => {
state.propagate_constants = false;
}
2020-04-01 03:51:33 +02:00
// Do not call some special keywords
2020-11-12 05:37:42 +01:00
Expr::FnCall(x, _) if DONT_EVAL_KEYWORDS.contains(&x.name.as_ref()) => {
x.args.iter_mut().for_each(|a| optimize_expr(a, state));
}
2020-03-19 12:53:42 +01:00
2020-10-09 05:15:25 +02:00
// Call built-in operators
2020-11-12 05:37:42 +01:00
Expr::FnCall(x, pos)
2020-10-31 07:13:45 +01:00
if x.namespace.is_none() // Non-qualified
&& state.optimization_level == OptimizationLevel::Simple // simple optimizations
2020-10-31 07:13:45 +01:00
&& x.args.len() == 2 // binary call
&& x.args.iter().all(Expr::is_constant) // all arguments are constants
&& !is_valid_identifier(x.name.chars()) // cannot be scripted
=> {
2020-11-12 05:37:42 +01:00
let arg_values: StaticVec<_> = x.args.iter().map(|e| e.get_constant_value().unwrap()).collect();
let arg_types: StaticVec<_> = arg_values.iter().map(Dynamic::type_id).collect();
// Search for overloaded operators (can override built-in).
if !state.engine.has_override_by_name_and_arguments(Some(&state.mods), None, state.lib, x.name.as_ref(), arg_types.as_ref(), false) {
2020-11-12 05:37:42 +01:00
if let Some(result) = run_builtin_binary_op(x.name.as_ref(), &arg_values[0], &arg_values[1])
.ok().flatten()
2020-11-12 05:37:42 +01:00
.and_then(|result| map_dynamic_to_expr(result, *pos))
{
state.set_dirty();
2020-11-12 05:37:42 +01:00
*expr = result;
return;
}
}
2020-11-12 05:37:42 +01:00
x.args.iter_mut().for_each(|a| optimize_expr(a, state));
}
2020-03-18 03:36:50 +01:00
// Eagerly call functions
2020-11-12 05:37:42 +01:00
Expr::FnCall(x, pos)
2020-10-31 07:13:45 +01:00
if x.namespace.is_none() // Non-qualified
&& state.optimization_level == OptimizationLevel::Full // full optimizations
2020-10-31 07:13:45 +01:00
&& x.args.iter().all(Expr::is_constant) // all arguments are constants
2020-03-17 03:27:43 +01:00
=> {
// First search for script-defined functions (can override built-in)
2020-10-05 06:09:45 +02:00
#[cfg(not(feature = "no_function"))]
2020-11-12 05:37:42 +01:00
let has_script_fn = state.lib.iter().any(|&m| m.get_script_fn(x.name.as_ref(), x.args.len(), false).is_some());
2020-10-05 06:09:45 +02:00
#[cfg(feature = "no_function")]
let has_script_fn = false;
if !has_script_fn {
2020-11-12 05:37:42 +01:00
let mut arg_values: StaticVec<_> = x.args.iter().map(|e| e.get_constant_value().unwrap()).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-11-12 05:37:42 +01:00
let arg_for_type_of = if x.name == KEYWORD_TYPE_OF && arg_values.len() == 1 {
state.engine.map_type_name(arg_values[0].type_name())
} else {
""
};
2020-11-12 05:37:42 +01:00
if let Some(result) = call_fn_with_constant_arguments(&state, x.name.as_ref(), arg_values.as_mut())
.or_else(|| {
if !arg_for_type_of.is_empty() {
// Handle `type_of()`
Some(arg_for_type_of.to_string().into())
} else {
// Otherwise use the default value, if any
2020-11-20 09:52:28 +01:00
x.def_value.clone()
}
})
2020-11-12 05:37:42 +01:00
.and_then(|result| map_dynamic_to_expr(result, *pos))
{
2020-06-01 09:25:22 +02:00
state.set_dirty();
2020-11-12 05:37:42 +01:00
*expr = result;
return;
}
}
2020-11-12 05:37:42 +01:00
x.args.iter_mut().for_each(|a| optimize_expr(a, state));
}
2020-03-19 12:53:42 +01:00
2020-03-18 03:36:50 +01:00
// id(args ..) -> optimize function call arguments
2020-11-12 05:37:42 +01:00
Expr::FnCall(x, _) => x.args.iter_mut().for_each(|a| optimize_expr(a, state)),
2020-03-19 12:53:42 +01:00
2020-03-18 03:36:50 +01:00
// constant-name
2020-12-24 16:22:50 +01:00
Expr::Variable(x) if x.1.is_none() && state.find_constant(&x.2.name).is_some() => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
// Replace constant with value
2020-12-24 16:22:50 +01:00
let mut result = state.find_constant(&x.2.name).unwrap().clone();
result.set_position(x.2.pos);
2020-11-12 05:37:42 +01:00
*expr = result;
2020-03-13 11:12:41 +01:00
}
2020-03-19 12:53:42 +01:00
2020-07-09 13:54:28 +02:00
// Custom syntax
2021-01-12 16:52:50 +01:00
Expr::Custom(x, _) => {
if x.scope_delta != 0 {
state.propagate_constants = false;
}
x.keywords.iter_mut().for_each(|expr| optimize_expr(expr, state));
}
2020-07-09 13:54:28 +02:00
2020-03-18 03:36:50 +01:00
// All other expressions - skip
2020-11-12 05:37:42 +01:00
_ => (),
2020-03-09 14:57:07 +01:00
}
}
2020-12-26 16:21:16 +01:00
/// Optimize a block of [statements][Stmt] at top level.
2020-11-25 02:36:06 +01:00
fn optimize_top_level(
2020-11-15 06:49:54 +01:00
mut statements: Vec<Stmt>,
2020-04-16 17:31:48 +02:00
engine: &Engine,
scope: &Scope,
2020-10-20 04:54:32 +02:00
lib: &[&Module],
level: OptimizationLevel,
) -> Vec<Stmt> {
// If optimization level is None then skip optimizing
if level == OptimizationLevel::None {
2020-11-15 06:49:54 +01:00
statements.shrink_to_fit();
return statements;
}
// Set up the state
let mut state = State::new(engine, lib, level);
// Add constants and variables from the scope
scope.iter().for_each(|(name, constant, value)| {
if !constant {
state.push_var(name, AccessMode::ReadWrite, Expr::Unit(Position::NONE));
} else if let Some(val) = map_dynamic_to_expr(value, Position::NONE) {
state.push_var(name, AccessMode::ReadOnly, val);
} else {
state.push_var(name, AccessMode::ReadOnly, Expr::Unit(Position::NONE));
}
});
let orig_constants_len = state.variables.len();
2020-03-18 03:36:50 +01:00
// Optimization loop
2020-03-09 14:57:07 +01:00
loop {
state.reset();
state.restore_var(orig_constants_len);
2020-03-09 14:57:07 +01:00
2020-11-15 06:49:54 +01:00
let num_statements = statements.len();
2020-11-15 06:49:54 +01:00
statements.iter_mut().enumerate().for_each(|(i, stmt)| {
2020-11-12 05:37:42 +01:00
match stmt {
Stmt::Const(var_def, expr, _, _) if expr.is_some() => {
// Load constants
let value_expr = expr.as_mut().unwrap();
optimize_expr(value_expr, &mut state);
2020-10-09 05:15:25 +02:00
2020-11-13 11:32:18 +01:00
if value_expr.is_constant() {
state.push_var(&var_def.name, AccessMode::ReadOnly, value_expr.clone());
2020-04-11 12:09:03 +02:00
}
2020-11-12 05:37:42 +01:00
// Keep it in the global scope
if value_expr.is_unit() {
state.set_dirty();
*expr = None;
2020-04-11 12:09:03 +02:00
}
2020-03-13 11:12:41 +01:00
}
2020-11-12 05:37:42 +01:00
Stmt::Const(var_def, None, _, _) => {
state.push_var(&var_def.name, AccessMode::ReadOnly, Expr::Unit(var_def.pos));
}
2021-01-12 16:52:50 +01:00
Stmt::Let(var_def, expr, _, _) => {
if let Some(value_expr) = expr {
optimize_expr(value_expr, &mut state);
}
state.push_var(
&var_def.name,
AccessMode::ReadWrite,
Expr::Unit(var_def.pos),
);
2020-11-12 05:37:42 +01:00
}
_ => {
// Keep all variable declarations at this level
// and always keep the last return value
let keep = match stmt {
Stmt::Let(_, _, _, _) | Stmt::Const(_, _, _, _) => true,
2020-11-12 05:37:42 +01:00
#[cfg(not(feature = "no_module"))]
Stmt::Import(_, _, _) => true,
_ => i == num_statements - 1,
};
optimize_stmt(stmt, &mut state, keep);
}
}
});
2020-03-09 14:57:07 +01:00
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-11-15 06:49:54 +01:00
let last_stmt = statements.pop();
2020-03-11 16:43:10 +01:00
// Remove all pure statements at global level
2020-11-15 06:49:54 +01:00
statements.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-11-15 06:49:54 +01:00
if !statements.is_empty() || !stmt.is_noop() {
statements.push(stmt);
2020-03-18 11:41:18 +01:00
}
2020-03-11 16:43:10 +01:00
}
2020-11-15 06:49:54 +01:00
statements.shrink_to_fit();
statements
2020-03-09 14:57:07 +01:00
}
2020-11-25 02:36:06 +01:00
/// Optimize an [`AST`].
2020-03-18 11:41:18 +01:00
pub fn optimize_into_ast(
engine: &Engine,
scope: &Scope,
2020-11-15 06:49:54 +01:00
mut statements: Vec<Stmt>,
2020-07-26 09:53:22 +02:00
_functions: Vec<ScriptFnDef>,
level: OptimizationLevel,
) -> AST {
2020-07-31 16:30:23 +02:00
let level = if cfg!(feature = "no_optimize") {
OptimizationLevel::None
} else {
level
};
2020-04-10 06:16:39 +02:00
2020-09-24 17:32:54 +02:00
#[cfg(not(feature = "no_function"))]
let lib = {
let mut module = Module::new();
if !level.is_none() {
// We only need the script library's signatures for optimization purposes
let mut lib2 = Module::new();
2020-07-26 09:53:22 +02:00
_functions
.iter()
2020-11-25 02:36:06 +01:00
.map(|fn_def| ScriptFnDef {
name: fn_def.name.clone(),
access: fn_def.access,
body: Default::default(),
params: fn_def.params.clone(),
#[cfg(not(feature = "no_closure"))]
externals: fn_def.externals.clone(),
lib: None,
#[cfg(not(feature = "no_module"))]
mods: Default::default(),
comments: Default::default(),
})
2020-07-12 05:46:53 +02:00
.for_each(|fn_def| {
lib2.set_script_fn(fn_def);
});
2020-07-26 09:53:22 +02:00
_functions
.into_iter()
.map(|mut fn_def| {
let pos = fn_def.body.position();
// Optimize the function body
2020-11-25 02:36:06 +01:00
let mut body = optimize_top_level(
vec![fn_def.body],
engine,
&Scope::new(),
&[&lib2],
level,
);
// {} -> Noop
fn_def.body = match body.pop().unwrap_or_else(|| Stmt::Noop(pos)) {
// { return val; } -> val
2020-11-16 09:28:04 +01:00
Stmt::Return((crate::ast::ReturnType::Return, _), Some(expr), _) => {
Stmt::Expr(expr)
}
// { return; } -> ()
2020-11-16 09:28:04 +01:00
Stmt::Return((crate::ast::ReturnType::Return, pos), None, _) => {
2020-10-27 11:18:19 +01:00
Stmt::Expr(Expr::Unit(pos))
}
// All others
stmt => stmt,
};
2020-11-25 02:36:06 +01:00
fn_def
})
2020-07-12 05:46:53 +02:00
.for_each(|fn_def| {
module.set_script_fn(fn_def);
});
} else {
2020-07-26 09:53:22 +02:00
_functions.into_iter().for_each(|fn_def| {
2020-11-25 02:36:06 +01:00
module.set_script_fn(fn_def);
2020-07-12 05:46:53 +02:00
});
}
module
};
2020-09-24 17:32:54 +02:00
#[cfg(feature = "no_function")]
let lib = Default::default();
2020-11-15 06:49:54 +01:00
statements.shrink_to_fit();
2020-05-05 09:00:10 +02:00
AST::new(
match level {
OptimizationLevel::None => statements,
OptimizationLevel::Simple | OptimizationLevel::Full => {
2020-11-25 02:36:06 +01:00
optimize_top_level(statements, engine, &scope, &[&lib], level)
}
},
2020-05-05 09:00:10 +02:00
lib,
)
}