rhai/src/optimize.rs

898 lines
32 KiB
Rust
Raw Normal View History

//! Module implementing the AST optimizer.
2020-10-31 07:13:45 +01:00
use crate::ast::{BinaryExpr, CustomExpr, Expr, FnCallInfo, ScriptFnDef, Stmt, AST};
2020-10-28 15:18:44 +01:00
use crate::dynamic::Dynamic;
2020-07-19 11:14:55 +02:00
use crate::engine::{
2020-10-09 07:47:35 +02:00
Engine, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_IS_DEF_FN, KEYWORD_IS_DEF_VAR, KEYWORD_PRINT,
KEYWORD_TYPE_OF,
2020-07-19 11:14:55 +02:00
};
use crate::fn_call::run_builtin_binary_op;
use crate::module::Module;
2020-10-29 04:37:51 +01:00
use crate::parser::map_dynamic_to_expr;
2020-11-01 15:46:46 +01:00
use crate::scope::Scope;
2020-11-02 06:18:37 +01:00
use crate::token::{is_valid_identifier, NO_POS};
2020-10-28 15:18:44 +01:00
use crate::{calc_native_fn_hash, StaticVec};
2020-03-09 14:57:07 +01:00
2020-09-24 17:32:54 +02:00
#[cfg(not(feature = "no_function"))]
2020-10-29 04:37:51 +01:00
use crate::ast::ReturnType;
2020-09-24 17:32:54 +02:00
2020-03-17 19:26:11 +01:00
use crate::stdlib::{
2020-03-18 11:41:18 +01:00
boxed::Box,
iter::empty,
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.
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-05-31 06:36:31 +02:00
/// Is the `OptimizationLevel` Simple.
2020-08-05 16:53:01 +02:00
#[cfg(not(feature = "no_optimize"))]
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-04-10 06:16:39 +02:00
/// Is the `OptimizationLevel` Full.
2020-08-05 16:53:01 +02:00
#[cfg(not(feature = "no_optimize"))]
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-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.
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,
constants: vec![],
engine,
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-03-18 03:36:50 +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-03-18 03:36:50 +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
/// Does a constant exist?
2020-10-08 16:25:50 +02:00
#[inline(always)]
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-10-08 16:25:50 +02:00
#[inline(always)]
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-10-08 16:25:50 +02:00
#[inline(always)]
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-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> {
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
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(
&mut Default::default(),
state.lib,
2020-05-23 12:59:28 +02:00
fn_name,
2020-07-30 12:18:28 +02:00
hash_fn,
2020-05-24 05:57:46 +02:00
arg_values.iter_mut().collect::<StaticVec<_>>().as_mut(),
false,
true,
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-03-18 03:36:50 +01:00
/// Optimize a statement.
2020-05-30 04:27:48 +02:00
fn optimize_stmt(stmt: Stmt, state: &mut State, preserve_result: bool) -> Stmt {
2020-03-09 14:57:07 +01:00
match stmt {
2020-10-27 16:21:20 +01:00
// id op= expr
Stmt::Assignment(x, pos) => Stmt::Assignment(
Box::new((optimize_expr(x.0, state), x.1, optimize_expr(x.2, state))),
pos,
),
2020-10-27 11:18:19 +01:00
// if false { if_block } -> Noop
2020-10-27 12:23:43 +01:00
Stmt::IfThenElse(Expr::False(pos), x, _) if x.1.is_none() => {
2020-10-27 11:18:19 +01:00
state.set_dirty();
Stmt::Noop(pos)
}
// if true { if_block } -> if_block
2020-10-27 12:23:43 +01:00
Stmt::IfThenElse(Expr::True(_), x, _) if x.1.is_none() => optimize_stmt(x.0, state, true),
2020-03-18 03:36:50 +01:00
// if expr { Noop }
2020-10-27 12:23:43 +01:00
Stmt::IfThenElse(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();
let expr = optimize_expr(condition, state);
2020-03-12 16:46:52 +01:00
2020-03-18 03:36:50 +01:00
if preserve_result {
// -> { expr, Noop }
2020-10-27 11:18:19 +01:00
let mut statements = Vec::new();
statements.push(Stmt::Expr(expr));
2020-10-27 12:23:43 +01:00
statements.push(x.0);
2020-10-27 11:18:19 +01:00
Stmt::Block(statements, 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-03-12 16:46:52 +01:00
}
}
2020-03-18 03:36:50 +01:00
// if expr { if_block }
2020-10-27 12:23:43 +01:00
Stmt::IfThenElse(condition, x, pos) if x.1.is_none() => Stmt::IfThenElse(
2020-10-27 11:18:19 +01:00
optimize_expr(condition, state),
2020-10-27 12:23:43 +01:00
Box::new((optimize_stmt(x.0, state, true), None)),
2020-10-27 11:18:19 +01:00
pos,
),
// if false { if_block } else { else_block } -> else_block
2020-10-27 12:23:43 +01:00
Stmt::IfThenElse(Expr::False(_), x, _) if x.1.is_some() => {
optimize_stmt(x.1.unwrap(), state, true)
2020-10-27 11:18:19 +01:00
}
// if true { if_block } else { else_block } -> if_block
2020-10-27 12:23:43 +01:00
Stmt::IfThenElse(Expr::True(_), x, _) => optimize_stmt(x.0, state, true),
2020-03-18 03:36:50 +01:00
// if expr { if_block } else { else_block }
2020-10-27 12:23:43 +01:00
Stmt::IfThenElse(condition, x, pos) => Stmt::IfThenElse(
2020-10-27 11:18:19 +01:00
optimize_expr(condition, state),
2020-10-27 12:23:43 +01:00
Box::new((
optimize_stmt(x.0, state, true),
match optimize_stmt(x.1.unwrap(), state, true) {
Stmt::Noop(_) => None, // Noop -> no else block
stmt => Some(stmt),
},
)),
2020-10-27 11:18:19 +01:00
pos,
),
// while false { block } -> Noop
Stmt::While(Expr::False(pos), _, _) => {
state.set_dirty();
Stmt::Noop(pos)
}
// while true { block } -> loop { block }
Stmt::While(Expr::True(_), block, pos) => {
Stmt::Loop(Box::new(optimize_stmt(*block, state, false)), pos)
}
2020-03-18 03:36:50 +01:00
// while expr { block }
2020-10-27 11:18:19 +01:00
Stmt::While(condition, block, pos) => {
match optimize_stmt(*block, 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();
2020-10-27 11:18:19 +01:00
let mut statements = Vec::new();
statements.push(Stmt::Expr(optimize_expr(condition, state)));
2020-03-17 10:33:37 +01:00
if preserve_result {
statements.push(Stmt::Noop(pos))
}
2020-10-27 11:18:19 +01:00
Stmt::Block(statements, pos)
2020-03-17 10:33:37 +01:00
}
2020-03-18 03:36:50 +01:00
// while expr { block }
2020-10-27 11:18:19 +01:00
stmt => Stmt::While(optimize_expr(condition, state), Box::new(stmt), pos),
}
}
2020-03-18 03:36:50 +01:00
// loop { block }
2020-10-27 11:18:19 +01:00
Stmt::Loop(block, pos) => match optimize_stmt(*block, state, false) {
2020-03-18 03:36:50 +01:00
// 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-10-27 11:18:19 +01:00
stmt => Stmt::Loop(Box::new(stmt), pos),
2020-03-09 14:57:07 +01:00
},
2020-03-18 03:36:50 +01:00
// for id in expr { block }
2020-10-27 12:23:43 +01:00
Stmt::For(iterable, x, pos) => {
let (var_name, block) = *x;
Stmt::For(
optimize_expr(iterable, state),
Box::new((var_name, optimize_stmt(block, state, false))),
pos,
)
}
2020-03-18 03:36:50 +01:00
// let id = expr;
2020-10-27 11:18:19 +01:00
Stmt::Let(name, Some(expr), pos) => Stmt::Let(name, Some(optimize_expr(expr, state)), pos),
2020-03-18 03:36:50 +01:00
// let id;
2020-10-27 11:18:19 +01:00
stmt @ Stmt::Let(_, None, _) => stmt,
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-10-27 11:18:19 +01:00
Stmt::Import(expr, alias, pos) => Stmt::Import(optimize_expr(expr, state), alias, pos),
2020-03-18 03:36:50 +01:00
// { block }
2020-10-27 11:18:19 +01:00
Stmt::Block(statements, pos) => {
let orig_len = statements.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
2020-03-09 14:57:07 +01:00
2020-03-18 03:36:50 +01:00
// Optimize each statement in the block
2020-10-27 11:18:19 +01:00
let mut result: Vec<_> = statements
.into_iter()
.map(|stmt| match stmt {
// Add constant literals into the state
2020-10-28 12:11:17 +01:00
Stmt::Const(var_def, Some(expr), pos) if expr.is_literal() => {
2020-10-27 11:18:19 +01:00
state.set_dirty();
2020-10-28 12:11:17 +01:00
state.push_constant(&var_def.name, expr);
2020-10-27 11:18:19 +01:00
Stmt::Noop(pos) // No need to keep constants
}
2020-10-28 12:11:17 +01:00
Stmt::Const(var_def, Some(expr), pos) if expr.is_literal() => {
2020-10-27 11:18:19 +01:00
let expr = optimize_expr(expr, state);
2020-10-28 12:11:17 +01:00
Stmt::Const(var_def, Some(expr), pos)
2020-10-27 11:18:19 +01:00
}
2020-10-28 12:11:17 +01:00
Stmt::Const(var_def, None, pos) => {
2020-10-27 11:18:19 +01:00
state.set_dirty();
2020-10-28 12:11:17 +01:00
state.push_constant(&var_def.name, Expr::Unit(var_def.pos));
2020-10-27 11:18:19 +01:00
Stmt::Noop(pos) // No need to keep constants
}
// Optimize the statement
stmt => optimize_stmt(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 {
2020-10-27 11:18:19 +01:00
Stmt::Let(_, expr, _) => {
removed = expr.as_ref().map(Expr::is_pure).unwrap_or(true)
}
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_module"))]
2020-10-27 11:18:19 +01:00
Stmt::Import(expr, _, _) => removed = expr.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-10-27 11:18:19 +01:00
.map(|(i, stmt)| optimize_stmt(stmt, 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 {
2020-10-27 11:18:19 +01:00
Stmt::ReturnWithVal(_, _, _) | Stmt::Break(_) => dead_code = true,
2020-03-17 10:33:37 +01:00
_ => (),
}
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
2020-10-27 11:18:19 +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-07-26 09:53:22 +02:00
// Only one let statement - leave it alone
2020-10-27 11:18:19 +01:00
[x] if matches!(x, Stmt::Let(_, _, _)) => Stmt::Block(result, pos),
2020-07-26 09:53:22 +02:00
// Only one import statement - leave it alone
#[cfg(not(feature = "no_module"))]
2020-10-27 11:18:19 +01:00
[x] if matches!(x, Stmt::Import(_, _, _)) => Stmt::Block(result, 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)
}
2020-10-27 11:18:19 +01:00
_ => Stmt::Block(result, pos),
2020-03-09 14:57:07 +01:00
}
}
2020-10-20 17:16:03 +02:00
// try { block } catch ( var ) { block }
2020-10-28 12:11:17 +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();
let mut statements = match optimize_stmt(x.0, state, preserve_result) {
Stmt::Block(statements, _) => statements,
stmt => vec![stmt],
};
2020-10-20 17:16:03 +02:00
statements.push(Stmt::Noop(pos));
2020-10-27 11:18:19 +01:00
Stmt::Block(statements, pos)
2020-10-20 17:16:03 +02:00
}
// try { block } catch ( var ) { block }
2020-10-27 11:18:19 +01:00
Stmt::TryCatch(x) => {
2020-10-28 12:11:17 +01:00
let (try_block, var_name, catch_block, pos) = *x;
2020-10-27 11:18:19 +01:00
Stmt::TryCatch(Box::new((
2020-10-28 12:11:17 +01:00
optimize_stmt(try_block, state, false),
2020-10-27 11:18:19 +01:00
var_name,
2020-10-28 12:11:17 +01:00
optimize_stmt(catch_block, state, false),
pos,
2020-10-27 11:18:19 +01:00
)))
}
2020-03-18 03:36:50 +01:00
// expr;
2020-10-31 07:13:45 +01:00
Stmt::Expr(Expr::Stmt(x, _)) if matches!(*x, Stmt::Expr(_)) => {
2020-10-28 07:10:48 +01:00
state.set_dirty();
2020-10-31 07:13:45 +01:00
optimize_stmt(*x, state, preserve_result)
2020-10-28 07:10:48 +01:00
}
// expr;
2020-10-27 11:18:19 +01:00
Stmt::Expr(expr) => Stmt::Expr(optimize_expr(expr, state)),
2020-03-18 03:36:50 +01:00
// return expr;
2020-10-27 11:18:19 +01:00
Stmt::ReturnWithVal(ret, Some(expr), pos) => {
Stmt::ReturnWithVal(ret, Some(optimize_expr(expr, state)), pos)
}
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.
2020-05-30 04:27:48 +02:00
fn optimize_expr(expr: Expr, state: &mut State) -> Expr {
2020-03-18 03:36:50 +01:00
// These keywords are handled specially
const DONT_EVAL_KEYWORDS: &[&str] = &[
2020-10-09 07:47:35 +02:00
KEYWORD_PRINT, // side effects
KEYWORD_DEBUG, // side effects
KEYWORD_EVAL, // arbitrary scripts
KEYWORD_IS_DEF_FN, // functions collection is volatile
KEYWORD_IS_DEF_VAR, // variables scope is volatile
];
2020-03-17 03:27:43 +01:00
2020-03-09 14:57:07 +01:00
match expr {
2020-05-30 04:27:48 +02:00
// expr - do not promote because there is a reason it is wrapped in an `Expr::Expr`
Expr::Expr(x) => Expr::Expr(Box::new(optimize_expr(*x, state))),
2020-10-28 07:10:48 +01:00
// { stmt }
2020-10-31 07:13:45 +01:00
Expr::Stmt(x, pos) => match *x {
2020-10-28 07:10:48 +01:00
// {} -> ()
2020-03-09 14:57:07 +01:00
Stmt::Noop(_) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
2020-10-31 07:13:45 +01:00
Expr::Unit(pos)
2020-03-09 14:57:07 +01:00
}
2020-10-28 07:10:48 +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-10-28 07:10:48 +01:00
optimize_expr(expr, state)
2020-03-09 14:57:07 +01:00
}
2020-10-28 07:10:48 +01:00
// { stmt }
2020-10-31 07:13:45 +01:00
stmt => Expr::Stmt(Box::new(optimize_stmt(stmt, state, true)), pos),
2020-03-09 14:57:07 +01:00
},
2020-03-18 03:36:50 +01:00
// lhs.rhs
#[cfg(not(feature = "no_object"))]
2020-10-31 16:26:21 +01:00
Expr::Dot(x, dot_pos) => match (x.lhs, 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-11-02 16:54:19 +01:00
let prop = &p.1.name;
// Map literal where everything is pure - promote the indexed item.
// All other items can be thrown away.
state.set_dirty();
2020-10-31 16:26:21 +01:00
m.into_iter().find(|(x, _)| &x.name == prop)
.map(|(_, mut expr)| { expr.set_position(pos); expr })
.unwrap_or_else(|| Expr::Unit(pos))
}
// lhs.rhs
2020-10-27 16:00:05 +01:00
(lhs, rhs) => Expr::Dot(Box::new(BinaryExpr {
lhs: optimize_expr(lhs, state),
rhs: optimize_expr(rhs, state),
2020-10-31 16:26:21 +01:00
}), dot_pos)
}
2020-03-11 04:03:18 +01:00
2020-03-18 03:36:50 +01:00
// lhs[rhs]
#[cfg(not(feature = "no_index"))]
2020-10-31 16:26:21 +01:00
Expr::Index(x, idx_pos) => match (x.lhs, x.rhs) {
2020-03-18 03:36:50 +01:00
// array[int]
2020-10-31 16:26:21 +01:00
(Expr::Array(mut 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-10-31 16:26:21 +01:00
let mut expr = a.remove(i as usize);
expr.set_position(pos);
expr
}
// map[string]
2020-10-31 16:26:21 +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-10-31 16:26:21 +01:00
m.into_iter().find(|(x, _)| x.name == s.name)
.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-10-31 07:13:45 +01:00
(Expr::StringConstant(s), Expr::IntegerConstant(i, _)) if i >= 0 && (i as usize) < s.name.chars().count() => {
// String literal indexing - get the character
state.set_dirty();
2020-10-31 07:13:45 +01:00
Expr::CharConstant(s.name.chars().nth(i as usize).unwrap(), s.pos)
}
2020-03-18 03:36:50 +01:00
// lhs[rhs]
2020-10-27 16:00:05 +01:00
(lhs, rhs) => Expr::Index(Box::new(BinaryExpr {
lhs: optimize_expr(lhs, state),
rhs: optimize_expr(rhs, state),
2020-10-31 16:26:21 +01:00
}), idx_pos),
},
2020-03-18 03:36:50 +01:00
// [ items .. ]
#[cfg(not(feature = "no_index"))]
2020-10-31 16:26:21 +01:00
Expr::Array(a, pos) => Expr::Array(Box::new(a
2020-05-17 16:19:49 +02:00
.into_iter().map(|expr| optimize_expr(expr, state))
2020-10-31 16:26:21 +01:00
.collect()), pos),
2020-03-29 17:53:35 +02:00
// [ items .. ]
#[cfg(not(feature = "no_object"))]
2020-10-31 16:26:21 +01:00
Expr::Map(m, pos) => Expr::Map(Box::new(m
.into_iter().map(|(key, expr)| (key, optimize_expr(expr, state)))
.collect()), pos),
2020-04-06 11:47:34 +02:00
// lhs in rhs
2020-10-31 16:26:21 +01:00
Expr::In(x, in_pos) => match (x.lhs, x.rhs) {
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();
2020-10-28 12:11:17 +01:00
if b.name.contains(a.name.as_str()) { Expr::True(a.pos) } else { Expr::False(a.pos) }
2020-04-06 11:47:34 +02:00
}
// 'x' in "xxxxx"
2020-10-31 07:13:45 +01:00
(Expr::CharConstant(a, pos), Expr::StringConstant(b)) => {
2020-04-06 11:47:34 +02:00
state.set_dirty();
2020-10-31 07:13:45 +01:00
if b.name.contains(a) { Expr::True(pos) } else { Expr::False(pos) }
2020-04-06 11:47:34 +02:00
}
// "xxx" in #{...}
2020-10-31 16:26:21 +01:00
(Expr::StringConstant(a), Expr::Map(b, _)) => {
2020-04-06 11:47:34 +02:00
state.set_dirty();
2020-10-31 16:26:21 +01:00
if b.iter().find(|(x, _)| x.name == a.name).is_some() {
2020-10-28 12:11:17 +01:00
Expr::True(a.pos)
2020-04-06 11:47:34 +02:00
} else {
2020-10-28 12:11:17 +01:00
Expr::False(a.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();
2020-04-06 11:47:34 +02:00
2020-10-31 16:26:21 +01:00
if b.iter().find(|(x, _)| x.name == &ch).is_some() {
2020-10-31 07:13:45 +01:00
Expr::True(pos)
2020-04-06 11:47:34 +02:00
} else {
2020-10-31 07:13:45 +01:00
Expr::False(pos)
2020-04-06 11:47:34 +02:00
}
}
// lhs in rhs
2020-10-27 16:00:05 +01:00
(lhs, rhs) => Expr::In(Box::new(BinaryExpr {
lhs: optimize_expr(lhs, state),
rhs: optimize_expr(rhs, state),
2020-10-31 16:26:21 +01:00
}), in_pos),
2020-04-06 11:47:34 +02:00
},
2020-03-18 03:36:50 +01:00
// lhs && rhs
2020-10-31 16:26:21 +01:00
Expr::And(x, and_pos) => match (x.lhs, x.rhs) {
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
2020-10-27 16:00:05 +01:00
(lhs, rhs) => Expr::And(Box::new(BinaryExpr {
lhs: optimize_expr(lhs, state),
rhs: optimize_expr(rhs, state),
2020-10-31 16:26:21 +01:00
}), and_pos),
2020-03-09 14:57:07 +01:00
},
2020-03-18 03:36:50 +01:00
// lhs || rhs
2020-10-31 16:26:21 +01:00
Expr::Or(x, or_pos) => match (x.lhs, x.rhs) {
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
2020-10-27 16:00:05 +01:00
(lhs, rhs) => Expr::Or(Box::new(BinaryExpr {
lhs: optimize_expr(lhs, state),
rhs: optimize_expr(rhs, state),
2020-10-31 16:26:21 +01:00
}), or_pos),
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-10-31 16:26:21 +01:00
Expr::FnCall(mut x, pos) if DONT_EVAL_KEYWORDS.contains(&x.name.as_ref()) => {
2020-10-31 07:13:45 +01:00
x.args = x.args.into_iter().map(|a| optimize_expr(a, state)).collect();
2020-10-31 16:26:21 +01:00
Expr::FnCall(x, pos)
}
2020-03-19 12:53:42 +01:00
2020-10-09 05:15:25 +02:00
// Call built-in operators
2020-10-31 16:26:21 +01:00
Expr::FnCall(mut 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-10-31 16:26:21 +01:00
let FnCallInfo { name, args, .. } = x.as_mut();
let arg_values: StaticVec<_> = 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(state.lib, name, arg_types.as_ref(), false) {
if let Some(expr) = run_builtin_binary_op(name, &arg_values[0], &arg_values[1])
.ok().flatten()
2020-10-31 16:26:21 +01:00
.and_then(|result| map_dynamic_to_expr(result, pos))
{
state.set_dirty();
return expr;
}
}
2020-10-31 07:13:45 +01:00
x.args = x.args.into_iter().map(|a| optimize_expr(a, state)).collect();
2020-10-31 16:26:21 +01:00
Expr::FnCall(x, pos)
}
2020-03-18 03:36:50 +01:00
// Eagerly call functions
2020-10-31 16:26:21 +01:00
Expr::FnCall(mut 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
=> {
2020-10-31 16:26:21 +01:00
let FnCallInfo { name, args, def_value, .. } = x.as_mut();
2020-05-09 18:19:13 +02: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-10-20 04:54:32 +02:00
let has_script_fn = state.lib.iter().any(|&m| m.get_script_fn(name, 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 {
let mut arg_values: StaticVec<_> = 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
let arg_for_type_of = if name == KEYWORD_TYPE_OF && arg_values.len() == 1 {
state.engine.map_type_name(arg_values[0].type_name())
} else {
""
};
if let Some(expr) = call_fn_with_constant_arguments(&state, name, 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
def_value.map(|v| v.into())
}
})
2020-10-31 16:26:21 +01:00
.and_then(|result| map_dynamic_to_expr(result, pos))
{
2020-06-01 09:25:22 +02:00
state.set_dirty();
return expr;
}
}
2020-10-31 07:13:45 +01:00
x.args = x.args.into_iter().map(|a| optimize_expr(a, state)).collect();
2020-10-31 16:26:21 +01:00
Expr::FnCall(x, pos)
}
2020-03-19 12:53:42 +01:00
2020-03-18 03:36:50 +01:00
// id(args ..) -> optimize function call arguments
2020-10-31 16:26:21 +01:00
Expr::FnCall(mut x, pos) => {
2020-10-31 07:13:45 +01:00
x.args = x.args.into_iter().map(|a| optimize_expr(a, state)).collect();
2020-10-31 16:26:21 +01:00
Expr::FnCall(x, pos)
}
2020-03-19 12:53:42 +01:00
2020-03-18 03:36:50 +01:00
// constant-name
2020-11-02 16:54:19 +01:00
Expr::Variable(x) if x.1.is_none() && state.contains_constant(&x.3.name) => {
2020-03-13 11:12:41 +01:00
state.set_dirty();
// Replace constant with value
2020-11-02 16:54:19 +01:00
let mut expr = state.find_constant(&x.3.name).unwrap().clone();
expr.set_position(x.3.pos);
expr
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
2020-10-31 16:26:21 +01:00
Expr::Custom(x, pos) => Expr::Custom(Box::new(CustomExpr {
2020-10-28 12:11:17 +01:00
keywords: x.keywords.into_iter().map(|expr| optimize_expr(expr, state)).collect(),
..*x
2020-10-31 16:26:21 +01:00
}), pos),
2020-07-09 13:54:28 +02: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
}
}
fn optimize(
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 {
return statements;
}
// Set up the state
let mut state = State::new(engine, lib, level);
2020-11-01 15:46:46 +01:00
// Add constants from the scope that can be made into a literal into the state
scope
2020-11-01 15:46:46 +01:00
.iter()
.filter(|(_, typ, _)| *typ)
.for_each(|(name, _, value)| {
2020-11-02 05:50:27 +01:00
if let Some(val) = map_dynamic_to_expr(value, NO_POS) {
2020-11-01 15:46:46 +01:00
state.push_constant(name, val);
}
});
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)| {
2020-10-09 05:15:25 +02:00
match stmt {
2020-10-27 11:18:19 +01:00
Stmt::Const(var_def, Some(expr), pos) => {
2020-04-11 12:09:03 +02:00
// Load constants
2020-10-27 11:18:19 +01:00
let expr = optimize_expr(expr, &mut state);
if expr.is_literal() {
2020-10-28 12:11:17 +01:00
state.push_constant(&var_def.name, expr.clone());
2020-10-27 11:18:19 +01:00
}
// Keep it in the global scope
if expr.is_unit() {
state.set_dirty();
Stmt::Const(var_def, None, pos)
2020-10-09 05:15:25 +02:00
} else {
2020-10-27 11:18:19 +01:00
Stmt::Const(var_def, Some(expr), pos)
2020-10-09 05:15:25 +02:00
}
2020-10-27 11:18:19 +01:00
}
Stmt::Const(ref var_def, None, _) => {
2020-10-28 12:11:17 +01:00
state.push_constant(&var_def.name, Expr::Unit(var_def.pos));
2020-10-09 05:15:25 +02:00
// Keep it in the global scope
2020-10-27 11:18:19 +01:00
stmt
2020-04-11 12:09:03 +02:00
}
_ => {
// 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 {
2020-10-27 11:18:19 +01:00
Stmt::Let(_, _, _) => true,
2020-07-26 09:53:22 +02:00
#[cfg(not(feature = "no_module"))]
2020-10-27 11:18:19 +01:00
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-10-27 04:30:38 +01:00
if !result.is_empty() || !stmt.is_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>,
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()
.map(|fn_def| {
ScriptFnDef {
name: fn_def.name.clone(),
access: fn_def.access,
body: Default::default(),
params: fn_def.params.clone(),
2020-08-03 06:10:20 +02:00
#[cfg(not(feature = "no_closure"))]
2020-07-30 07:28:06 +02:00
externals: fn_def.externals.clone(),
pos: fn_def.pos,
lib: None,
}
.into()
})
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-10-20 04:54:32 +02:00
let mut body =
optimize(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-10-27 11:18:19 +01:00
Stmt::ReturnWithVal((ReturnType::Return, _), Some(expr), _) => {
Stmt::Expr(expr)
}
// { return; } -> ()
2020-10-27 11:18:19 +01:00
Stmt::ReturnWithVal((ReturnType::Return, pos), None, _) => {
Stmt::Expr(Expr::Unit(pos))
}
// All others
stmt => stmt,
};
fn_def.into()
})
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| {
module.set_script_fn(fn_def.into());
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-05-05 09:00:10 +02:00
AST::new(
match level {
OptimizationLevel::None => statements,
OptimizationLevel::Simple | OptimizationLevel::Full => {
2020-10-20 04:54:32 +02:00
optimize(statements, engine, &scope, &[&lib], level)
}
},
2020-05-05 09:00:10 +02:00
lib,
)
}