rhai/src/optimizer.rs

1205 lines
46 KiB
Rust
Raw Normal View History

2020-11-25 02:36:06 +01:00
//! Module implementing the [`AST`] optimizer.
2021-11-27 16:20:05 +01:00
#![cfg(not(feature = "no_optimize"))]
2021-11-28 03:49:48 +01:00
use crate::ast::{Expr, OpAssignment, ScriptFnDef, Stmt, AST_OPTION_FLAGS::*};
use crate::engine::{
EvalState, Imports, KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_PRINT, KEYWORD_TYPE_OF,
};
2021-11-13 15:36:23 +01:00
use crate::func::builtin::get_builtin_binary_op_fn;
use crate::func::hashing::get_hasher;
use crate::tokenizer::Token;
use crate::types::dynamic::AccessMode;
2021-03-08 11:40:23 +01:00
use crate::{
2021-04-20 17:40:52 +02:00
calc_fn_hash, calc_fn_params_hash, combine_hashes, Dynamic, Engine, FnPtr, ImmutableString,
2021-11-27 16:20:05 +01:00
Module, Position, Scope, Shared, StaticVec, AST,
2021-03-08 11:40:23 +01:00
};
2021-04-17 09:15:54 +02:00
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
any::TypeId,
hash::{Hash, Hasher},
mem,
ops::DerefMut,
2021-04-17 09:15:54 +02:00
};
2021-07-14 16:33:47 +02:00
#[cfg(not(feature = "no_closure"))]
use crate::engine::KEYWORD_IS_SHARED;
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,
}
2021-05-18 06:24:11 +02:00
impl Default for OptimizationLevel {
2020-10-08 16:25:50 +02:00
#[inline(always)]
2021-05-18 06:24:11 +02:00
fn default() -> Self {
if cfg!(feature = "no_optimize") {
Self::None
} else {
Self::Simple
}
2020-04-10 06:16:39 +02:00
}
}
2020-03-18 03:36:50 +01:00
/// Mutable state throughout an optimization pass.
#[derive(Debug, Clone)]
2021-07-04 10:40:15 +02:00
struct OptimizerState<'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.
2021-09-12 08:34:00 +02:00
variables: StaticVec<(String, AccessMode, Option<Dynamic>)>,
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-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
}
2021-07-04 10:40:15 +02:00
impl<'a> OptimizerState<'a> {
2020-04-01 03:51:33 +02:00
/// Create a new State.
2020-10-08 16:25:50 +02:00
#[inline(always)]
2021-11-25 10:09:00 +01:00
pub const fn new(
2021-03-11 11:29:22 +01:00
engine: &'a Engine,
lib: &'a [&'a Module],
optimization_level: OptimizationLevel,
) -> Self {
2020-04-01 03:51:33 +02:00
Self {
changed: false,
2021-11-25 10:09:00 +01:00
variables: StaticVec::new_const(),
2021-01-12 16:52:50 +01:00
propagate_constants: true,
2020-04-01 03:51:33 +02:00
engine,
lib,
2021-03-11 11:29:22 +01:00
optimization_level,
2020-04-01 03:51:33 +02:00
}
}
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;
}
2021-03-11 11:29:22 +01:00
/// Set the [`AST`] state to be not dirty (i.e. unchanged).
#[inline(always)]
pub fn clear_dirty(&mut self) {
self.changed = false;
}
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)]
2021-06-28 12:06:05 +02:00
pub const fn is_dirty(&self) -> bool {
2020-03-13 11:12:41 +01:00
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)]
2021-11-27 16:04:45 +01:00
pub fn push_var(
&mut self,
name: impl Into<String>,
access: AccessMode,
value: Option<Dynamic>,
) {
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]
2021-11-27 16:04:45 +01:00
pub fn find_constant(&self, name: impl AsRef<str>) -> Option<&Dynamic> {
2021-01-12 16:52:50 +01:00
if !self.propagate_constants {
return None;
}
2021-11-27 16:04:45 +01:00
let name = name.as_ref();
for (n, access, value) in self.variables.iter().rev() {
2020-03-13 11:12:41 +01:00
if n == name {
return match access {
2021-03-05 06:34:58 +01:00
AccessMode::ReadWrite => None,
2021-05-16 15:21:13 +02:00
AccessMode::ReadOnly => value.as_ref(),
};
2020-03-13 11:12:41 +01:00
}
}
None
2020-03-13 11:12:41 +01:00
}
/// Call a registered function
#[inline]
pub fn call_fn_with_constant_arguments(
&self,
2021-11-27 16:04:45 +01:00
fn_name: impl AsRef<str>,
arg_values: &mut [Dynamic],
) -> Option<Dynamic> {
self.engine
.call_native_fn(
&mut Imports::new(),
&mut EvalState::new(),
self.lib,
2021-11-27 16:04:45 +01:00
&fn_name,
calc_fn_hash(&fn_name, arg_values.len()),
&mut arg_values.iter_mut().collect::<StaticVec<_>>(),
false,
false,
Position::NONE,
)
.ok()
.map(|(v, _)| v)
}
// Has a system function a Rust-native override?
pub fn has_native_fn_override(&self, hash_script: u64, arg_types: &[TypeId]) -> bool {
let hash_params = calc_fn_params_hash(arg_types.iter().cloned());
let hash = combine_hashes(hash_script, hash_params);
2021-03-08 11:40:23 +01:00
// First check the global namespace and packages, but skip modules that are standard because
// they should never conflict with system functions.
self.engine.global_modules.iter().filter(|m| !m.standard).any(|m| m.contains_fn(hash))
2021-03-08 11:40:23 +01:00
// Then check sub-modules
|| self.engine.global_sub_modules.values().any(|m| m.contains_qualified_fn(hash))
}
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(
2021-09-12 08:34:00 +02:00
mut statements: StaticVec<Stmt>,
2021-07-04 10:40:15 +02:00
state: &mut OptimizerState,
2020-11-12 05:37:42 +01:00
preserve_result: bool,
2021-03-13 16:43:05 +01:00
is_internal: bool,
reduce_return: bool,
2021-09-12 08:34:00 +02:00
) -> StaticVec<Stmt> {
2021-03-10 05:27:10 +01:00
if statements.is_empty() {
return statements;
}
2021-03-11 11:29:22 +01:00
let mut is_dirty = state.is_dirty();
2021-01-12 16:52:50 +01:00
2021-03-13 16:43:05 +01:00
let is_pure = if is_internal {
Stmt::is_internally_pure
} else {
Stmt::is_pure
};
2021-03-11 11:29:22 +01:00
loop {
state.clear_dirty();
2020-11-12 05:37:42 +01:00
2021-03-11 11:29:22 +01:00
let orig_constants_len = state.variables.len(); // Original number of constants in the state, for restore later
let orig_propagate_constants = state.propagate_constants;
2020-11-12 05:37:42 +01:00
2021-03-11 11:29:22 +01:00
// Remove everything following control flow breaking statements
let mut dead_code = false;
2020-11-12 05:37:42 +01:00
2021-03-11 11:29:22 +01:00
statements.retain(|stmt| {
if dead_code {
state.set_dirty();
false
} else if stmt.is_control_flow_break() {
dead_code = true;
true
} else {
true
}
});
2020-11-12 05:37:42 +01:00
2021-03-11 11:29:22 +01:00
// Optimize each statement in the block
statements.iter_mut().for_each(|stmt| {
match stmt {
Stmt::Var(value_expr, x, options, _) => {
if options.contains(AST_OPTION_CONSTANT) {
// Add constant literals into the state
optimize_expr(value_expr, state, false);
if value_expr.is_constant() {
state.push_var(
2021-11-27 16:04:45 +01:00
x.name.as_str(),
AccessMode::ReadOnly,
value_expr.get_literal_value(),
);
}
} else {
// Add variables into the state
optimize_expr(value_expr, state, false);
2021-11-27 16:04:45 +01:00
state.push_var(x.name.as_str(), AccessMode::ReadWrite, None);
2021-03-11 11:29:22 +01:00
}
}
// Optimize the statement
_ => optimize_stmt(stmt, state, preserve_result),
2020-11-12 05:37:42 +01:00
}
2021-03-11 11:29:22 +01:00
});
2020-11-12 05:37:42 +01:00
2021-03-13 16:43:05 +01:00
// Remove all pure statements except the last one
let mut index = 0;
let mut first_non_constant = statements
.iter()
.rev()
.enumerate()
.find_map(|(i, stmt)| match stmt {
stmt if !is_pure(stmt) => Some(i),
Stmt::Var(e, _, _, _) | Stmt::Expr(e) if !e.is_constant() => Some(i),
2021-03-13 16:43:05 +01:00
2021-03-14 03:47:21 +01:00
#[cfg(not(feature = "no_module"))]
2021-04-24 07:42:45 +02:00
Stmt::Import(e, _, _) if !e.is_constant() => Some(i),
2021-03-14 03:47:21 +01:00
2021-04-24 07:42:45 +02:00
_ => None,
2021-03-13 16:43:05 +01:00
})
2021-04-24 07:42:45 +02:00
.map_or(0, |n| statements.len() - n - 1);
2021-03-13 16:43:05 +01:00
while index < statements.len() {
if preserve_result && index >= statements.len() - 1 {
break;
} else {
2021-06-14 06:02:22 +02:00
match statements[index] {
ref stmt if is_pure(stmt) && index >= first_non_constant => {
2021-03-13 16:43:05 +01:00
state.set_dirty();
statements.remove(index);
}
2021-06-14 06:02:22 +02:00
ref stmt if stmt.is_pure() => {
2021-03-13 16:43:05 +01:00
state.set_dirty();
if index < first_non_constant {
first_non_constant -= 1;
}
statements.remove(index);
}
_ => index += 1,
}
}
}
2021-03-11 11:29:22 +01:00
// Remove all pure statements that do not return values at the end of a block.
// We cannot remove anything for non-pure statements due to potential side-effects.
if preserve_result {
loop {
2021-06-14 06:02:22 +02:00
match statements[..] {
2021-03-13 16:43:05 +01:00
// { return; } -> {}
[Stmt::Return(options, None, _)]
if reduce_return && !options.contains(AST_OPTION_BREAK_OUT) =>
{
2021-03-13 16:43:05 +01:00
state.set_dirty();
statements.clear();
}
2021-06-14 06:02:22 +02:00
[ref stmt] if !stmt.returns_value() && is_pure(stmt) => {
2021-03-11 11:29:22 +01:00
state.set_dirty();
statements.clear();
}
2021-03-13 16:43:05 +01:00
// { ...; return; } -> { ... }
[.., ref last_stmt, Stmt::Return(options, None, _)]
if reduce_return
&& !options.contains(AST_OPTION_BREAK_OUT)
&& !last_stmt.returns_value() =>
2021-03-13 16:43:05 +01:00
{
state.set_dirty();
2021-11-13 05:23:35 +01:00
statements.pop().expect(">= 2 elements");
2021-03-13 16:43:05 +01:00
}
// { ...; return val; } -> { ...; val }
[.., Stmt::Return(options, ref mut expr, pos)]
if reduce_return && !options.contains(AST_OPTION_BREAK_OUT) =>
2021-03-13 16:43:05 +01:00
{
state.set_dirty();
2021-11-13 05:23:35 +01:00
*statements.last_mut().expect(">= 2 elements") = if let Some(expr) = expr {
Stmt::Expr(mem::take(expr))
} else {
Stmt::Noop(pos)
};
2021-03-13 16:43:05 +01:00
}
2021-07-01 06:27:29 +02:00
// { ...; stmt; noop } -> done
2021-06-14 06:02:22 +02:00
[.., ref second_last_stmt, Stmt::Noop(_)]
2021-07-01 06:27:29 +02:00
if second_last_stmt.returns_value() =>
{
break
}
// { ...; stmt_that_returns; pure_non_value_stmt } -> { ...; stmt_that_returns; noop }
// { ...; stmt; pure_non_value_stmt } -> { ...; stmt }
2021-06-14 06:02:22 +02:00
[.., ref second_last_stmt, ref last_stmt]
2021-03-13 16:43:05 +01:00
if !last_stmt.returns_value() && is_pure(last_stmt) =>
2021-03-11 11:29:22 +01:00
{
state.set_dirty();
if second_last_stmt.returns_value() {
2021-11-13 05:23:35 +01:00
*statements.last_mut().expect(">= 2 elements") =
2021-08-26 17:58:41 +02:00
Stmt::Noop(last_stmt.position());
2021-03-11 11:29:22 +01:00
} else {
2021-11-13 05:23:35 +01:00
statements.pop().expect(">= 2 elements");
2021-03-11 11:29:22 +01:00
}
}
_ => break,
}
}
} else {
loop {
2021-06-14 06:02:22 +02:00
match statements[..] {
[ref stmt] if is_pure(stmt) => {
2021-03-11 11:29:22 +01:00
state.set_dirty();
statements.clear();
}
2021-03-13 16:43:05 +01:00
// { ...; return; } -> { ... }
[.., Stmt::Return(options, None, _)]
if reduce_return && !options.contains(AST_OPTION_BREAK_OUT) =>
2021-03-13 16:43:05 +01:00
{
state.set_dirty();
2021-11-13 05:23:35 +01:00
statements.pop().expect(">= 2 elements");
2021-03-13 16:43:05 +01:00
}
// { ...; return pure_val; } -> { ... }
[.., Stmt::Return(options, Some(ref expr), _)]
if reduce_return
&& !options.contains(AST_OPTION_BREAK_OUT)
&& expr.is_pure() =>
2021-03-13 16:43:05 +01:00
{
state.set_dirty();
2021-11-13 05:23:35 +01:00
statements.pop().expect(">= 2 elements");
2021-03-13 16:43:05 +01:00
}
2021-06-14 06:02:22 +02:00
[.., ref last_stmt] if is_pure(last_stmt) => {
2021-03-11 11:29:22 +01:00
state.set_dirty();
2021-11-13 05:23:35 +01:00
statements.pop().expect("not empty");
2021-03-11 11:29:22 +01:00
}
_ => break,
}
}
2020-11-12 05:37:42 +01:00
}
2021-03-11 11:29:22 +01:00
// Pop the stack and remove all the local constants
state.restore_var(orig_constants_len);
state.propagate_constants = orig_propagate_constants;
2020-11-12 05:37:42 +01:00
2021-03-11 11:29:22 +01:00
if !state.is_dirty() {
break;
2020-11-12 05:37:42 +01:00
}
2021-03-11 11:29:22 +01:00
is_dirty = true;
}
2020-11-12 05:37:42 +01:00
2021-03-11 11:29:22 +01:00
if is_dirty {
2020-11-12 05:37:42 +01:00
state.set_dirty();
}
2021-03-13 16:43:05 +01:00
statements.shrink_to_fit();
2021-03-10 05:27:10 +01:00
statements
2020-11-12 05:37:42 +01:00
}
2020-12-26 16:21:16 +01:00
/// Optimize a [statement][Stmt].
2021-07-04 10:40:15 +02:00
fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: bool) {
2020-03-09 14:57:07 +01:00
match stmt {
2021-04-23 17:37:10 +02:00
// var = var op expr => var op= expr
Stmt::Assignment(x, _)
if x.1.is_none()
&& x.0.is_variable_access(true)
&& matches!(&x.2, Expr::FnCall(x2, _)
2021-04-24 05:55:40 +02:00
if Token::lookup_from_syntax(&x2.name).map(|t| t.has_op_assignment()).unwrap_or(false)
&& x2.args.len() == 2
2021-04-23 17:37:10 +02:00
&& x2.args[0].get_variable_name(true) == x.0.get_variable_name(true)
) =>
{
2021-06-14 06:02:22 +02:00
match x.2 {
Expr::FnCall(ref mut x2, _) => {
2021-04-23 17:37:10 +02:00
state.set_dirty();
2021-11-13 05:23:35 +01:00
let op = Token::lookup_from_syntax(&x2.name).expect("operator");
let op_assignment = op.make_op_assignment().expect("operator");
2021-04-24 05:55:40 +02:00
x.1 = Some(OpAssignment::new(op_assignment));
let value = mem::take(&mut x2.args[1]);
if let Expr::Stack(slot, pos) = value {
2021-11-13 05:23:35 +01:00
let value = mem::take(x2.constants.get_mut(slot).expect("valid slot"));
x.2 = Expr::from_dynamic(value, pos);
2021-04-23 17:37:10 +02:00
} else {
x.2 = value;
}
2021-04-23 17:37:10 +02:00
}
_ => unreachable!(),
}
}
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 {
2021-06-02 08:29:18 +02:00
Expr::Variable(_, _, _) => optimize_expr(&mut x.2, state, false),
2020-11-12 05:37:42 +01:00
_ => {
2021-06-02 08:29:18 +02:00
optimize_expr(&mut x.0, state, false);
optimize_expr(&mut x.2, state, false);
2020-11-03 06:08:19 +01:00
}
},
2020-11-14 16:43:36 +01:00
2021-03-10 05:27:10 +01:00
// if expr {}
Stmt::If(condition, x, _) if x.0.is_empty() && x.1.is_empty() => {
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);
2021-06-02 08:29:18 +02:00
optimize_expr(&mut expr, state, false);
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-06-29 12:25:20 +02:00
Stmt::Block([Stmt::Expr(expr), Stmt::Noop(pos)].into(), 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
}
2021-03-10 05:27:10 +01:00
// if false { if_block } -> Noop
Stmt::If(Expr::BoolConstant(false, pos), x, _) if x.1.is_empty() => {
state.set_dirty();
*stmt = Stmt::Noop(*pos);
2020-11-12 05:37:42 +01:00
}
2020-10-27 11:18:19 +01:00
// if false { if_block } else { else_block } -> else_block
2021-03-10 05:27:10 +01:00
Stmt::If(Expr::BoolConstant(false, _), x, _) => {
state.set_dirty();
2021-09-12 08:34:00 +02:00
let else_block = mem::take(&mut *x.1);
2021-03-13 16:43:05 +01:00
*stmt = match optimize_stmt_block(else_block, state, preserve_result, true, false) {
2021-04-16 07:15:11 +02:00
statements if statements.is_empty() => Stmt::Noop(x.1.position()),
2021-05-05 12:38:52 +02:00
statements => Stmt::Block(statements.into_boxed_slice(), x.1.position()),
2021-03-10 05:27:10 +01:00
}
2020-10-27 11:18:19 +01:00
}
// if true { if_block } else { else_block } -> if_block
Stmt::If(Expr::BoolConstant(true, _), x, _) => {
2021-03-10 05:27:10 +01:00
state.set_dirty();
2021-09-12 08:34:00 +02:00
let if_block = mem::take(&mut *x.0);
2021-03-13 16:43:05 +01:00
*stmt = match optimize_stmt_block(if_block, state, preserve_result, true, false) {
2021-04-16 07:15:11 +02:00
statements if statements.is_empty() => Stmt::Noop(x.0.position()),
2021-05-05 12:38:52 +02:00
statements => Stmt::Block(statements.into_boxed_slice(), x.0.position()),
2021-03-10 05:27:10 +01:00
}
2020-11-12 05:37:42 +01:00
}
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, _) => {
2021-06-02 08:29:18 +02:00
optimize_expr(condition, state, false);
2021-09-12 08:34:00 +02:00
let if_block = mem::take(x.0.deref_mut());
*x.0 = optimize_stmt_block(if_block, state, preserve_result, true, false);
let else_block = mem::take(x.1.deref_mut());
*x.1 = optimize_stmt_block(else_block, state, preserve_result, true, false);
2020-11-12 05:37:42 +01:00
}
2020-10-27 11:18:19 +01:00
2020-11-14 16:43:36 +01:00
// switch const { ... }
2021-04-16 06:04:33 +02:00
Stmt::Switch(match_expr, x, pos) if match_expr.is_constant() => {
2021-11-01 02:42:22 +01:00
let value = match_expr.get_literal_value().expect("constant");
2020-11-14 16:43:36 +01:00
let hasher = &mut get_hasher();
value.hash(hasher);
let hash = hasher.finish();
state.set_dirty();
let table = &mut x.0;
2021-04-16 06:04:33 +02:00
if let Some(block) = table.get_mut(&hash) {
if let Some(mut condition) = mem::take(&mut block.0) {
// switch const { case if condition => stmt, _ => def } => if condition { stmt } else { def }
2021-06-02 08:29:18 +02:00
optimize_expr(&mut condition, state, false);
2021-04-16 06:04:33 +02:00
2021-09-12 08:34:00 +02:00
let def_block = mem::take(&mut *x.1);
2021-04-16 06:04:33 +02:00
let def_stmt = optimize_stmt_block(def_block, state, true, true, false);
2021-04-16 07:15:11 +02:00
let def_pos = if x.1.position().is_none() {
*pos
} else {
x.1.position()
};
2021-04-16 06:04:33 +02:00
*stmt = Stmt::If(
condition,
Box::new((
mem::take(&mut block.1),
2021-05-05 12:38:52 +02:00
Stmt::Block(def_stmt.into_boxed_slice(), def_pos).into(),
2021-04-16 06:04:33 +02:00
)),
match_expr.position(),
);
} else {
// Promote the matched case
2021-04-16 07:15:11 +02:00
let new_pos = block.1.position();
let statements = mem::take(&mut *block.1);
2021-09-12 08:34:00 +02:00
let statements = optimize_stmt_block(statements, state, true, true, false);
2021-05-05 12:38:52 +02:00
*stmt = Stmt::Block(statements.into_boxed_slice(), new_pos);
2021-04-16 06:04:33 +02:00
}
2020-11-14 16:43:36 +01:00
} else {
2021-04-16 06:04:33 +02:00
// Promote the default case
2021-09-12 08:34:00 +02:00
let def_block = mem::take(&mut *x.1);
2021-04-16 06:04:33 +02:00
let def_stmt = optimize_stmt_block(def_block, state, true, true, false);
2021-04-16 07:15:11 +02:00
let def_pos = if x.1.position().is_none() {
*pos
} else {
x.1.position()
};
2021-05-05 12:38:52 +02:00
*stmt = Stmt::Block(def_stmt.into_boxed_slice(), def_pos);
2021-04-16 06:04:33 +02:00
}
2020-11-14 16:43:36 +01:00
}
// switch
2021-04-16 06:04:33 +02:00
Stmt::Switch(match_expr, x, _) => {
2021-06-02 08:29:18 +02:00
optimize_expr(match_expr, state, false);
2021-03-10 15:12:48 +01:00
x.0.values_mut().for_each(|block| {
2021-05-25 04:54:48 +02:00
let condition = mem::take(&mut block.0).map_or_else(
|| Expr::Unit(Position::NONE),
|mut condition| {
2021-06-02 08:29:18 +02:00
optimize_expr(&mut condition, state, false);
2021-05-25 04:54:48 +02:00
condition
},
);
2021-04-16 06:04:33 +02:00
match condition {
Expr::Unit(_) | Expr::BoolConstant(true, _) => (),
_ => {
block.0 = Some(condition);
*block.1 = optimize_stmt_block(
2021-09-12 08:34:00 +02:00
mem::take(block.1.deref_mut()),
2021-04-16 07:15:11 +02:00
state,
preserve_result,
true,
false,
2021-09-12 08:34:00 +02:00
);
2021-04-16 06:04:33 +02:00
}
}
2021-03-10 15:12:48 +01:00
});
2021-04-16 06:04:33 +02:00
// Remove false cases
while let Some((&key, _)) = x.0.iter().find(|(_, block)| match block.0 {
Some(Expr::BoolConstant(false, _)) => true,
_ => false,
}) {
state.set_dirty();
x.0.remove(&key);
}
2021-09-12 08:34:00 +02:00
let def_block = mem::take(x.1.deref_mut());
*x.1 = optimize_stmt_block(def_block, state, preserve_result, true, false);
2020-11-14 16:43:36 +01:00
}
2020-10-27 11:18:19 +01:00
// while false { block } -> Noop
2021-03-09 16:30:48 +01:00
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 }
2021-03-13 16:43:05 +01:00
Stmt::While(condition, body, _) => {
2021-06-02 08:29:18 +02:00
optimize_expr(condition, state, false);
2021-08-04 11:40:26 +02:00
if let Expr::BoolConstant(true, pos) = condition {
*condition = Expr::Unit(*pos);
}
2021-09-12 08:34:00 +02:00
let block = mem::take(body.as_mut().deref_mut());
*body.as_mut().deref_mut() = optimize_stmt_block(block, state, false, true, false);
2021-03-10 05:27:10 +01:00
2021-03-13 16:43:05 +01:00
if body.len() == 1 {
2021-04-16 07:15:11 +02:00
match body[0] {
2021-03-10 05:27:10 +01:00
// while expr { break; } -> { expr; }
Stmt::BreakLoop(options, pos) if options.contains(AST_OPTION_BREAK_OUT) => {
2021-03-10 05:27:10 +01:00
// Only a single break statement - turn into running the guard expression once
state.set_dirty();
if !condition.is_unit() {
let mut statements = vec![Stmt::Expr(mem::take(condition))];
if preserve_result {
statements.push(Stmt::Noop(pos))
}
2021-05-05 12:38:52 +02:00
*stmt = Stmt::Block(statements.into_boxed_slice(), pos);
2021-03-10 05:27:10 +01:00
} else {
*stmt = Stmt::Noop(pos);
};
}
_ => (),
2020-03-17 10:33:37 +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(body, Expr::BoolConstant(x, _), options, _)
if *x == options.contains(AST_OPTION_NEGATED) =>
{
2020-11-20 15:23:37 +01:00
state.set_dirty();
2021-04-16 07:15:11 +02:00
let block_pos = body.position();
2021-09-12 08:34:00 +02:00
let block = mem::take(body.as_mut().deref_mut());
2021-03-10 05:27:10 +01:00
*stmt = Stmt::Block(
2021-05-05 12:38:52 +02:00
optimize_stmt_block(block, state, false, true, false).into_boxed_slice(),
2021-04-16 07:15:11 +02:00
block_pos,
2021-03-10 05:27:10 +01:00
);
2020-11-20 15:23:37 +01:00
}
// do { block } while|until expr
2021-03-13 16:43:05 +01:00
Stmt::Do(body, condition, _, _) => {
2021-06-02 08:29:18 +02:00
optimize_expr(condition, state, false);
2021-09-12 08:34:00 +02:00
let block = mem::take(body.as_mut().deref_mut());
*body.as_mut().deref_mut() = optimize_stmt_block(block, state, false, true, false);
2020-11-12 05:37:42 +01:00
}
2020-03-18 03:36:50 +01:00
// for id in expr { block }
2021-03-09 16:48:40 +01:00
Stmt::For(iterable, x, _) => {
2021-06-02 08:29:18 +02:00
optimize_expr(iterable, state, false);
2021-09-12 08:34:00 +02:00
let body = mem::take(x.2.deref_mut());
*x.2 = optimize_stmt_block(body, state, false, true, false);
2020-10-27 12:23:43 +01:00
}
2020-03-18 03:36:50 +01:00
// let id = expr;
Stmt::Var(expr, _, options, _) if !options.contains(AST_OPTION_CONSTANT) => {
optimize_expr(expr, state, false)
}
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"))]
2021-06-02 08:29:18 +02:00
Stmt::Import(expr, _, _) => optimize_expr(expr, state, false),
2020-03-18 03:36:50 +01:00
// { block }
2020-10-27 11:18:19 +01:00
Stmt::Block(statements, pos) => {
2021-09-12 08:34:00 +02:00
let statements = mem::take(statements).into_vec().into();
2021-05-05 12:38:52 +02:00
let mut block = optimize_stmt_block(statements, state, preserve_result, true, false);
2021-04-05 08:57:07 +02:00
match block.as_mut_slice() {
[] => {
2021-03-10 05:27:10 +01:00
state.set_dirty();
2021-04-05 08:57:07 +02:00
*stmt = Stmt::Noop(*pos);
2021-03-10 05:27:10 +01:00
}
// Only one statement - promote
2021-04-05 08:57:07 +02:00
[s] => {
2021-03-10 05:27:10 +01:00
state.set_dirty();
2021-04-05 08:57:07 +02:00
*stmt = mem::take(s);
2021-03-10 05:27:10 +01:00
}
2021-05-05 12:38:52 +02:00
_ => *stmt = Stmt::Block(block.into_boxed_slice(), *pos),
2021-04-05 08:57:07 +02:00
}
2020-03-09 14:57:07 +01:00
}
2021-03-13 16:43:05 +01:00
// try { pure try_block } catch ( var ) { catch_block } -> try_block
2021-06-16 10:15:29 +02:00
Stmt::TryCatch(x, _) if x.0.iter().all(Stmt::is_pure) => {
2020-10-20 17:16:03 +02:00
// If try block is pure, there will never be any exceptions
state.set_dirty();
2021-04-16 07:15:11 +02:00
let try_pos = x.0.position();
2021-09-12 08:34:00 +02:00
let try_block = mem::take(&mut *x.0);
2021-03-10 05:27:10 +01:00
*stmt = Stmt::Block(
2021-05-05 12:38:52 +02:00
optimize_stmt_block(try_block, state, false, true, false).into_boxed_slice(),
2021-04-16 07:15:11 +02:00
try_pos,
2021-03-10 05:27:10 +01:00
);
2020-10-20 17:16:03 +02:00
}
2021-03-13 16:43:05 +01:00
// try { try_block } catch ( var ) { catch_block }
2021-06-16 10:15:29 +02:00
Stmt::TryCatch(x, _) => {
2021-09-12 08:34:00 +02:00
let try_block = mem::take(x.0.deref_mut());
*x.0 = optimize_stmt_block(try_block, state, false, true, false);
let catch_block = mem::take(x.2.deref_mut());
*x.2 = optimize_stmt_block(catch_block, state, false, true, false);
2020-10-27 11:18:19 +01:00
}
2021-04-21 12:16:24 +02:00
// func(...)
Stmt::Expr(expr @ Expr::FnCall(_, _)) => {
2021-06-02 08:29:18 +02:00
optimize_expr(expr, state, false);
2021-04-21 12:16:24 +02:00
match expr {
Expr::FnCall(x, pos) => {
state.set_dirty();
*stmt = Stmt::FnCall(mem::take(x), *pos);
}
_ => (),
}
}
2020-11-04 06:11:37 +01:00
// {}
2021-04-16 07:15:11 +02:00
Stmt::Expr(Expr::Stmt(x)) if x.is_empty() => {
2020-10-28 07:10:48 +01:00
state.set_dirty();
2021-04-16 07:15:11 +02:00
*stmt = Stmt::Noop(x.position());
2020-11-04 04:49:02 +01:00
}
2020-11-04 06:11:37 +01:00
// {...};
2021-03-10 15:12:48 +01:00
Stmt::Expr(Expr::Stmt(x)) => {
2020-11-04 04:49:02 +01:00
state.set_dirty();
2021-04-16 07:15:11 +02:00
*stmt = mem::take(x.as_mut()).into();
2020-10-28 07:10:48 +01:00
}
// expr;
2021-06-02 08:29:18 +02:00
Stmt::Expr(expr) => optimize_expr(expr, state, false),
2020-03-18 03:36:50 +01:00
// return expr;
2021-06-02 08:29:18 +02:00
Stmt::Return(_, Some(ref mut expr), _) => optimize_expr(expr, state, false),
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].
2021-08-13 07:42:39 +02:00
fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, chaining: bool) {
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
2021-08-13 07:42:39 +02:00
let _chaining = chaining;
2020-03-09 14:57:07 +01:00
match expr {
2020-11-04 04:49:02 +01:00
// {}
2021-04-16 07:15:11 +02:00
Expr::Stmt(x) if x.is_empty() => { state.set_dirty(); *expr = Expr::Unit(x.position()) }
2021-04-05 08:57:07 +02:00
// { stmt; ... } - do not count promotion as dirty because it gets turned back into an array
Expr::Stmt(x) => {
*x.as_mut().deref_mut() =
2021-09-12 08:34:00 +02:00
optimize_stmt_block(mem::take(x.as_mut().deref_mut()), state, true, true, false);
2021-04-05 08:57:07 +02:00
// { Stmt(Expr) } - promote
2021-04-16 07:15:11 +02:00
match x.as_mut().as_mut() {
2021-04-05 08:57:07 +02:00
[ Stmt::Expr(e) ] => { state.set_dirty(); *expr = mem::take(e); }
_ => ()
2021-04-04 07:13:07 +02:00
}
}
2020-03-18 03:36:50 +01:00
// lhs.rhs
#[cfg(not(feature = "no_object"))]
2021-07-24 06:27:33 +02:00
Expr::Dot(x,_, _) if !_chaining => match (&mut x.lhs, &mut x.rhs) {
// map.string
2021-03-23 11:25:40 +01:00
(Expr::Map(m, pos), Expr::Property(p)) if m.0.iter().all(|(_, x)| x.is_pure()) => {
2021-05-18 14:12:30 +02:00
let prop = p.2.0.as_str();
// Map literal where everything is pure - promote the indexed item.
// All other items can be thrown away.
state.set_dirty();
2021-07-24 08:11:16 +02:00
*expr = mem::take(&mut m.0).into_iter().find(|(x, _)| x.name == prop)
2020-11-12 05:37:42 +01:00
.map(|(_, mut expr)| { expr.set_position(*pos); expr })
.unwrap_or_else(|| Expr::Unit(*pos));
}
2020-11-03 06:08:19 +01:00
// var.rhs
2021-06-02 08:29:18 +02:00
(Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state, true),
// lhs.rhs
2021-06-02 08:29:18 +02:00
(lhs, rhs) => { optimize_expr(lhs, state, false); optimize_expr(rhs, state, true); }
}
2021-06-02 08:29:18 +02:00
// ....lhs.rhs
#[cfg(not(feature = "no_object"))]
2021-07-24 06:27:33 +02:00
Expr::Dot(x,_, _) => { optimize_expr(&mut x.lhs, state, false); optimize_expr(&mut x.rhs, state, _chaining); }
2020-03-11 04:03:18 +01:00
2020-03-18 03:36:50 +01:00
// lhs[rhs]
#[cfg(not(feature = "no_index"))]
2021-07-24 06:27:33 +02:00
Expr::Index(x, _, _) if !_chaining => 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();
2021-06-16 12:36:33 +02:00
let mut result = mem::take(&mut a[*i as usize]);
2020-11-12 05:37:42 +01:00
result.set_position(*pos);
*expr = result;
}
// array[-int]
(Expr::Array(a, pos), Expr::IntegerConstant(i, _))
if *i < 0 && i.checked_abs().map(|n| n as usize <= a.len()).unwrap_or(false) && a.iter().all(Expr::is_pure) =>
{
// Array literal where everything is pure - promote the indexed item.
// All other items can be thrown away.
state.set_dirty();
2021-06-16 12:36:33 +02:00
let index = a.len() - i.abs() as usize;
let mut result = mem::take(&mut a[index]);
result.set_position(*pos);
*expr = result;
}
// map[string]
2021-03-23 11:25:40 +01:00
(Expr::Map(m, pos), 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();
2021-03-29 05:36:02 +02:00
*expr = mem::take(&mut m.0).into_iter().find(|(x, _)| x.name.as_str() == s.as_str())
2020-11-12 05:37:42 +01:00
.map(|(_, mut expr)| { expr.set_position(*pos); expr })
.unwrap_or_else(|| Expr::Unit(*pos));
}
2021-06-02 08:29:18 +02:00
// int[int]
(Expr::IntegerConstant(n, pos), Expr::IntegerConstant(i, _)) if *i >= 0 && (*i as usize) < (std::mem::size_of_val(n) * 8) => {
// Bit-field literal indexing - get the bit
state.set_dirty();
*expr = Expr::BoolConstant((*n & (1 << (*i as usize))) != 0, *pos);
}
// int[-int]
(Expr::IntegerConstant(n, pos), Expr::IntegerConstant(i, _)) if *i < 0 && i.checked_abs().map(|i| i as usize <= (std::mem::size_of_val(n) * 8)).unwrap_or(false) => {
// Bit-field literal indexing - get the bit
state.set_dirty();
*expr = Expr::BoolConstant((*n & (1 << (std::mem::size_of_val(n) * 8 - i.abs() as usize))) != 0, *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();
2021-11-13 05:23:35 +01:00
*expr = Expr::CharConstant(s.chars().nth(*i as usize).expect("valid index"), *pos);
}
// string[-int]
(Expr::StringConstant(s, pos), Expr::IntegerConstant(i, _)) if *i < 0 && i.checked_abs().map(|n| n as usize <= s.chars().count()).unwrap_or(false) => {
// String literal indexing - get the character
state.set_dirty();
2021-11-13 05:23:35 +01:00
*expr = Expr::CharConstant(s.chars().rev().nth(i.abs() as usize - 1).expect("valid index"), *pos);
}
2020-11-03 06:08:19 +01:00
// var[rhs]
2021-06-02 08:29:18 +02:00
(Expr::Variable(_, _, _), rhs) => optimize_expr(rhs, state, true),
2020-03-18 03:36:50 +01:00
// lhs[rhs]
2021-06-02 08:29:18 +02:00
(lhs, rhs) => { optimize_expr(lhs, state, false); optimize_expr(rhs, state, true); }
},
2021-06-02 08:29:18 +02:00
// ...[lhs][rhs]
#[cfg(not(feature = "no_index"))]
2021-07-24 06:27:33 +02:00
Expr::Index(x, _, _) => { optimize_expr(&mut x.lhs, state, false); optimize_expr(&mut x.rhs, state, _chaining); }
2021-04-04 07:13:07 +02:00
// ``
2021-06-29 12:41:03 +02:00
Expr::InterpolatedString(x, pos) if x.is_empty() => {
2021-04-04 07:13:07 +02:00
state.set_dirty();
2021-09-26 15:30:33 +02:00
*expr = Expr::StringConstant(state.engine.const_empty_string(), *pos);
2021-04-04 07:13:07 +02:00
}
// `...`
2021-06-29 12:41:03 +02:00
Expr::InterpolatedString(x, _) if x.len() == 1 && matches!(x[0], Expr::StringConstant(_, _)) => {
2021-04-04 07:13:07 +02:00
state.set_dirty();
*expr = mem::take(&mut x[0]);
}
// `... ${ ... } ...`
2021-06-29 12:41:03 +02:00
Expr::InterpolatedString(x, _) => {
2021-09-20 16:36:10 +02:00
x.iter_mut().for_each(|expr| optimize_expr(expr, state, false));
2021-06-16 12:36:33 +02:00
let mut n = 0;
2021-04-04 07:13:07 +02:00
// Merge consecutive strings
while n < x.len()-1 {
match (mem::take(&mut x[n]), mem::take(&mut x[n+1])) {
(Expr::StringConstant(mut s1, pos), Expr::StringConstant(s2, _)) => {
s1 += s2;
x[n] = Expr::StringConstant(s1, pos);
x.remove(n+1);
state.set_dirty();
}
(expr1, Expr::Unit(_)) => {
x[n] = expr1;
x.remove(n+1);
state.set_dirty();
}
(Expr::Unit(_), expr2) => {
x[n+1] = expr2;
x.remove(n);
state.set_dirty();
}
(expr1, Expr::StringConstant(s, _)) if s.is_empty() => {
x[n] = expr1;
x.remove(n+1);
state.set_dirty();
}
(Expr::StringConstant(s, _), expr2) if s.is_empty()=> {
x[n+1] = expr2;
x.remove(n);
state.set_dirty();
}
(expr1, expr2) => {
x[n] = expr1;
x[n+1] = expr2;
n += 1;
}
}
}
2021-05-05 12:38:52 +02:00
x.shrink_to_fit();
2021-04-04 07:13:07 +02:00
}
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();
2021-11-01 02:42:22 +01:00
*expr = Expr::DynamicConstant(expr.get_literal_value().expect("constant").into(), expr.position());
2020-11-14 12:04:49 +01:00
}
2020-03-18 03:36:50 +01:00
// [ items .. ]
#[cfg(not(feature = "no_index"))]
2021-06-02 08:29:18 +02:00
Expr::Array(x, _) => x.iter_mut().for_each(|expr| optimize_expr(expr, state, false)),
2020-11-14 12:04:49 +01:00
// #{ key:constant, .. }
#[cfg(not(feature = "no_object"))]
Expr::Map(_, _) if expr.is_constant() => {
2020-11-14 12:04:49 +01:00
state.set_dirty();
2021-11-01 02:42:22 +01:00
*expr = Expr::DynamicConstant(expr.get_literal_value().expect("constant").into(), 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"))]
2021-06-02 08:29:18 +02:00
Expr::Map(x, _) => x.0.iter_mut().for_each(|(_, expr)| optimize_expr(expr, state, false)),
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();
2021-06-02 08:29:18 +02:00
optimize_expr(rhs, state, false);
2020-11-12 05:37:42 +01:00
*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();
2021-06-02 08:29:18 +02:00
optimize_expr(lhs, state, false);
2020-11-12 05:37:42 +01:00
*expr = mem::take(lhs);
2020-03-09 14:57:07 +01:00
}
2020-03-18 03:36:50 +01:00
// lhs && rhs
2021-06-02 08:29:18 +02:00
(lhs, rhs) => { optimize_expr(lhs, state, false); optimize_expr(rhs, state, false); }
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();
2021-06-02 08:29:18 +02:00
optimize_expr(rhs, state, false);
2020-11-12 05:37:42 +01:00
*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();
2021-06-02 08:29:18 +02:00
optimize_expr(lhs, state, false);
2020-11-12 05:37:42 +01:00
*expr = mem::take(lhs);
2020-03-09 14:57:07 +01:00
}
2020-03-18 03:36:50 +01:00
// lhs || rhs
2021-06-02 08:29:18 +02:00
(lhs, rhs) => { optimize_expr(lhs, state, false); optimize_expr(rhs, state, false); }
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;
}
2021-04-06 06:26:38 +02:00
// Fn
Expr::FnCall(x, pos)
2021-04-20 17:28:04 +02:00
if !x.is_qualified() // Non-qualified
2021-04-06 06:26:38 +02:00
&& state.optimization_level == OptimizationLevel::Simple // simple optimizations
&& x.args.len() == 1
&& x.args[0].is_constant()
2021-04-06 06:26:38 +02:00
&& x.name == KEYWORD_FN_PTR
=> {
let fn_name = match x.args[0] {
Expr::Stack(slot, _) => Some(x.constants[slot].clone()),
Expr::StringConstant(ref s, _) => Some(s.clone().into()),
_ => None
};
if let Some(fn_name) = fn_name {
if fn_name.is::<ImmutableString>() {
state.set_dirty();
2021-08-26 17:58:41 +02:00
let fn_ptr = FnPtr::new_unchecked(
2021-11-13 05:23:35 +01:00
fn_name.as_str_ref().expect("`ImmutableString`").into(),
2021-11-25 10:09:00 +01:00
StaticVec::new_const()
2021-08-26 17:58:41 +02:00
);
*expr = Expr::DynamicConstant(Box::new(fn_ptr.into()), *pos);
}
}
2021-04-06 06:26:38 +02:00
}
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()) => {
2021-06-02 08:29:18 +02:00
x.args.iter_mut().for_each(|a| optimize_expr(a, state, false));
}
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)
2021-04-20 17:28:04 +02:00
if !x.is_qualified() // Non-qualified
&& state.optimization_level == OptimizationLevel::Simple // simple optimizations
2020-10-31 07:13:45 +01:00
&& x.args.iter().all(Expr::is_constant) // all arguments are constants
//&& !is_valid_identifier(x.name.chars()) // cannot be scripted
=> {
let arg_values = &mut x.args.iter().map(|e| match e {
Expr::Stack(slot, _) => x.constants[*slot].clone(),
2021-11-01 02:42:22 +01:00
_ => e.get_literal_value().expect("constant")
}).collect::<StaticVec<_>>();
let arg_types: StaticVec<_> = arg_values.iter().map(Dynamic::type_id).collect();
2021-11-01 02:42:22 +01:00
match x.name.as_str() {
KEYWORD_TYPE_OF if arg_values.len() == 1 => {
state.set_dirty();
*expr = Expr::from_dynamic(state.engine.map_type_name(arg_values[0].type_name()).into(), *pos);
return;
2021-11-01 03:07:45 +01:00
}
2021-07-14 16:33:47 +02:00
#[cfg(not(feature = "no_closure"))]
2021-11-01 02:42:22 +01:00
KEYWORD_IS_SHARED if arg_values.len() == 1 => {
state.set_dirty();
*expr = Expr::from_dynamic(Dynamic::FALSE, *pos);
return;
}
// Overloaded operators can override built-in.
_ if x.args.len() == 2 && !state.has_native_fn_override(x.hashes.native, arg_types.as_ref()) => {
2021-11-01 02:42:22 +01:00
if let Some(result) = get_builtin_binary_op_fn(x.name.as_ref(), &arg_values[0], &arg_values[1])
.and_then(|f| {
2021-11-27 16:04:45 +01:00
let context = (state.engine, x.name.as_str(), state.lib).into();
2021-11-13 05:23:35 +01:00
let (first, second) = arg_values.split_first_mut().expect("not empty");
2021-11-05 12:35:33 +01:00
(f)(context, &mut [ first, &mut second[0] ]).ok()
2021-11-01 02:42:22 +01:00
}) {
state.set_dirty();
*expr = Expr::from_dynamic(result, *pos);
return;
}
}
2021-11-01 02:42:22 +01:00
_ => ()
}
2021-06-02 08:29:18 +02:00
x.args.iter_mut().for_each(|a| optimize_expr(a, state, false));
// Move constant arguments
2021-11-15 07:30:00 +01:00
let constants = &mut x.constants;
x.args.iter_mut().for_each(|arg| {
2021-06-10 04:16:39 +02:00
if let Some(value) = arg.get_literal_value() {
state.set_dirty();
2021-11-15 07:30:00 +01:00
constants.push(value);
*arg = Expr::Stack(constants.len()-1, arg.position());
}
2021-11-15 07:30:00 +01:00
});
}
2020-03-18 03:36:50 +01:00
// Eagerly call functions
2020-11-12 05:37:42 +01:00
Expr::FnCall(x, pos)
2021-04-20 17:28:04 +02:00
if !x.is_qualified() // 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"))]
2021-11-27 16:04:45 +01:00
let has_script_fn = state.lib.iter().any(|&m| m.get_script_fn(&x.name, x.args.len()).is_some());
2020-10-05 06:09:45 +02:00
#[cfg(feature = "no_function")]
let has_script_fn = false;
if !has_script_fn {
let arg_values = &mut x.args.iter().map(|e| match e {
Expr::Stack(slot, _) => x.constants[*slot].clone(),
2021-11-01 02:42:22 +01:00
_ => e.get_literal_value().expect("constant")
}).collect::<StaticVec<_>>();
let result = match x.name.as_str() {
KEYWORD_TYPE_OF if arg_values.len() == 1 => Some(state.engine.map_type_name(arg_values[0].type_name()).into()),
2021-07-14 16:33:47 +02:00
#[cfg(not(feature = "no_closure"))]
KEYWORD_IS_SHARED if arg_values.len() == 1 => Some(Dynamic::FALSE),
2021-11-27 16:04:45 +01:00
_ => state.call_fn_with_constant_arguments(&x.name, arg_values)
};
if let Some(result) = result {
2020-06-01 09:25:22 +02:00
state.set_dirty();
*expr = Expr::from_dynamic(result, *pos);
2020-11-12 05:37:42 +01:00
return;
}
}
2021-06-02 08:29:18 +02:00
x.args.iter_mut().for_each(|a| optimize_expr(a, state, false));
}
2020-03-19 12:53:42 +01:00
2020-03-18 03:36:50 +01:00
// id(args ..) -> optimize function call arguments
Expr::FnCall(x, _) => for arg in x.args.iter_mut() {
optimize_expr(arg, state, false);
// Move constant arguments
2021-06-10 04:16:39 +02:00
if let Some(value) = arg.get_literal_value() {
state.set_dirty();
x.constants.push(value);
*arg = Expr::Stack(x.constants.len()-1, arg.position());
}
},
2020-03-19 12:53:42 +01:00
2020-03-18 03:36:50 +01:00
// constant-name
2021-04-05 17:59:15 +02:00
Expr::Variable(_, pos, x) if x.1.is_none() && state.find_constant(&x.2).is_some() => {
2020-03-13 11:12:41 +01:00
// Replace constant with value
2021-11-13 05:23:35 +01:00
*expr = Expr::from_dynamic(state.find_constant(&x.2).expect("exists").clone(), *pos);
2021-05-16 15:21:13 +02:00
state.set_dirty();
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_may_be_changed {
2021-01-12 16:52:50 +01:00
state.propagate_constants = false;
}
2021-10-25 16:41:42 +02:00
x.inputs.iter_mut().for_each(|expr| optimize_expr(expr, state, false));
2021-01-12 16:52:50 +01:00
}
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.
///
/// Constants and variables from the scope are added.
2020-11-25 02:36:06 +01:00
fn optimize_top_level(
2021-09-12 08:34:00 +02:00
statements: StaticVec<Stmt>,
2020-04-16 17:31:48 +02:00
engine: &Engine,
scope: &Scope,
2020-10-20 04:54:32 +02:00
lib: &[&Module],
2021-03-11 11:29:22 +01:00
optimization_level: OptimizationLevel,
2021-09-12 08:34:00 +02:00
) -> StaticVec<Stmt> {
2021-08-13 07:42:39 +02:00
let mut statements = statements;
// If optimization level is None then skip optimizing
2021-03-11 11:29:22 +01:00
if optimization_level == OptimizationLevel::None {
2020-11-15 06:49:54 +01:00
statements.shrink_to_fit();
return statements;
}
// Set up the state
2021-07-04 10:40:15 +02:00
let mut state = OptimizerState::new(engine, lib, optimization_level);
// Add constants and variables from the scope
scope.iter().for_each(|(name, constant, value)| {
if !constant {
2021-05-16 15:21:13 +02:00
state.push_var(name, AccessMode::ReadWrite, None);
} else {
2021-05-16 15:21:13 +02:00
state.push_var(name, AccessMode::ReadOnly, Some(value));
}
});
2021-03-13 16:43:05 +01:00
statements = optimize_stmt_block(statements, &mut state, true, false, true);
2020-11-15 06:49:54 +01:00
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,
2021-09-12 08:34:00 +02:00
statements: StaticVec<Stmt>,
2021-11-27 16:20:05 +01:00
functions: StaticVec<Shared<ScriptFnDef>>,
2021-03-11 11:29:22 +01:00
optimization_level: OptimizationLevel,
) -> AST {
2020-07-31 16:30:23 +02:00
let level = if cfg!(feature = "no_optimize") {
2021-11-27 07:24:06 +01:00
OptimizationLevel::default()
2020-07-31 16:30:23 +02:00
} else {
2021-03-11 11:29:22 +01:00
optimization_level
2020-07-31 16:30:23 +02:00
};
2020-04-10 06:16:39 +02:00
2021-08-13 07:42:39 +02:00
let mut statements = statements;
let _functions = functions;
2020-09-24 17:32:54 +02:00
#[cfg(not(feature = "no_function"))]
let lib = {
let mut module = Module::new();
2021-05-18 06:24:11 +02:00
if level != OptimizationLevel::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()
2021-11-27 16:20:05 +01:00
.map(|fn_def| ScriptFnDef {
2020-11-25 02:36:06 +01:00
name: fn_def.name.clone(),
access: fn_def.access,
2021-11-28 03:49:48 +01:00
body: crate::ast::StmtBlock::NONE,
2020-11-25 02:36:06 +01:00
params: fn_def.params.clone(),
lib: None,
#[cfg(not(feature = "no_module"))]
2021-11-27 16:20:05 +01:00
mods: Imports::new(),
2021-04-09 16:49:47 +02:00
#[cfg(not(feature = "no_function"))]
#[cfg(feature = "metadata")]
2021-11-12 06:25:57 +01:00
comments: None,
})
2020-07-12 05:46:53 +02:00
.for_each(|fn_def| {
lib2.set_script_fn(fn_def);
});
2021-03-11 11:29:22 +01:00
let lib2 = &[&lib2];
2020-07-26 09:53:22 +02:00
_functions
.into_iter()
2021-03-12 07:11:08 +01:00
.map(|fn_def| {
2021-11-28 03:49:48 +01:00
let mut fn_def = crate::func::native::shared_take_or_clone(fn_def);
2021-03-12 07:11:08 +01:00
2021-03-13 16:43:05 +01:00
// Optimize the function body
2021-09-12 08:34:00 +02:00
let body = mem::take(fn_def.body.deref_mut());
2021-03-10 15:12:48 +01:00
*fn_def.body = optimize_top_level(body, engine, scope, lib2, level);
2021-03-10 15:12:48 +01:00
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 = Module::new();
2020-09-24 17:32:54 +02:00
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,
)
}