forked from rhaiscript/rhai
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathoptimizer.rs
1422 lines (1303 loc) · 55.3 KB
/
optimizer.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Module implementing the [`AST`] optimizer.
#![cfg(not(feature = "no_optimize"))]
use crate::ast::{
ASTFlags, Expr, FlowControl, OpAssignment, Stmt, StmtBlock, StmtBlockContainer,
SwitchCasesCollection,
};
use crate::engine::{
KEYWORD_DEBUG, KEYWORD_EVAL, KEYWORD_FN_PTR, KEYWORD_FN_PTR_CURRY, KEYWORD_PRINT,
KEYWORD_TYPE_OF, OP_NOT,
};
use crate::eval::{Caches, GlobalRuntimeState};
use crate::func::builtin::get_builtin_binary_op_fn;
use crate::func::hashing::get_hasher;
use crate::tokenizer::Token;
use crate::{
calc_fn_hash, calc_fn_hash_full, Dynamic, Engine, FnArgsVec, FnPtr, ImmutableString, Position,
Scope, AST,
};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
any::TypeId,
borrow::Cow,
convert::TryFrom,
hash::{Hash, Hasher},
mem,
};
/// Level of optimization performed.
///
/// Not available under `no_optimize`.
#[derive(Debug, Eq, PartialEq, Clone, Copy, Default, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub enum OptimizationLevel {
/// No optimization performed.
None,
/// Only perform simple optimizations without evaluating functions.
#[default]
Simple,
/// Full optimizations performed, including evaluating functions.
/// Take care that this may cause side effects as it essentially assumes that all functions are pure.
Full,
}
/// Mutable state throughout an optimization pass.
#[derive(Debug, Clone)]
struct OptimizerState<'a> {
/// Has the [`AST`] been changed during this pass?
is_dirty: bool,
/// Stack of variables/constants for constants propagation and strict variables checking.
variables: Vec<(ImmutableString, Option<Cow<'a, Dynamic>>)>,
/// Activate constants propagation?
propagate_constants: bool,
/// [`Engine`] instance for eager function evaluation.
engine: &'a Engine,
/// Optional [`Scope`].
scope: Option<&'a Scope<'a>>,
/// The global runtime state.
global: GlobalRuntimeState,
/// Function resolution caches.
caches: Caches,
/// Optimization level.
optimization_level: OptimizationLevel,
}
impl<'a> OptimizerState<'a> {
/// Create a new [`OptimizerState`].
#[inline(always)]
pub fn new(
engine: &'a Engine,
lib: &'a [crate::SharedModule],
scope: Option<&'a Scope<'a>>,
optimization_level: OptimizationLevel,
) -> Self {
let mut _global = engine.new_global_runtime_state();
let _lib = lib;
#[cfg(not(feature = "no_function"))]
{
_global.lib = _lib.into();
}
Self {
is_dirty: false,
variables: Vec::new(),
propagate_constants: true,
engine,
scope,
global: _global,
caches: Caches::new(),
optimization_level,
}
}
/// Set the [`AST`] state to be dirty (i.e. changed).
#[inline(always)]
pub fn set_dirty(&mut self) {
self.is_dirty = true;
}
/// Set the [`AST`] state to be not dirty (i.e. unchanged).
#[inline(always)]
pub fn clear_dirty(&mut self) {
self.is_dirty = false;
}
/// Is the [`AST`] dirty (i.e. changed)?
#[inline(always)]
pub const fn is_dirty(&self) -> bool {
self.is_dirty
}
/// Rewind the variables stack back to a specified size.
#[inline(always)]
pub fn rewind_var(&mut self, len: usize) {
self.variables.truncate(len);
}
/// Add a new variable to the stack.
///
/// `Some(value)` if literal constant (which can be used for constants propagation), `None` otherwise.
#[inline(always)]
pub fn push_var<'x: 'a>(&mut self, name: ImmutableString, value: Option<Cow<'x, Dynamic>>) {
self.variables.push((name, value));
}
/// Look up a literal constant from the variables stack.
#[inline]
pub fn find_literal_constant(&self, name: &str) -> Option<&Dynamic> {
self.variables
.iter()
.rev()
.find(|(n, _)| n == name)
.and_then(|(_, value)| value.as_deref())
}
/// Call a registered function
#[inline]
pub fn call_fn_with_const_args(
&mut self,
fn_name: &str,
op_token: Option<&Token>,
arg_values: &mut [Dynamic],
) -> Option<Dynamic> {
self.engine
.exec_native_fn_call(
&mut self.global,
&mut self.caches,
fn_name,
op_token,
calc_fn_hash(None, fn_name, arg_values.len()),
&mut arg_values.iter_mut().collect::<FnArgsVec<_>>(),
false,
true,
Position::NONE,
)
.ok()
.map(|(v, ..)| v)
}
}
/// Optimize a block of [statements][Stmt].
fn optimize_stmt_block(
mut statements: StmtBlockContainer,
state: &mut OptimizerState,
preserve_result: bool,
is_internal: bool,
reduce_return: bool,
) -> StmtBlockContainer {
if statements.is_empty() {
return statements;
}
let mut is_dirty = state.is_dirty();
let is_pure = if is_internal {
Stmt::is_internally_pure
} else {
Stmt::is_pure
};
// Flatten blocks
while let Some(n) = statements.iter().position(
|s| matches!(s, Stmt::Block(block, ..) if !block.iter().any(Stmt::is_block_dependent)),
) {
let (first, second) = statements.split_at_mut(n);
let mut stmt = second[0].take();
let stmts = match stmt {
Stmt::Block(ref mut block, ..) => block.statements_mut(),
_ => unreachable!("Stmt::Block expected but gets {:?}", stmt),
};
statements = first
.iter_mut()
.map(mem::take)
.chain(stmts.iter_mut().map(mem::take))
.chain(second.iter_mut().skip(1).map(mem::take))
.collect();
is_dirty = true;
}
// Optimize
loop {
state.clear_dirty();
let orig_constants_len = state.variables.len(); // Original number of constants in the state, for restore later
let orig_propagate_constants = state.propagate_constants;
// Remove everything following control flow breaking statements
let mut dead_code = false;
statements.retain(|stmt| {
if dead_code {
state.set_dirty();
false
} else if stmt.is_control_flow_break() {
dead_code = true;
true
} else {
true
}
});
// Optimize each statement in the block
statements.iter_mut().for_each(|stmt| {
match stmt {
Stmt::Var(x, options, ..) => {
optimize_expr(&mut x.1, state, false);
let value = if options.intersects(ASTFlags::CONSTANT) && x.1.is_constant() {
// constant literal
Some(Cow::Owned(x.1.get_literal_value().unwrap()))
} else {
// variable
None
};
state.push_var(x.0.name.clone(), value);
}
// Optimize the statement
_ => optimize_stmt(stmt, state, preserve_result),
}
});
// Remove all pure statements except the last one
let mut index = 0;
let mut first_non_constant = statements
.iter()
.rev()
.position(|stmt| match stmt {
stmt if !is_pure(stmt) => true,
Stmt::Var(x, ..) if x.1.is_constant() => true,
Stmt::Expr(e) if !e.is_constant() => true,
#[cfg(not(feature = "no_module"))]
Stmt::Import(x, ..) if !x.0.is_constant() => true,
_ => false,
})
.map_or(0, |n| statements.len() - n - 1);
while index < statements.len() {
if preserve_result && index >= statements.len() - 1 {
break;
}
match statements[index] {
ref stmt if is_pure(stmt) && index >= first_non_constant => {
state.set_dirty();
statements.remove(index);
}
ref stmt if stmt.is_pure() => {
state.set_dirty();
if index < first_non_constant {
first_non_constant -= 1;
}
statements.remove(index);
}
_ => index += 1,
}
}
// 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 {
match statements[..] {
// { return; } -> {}
[Stmt::Return(None, options, ..)]
if reduce_return && !options.intersects(ASTFlags::BREAK) =>
{
state.set_dirty();
statements.clear();
}
[ref stmt] if !stmt.returns_value() && is_pure(stmt) => {
state.set_dirty();
statements.clear();
}
// { ...; return; } -> { ... }
[.., ref last_stmt, Stmt::Return(None, options, ..)]
if reduce_return
&& !options.intersects(ASTFlags::BREAK)
&& !last_stmt.returns_value() =>
{
state.set_dirty();
statements.pop().unwrap();
}
// { ...; return val; } -> { ...; val }
[.., Stmt::Return(ref mut expr, options, pos)]
if reduce_return && !options.intersects(ASTFlags::BREAK) =>
{
state.set_dirty();
*statements.last_mut().unwrap() = expr
.as_mut()
.map_or_else(|| Stmt::Noop(pos), |e| Stmt::Expr(mem::take(e)));
}
// { ...; stmt; noop } -> done
[.., ref second_last_stmt, Stmt::Noop(..)]
if second_last_stmt.returns_value() =>
{
break
}
// { ...; stmt_that_returns; pure_non_value_stmt } -> { ...; stmt_that_returns; noop }
// { ...; stmt; pure_non_value_stmt } -> { ...; stmt }
[.., ref second_last_stmt, ref last_stmt]
if !last_stmt.returns_value() && is_pure(last_stmt) =>
{
state.set_dirty();
if second_last_stmt.returns_value() {
*statements.last_mut().unwrap() = Stmt::Noop(last_stmt.position());
} else {
statements.pop().unwrap();
}
}
_ => break,
}
}
} else {
loop {
match statements[..] {
[ref stmt] if is_pure(stmt) => {
state.set_dirty();
statements.clear();
}
// { ...; return; } -> { ... }
[.., Stmt::Return(None, options, ..)]
if reduce_return && !options.intersects(ASTFlags::BREAK) =>
{
state.set_dirty();
statements.pop().unwrap();
}
// { ...; return pure_val; } -> { ... }
[.., Stmt::Return(Some(ref expr), options, ..)]
if reduce_return
&& !options.intersects(ASTFlags::BREAK)
&& expr.is_pure() =>
{
state.set_dirty();
statements.pop().unwrap();
}
[.., ref last_stmt] if is_pure(last_stmt) => {
state.set_dirty();
statements.pop().unwrap();
}
_ => break,
}
}
}
// Pop the stack and remove all the local constants
state.rewind_var(orig_constants_len);
state.propagate_constants = orig_propagate_constants;
if !state.is_dirty() {
break;
}
is_dirty = true;
}
if is_dirty {
state.set_dirty();
}
statements.shrink_to_fit();
statements
}
impl StmtBlock {
#[inline(always)]
#[must_use]
fn take_statements(&mut self) -> StmtBlockContainer {
mem::take(self.statements_mut())
}
}
/// Is this [`Expr`] a constant that is hashable?
#[inline(always)]
fn is_hashable_constant(expr: &Expr) -> bool {
match expr {
_ if !expr.is_constant() => false,
Expr::DynamicConstant(v, ..) => v.is_hashable(),
_ => false,
}
}
/// Optimize a [statement][Stmt].
fn optimize_stmt(stmt: &mut Stmt, state: &mut OptimizerState, preserve_result: bool) {
#[inline(always)]
#[must_use]
fn is_variable_access(expr: &Expr, _non_qualified: bool) -> bool {
match expr {
#[cfg(not(feature = "no_module"))]
Expr::Variable(x, ..) if _non_qualified && !x.2.is_empty() => false,
Expr::Variable(..) => true,
_ => false,
}
}
match stmt {
// var = var op expr => var op= expr
Stmt::Assignment(x, ..)
if !x.0.is_op_assignment()
&& is_variable_access(&x.1.lhs, true)
&& matches!(&x.1.rhs, Expr::FnCall(x2, ..)
if Token::lookup_symbol_from_syntax(&x2.name).map_or(false, |t| t.has_op_assignment())
&& x2.args.len() == 2
&& x2.args[0].get_variable_name(true) == x.1.lhs.get_variable_name(true)
) =>
{
match x.1.rhs {
Expr::FnCall(ref mut x2, pos) => {
state.set_dirty();
x.0 = OpAssignment::new_op_assignment_from_base(&x2.name, pos);
x.1.rhs = x2.args[1].take();
}
ref expr => unreachable!("Expr::FnCall expected but gets {:?}", expr),
}
}
// expr op= expr
Stmt::Assignment(x, ..) => {
if !is_variable_access(&x.1.lhs, false) {
optimize_expr(&mut x.1.lhs, state, false);
}
optimize_expr(&mut x.1.rhs, state, false);
}
// if expr {}
Stmt::If(x, ..) if x.body.is_empty() && x.branch.is_empty() => {
let condition = &mut x.expr;
state.set_dirty();
let pos = condition.start_position();
let mut expr = condition.take();
optimize_expr(&mut expr, state, false);
*stmt = if preserve_result {
// -> { expr, Noop }
Stmt::Block(
StmtBlock::new(
[Stmt::Expr(expr.into()), Stmt::Noop(pos)],
pos,
Position::NONE,
)
.into(),
)
} else {
// -> expr
Stmt::Expr(expr.into())
};
}
// if false { if_block } -> Noop
Stmt::If(x, ..)
if matches!(x.expr, Expr::BoolConstant(false, ..)) && x.branch.is_empty() =>
{
match x.expr {
Expr::BoolConstant(false, pos) => {
state.set_dirty();
*stmt = Stmt::Noop(pos);
}
_ => unreachable!("`Expr::BoolConstant`"),
}
}
// if false { if_block } else { else_block } -> else_block
Stmt::If(x, ..) if matches!(x.expr, Expr::BoolConstant(false, ..)) => {
state.set_dirty();
let body = x.branch.take_statements();
*stmt = match optimize_stmt_block(body, state, preserve_result, true, false) {
statements if statements.is_empty() => Stmt::Noop(x.branch.position()),
statements => {
Stmt::Block(StmtBlock::new_with_span(statements, x.branch.span()).into())
}
}
}
// if true { if_block } else { else_block } -> if_block
Stmt::If(x, ..) if matches!(x.expr, Expr::BoolConstant(true, ..)) => {
state.set_dirty();
let body = x.body.take_statements();
*stmt = match optimize_stmt_block(body, state, preserve_result, true, false) {
statements if statements.is_empty() => Stmt::Noop(x.body.position()),
statements => {
Stmt::Block(StmtBlock::new_with_span(statements, x.body.span()).into())
}
}
}
// if expr { if_block } else { else_block }
Stmt::If(x, ..) => {
let FlowControl { expr, body, branch } = &mut **x;
optimize_expr(expr, state, false);
*body.statements_mut() =
optimize_stmt_block(body.take_statements(), state, preserve_result, true, false);
*branch.statements_mut() = optimize_stmt_block(
branch.take_statements(),
state,
preserve_result,
true,
false,
);
}
// switch const { ... }
Stmt::Switch(x, pos) if is_hashable_constant(&x.0) => {
let (
match_expr,
SwitchCasesCollection {
expressions,
cases,
ranges,
def_case,
},
) = &mut **x;
let value = match_expr.get_literal_value().unwrap();
let hasher = &mut get_hasher();
value.hash(hasher);
let hash = hasher.finish();
// First check hashes
if let Some(case_blocks_list) = cases.get(&hash) {
match &case_blocks_list[..] {
[] => (),
[index] => {
let mut b = mem::take(&mut expressions[*index]);
cases.clear();
if matches!(b.lhs, Expr::BoolConstant(true, ..)) {
// Promote the matched case
let mut statements = Stmt::Expr(b.rhs.take().into());
optimize_stmt(&mut statements, state, true);
*stmt = statements;
} else {
// switch const { case if condition => stmt, _ => def } => if condition { stmt } else { def }
optimize_expr(&mut b.lhs, state, false);
let branch = def_case.map_or(StmtBlock::NONE, |index| {
let mut def_stmt = Stmt::Expr(expressions[index].rhs.take().into());
optimize_stmt(&mut def_stmt, state, true);
def_stmt.into()
});
let body = Stmt::Expr(b.rhs.take().into()).into();
let expr = b.lhs.take();
*stmt = Stmt::If(
FlowControl { expr, body, branch }.into(),
match_expr.start_position(),
);
}
state.set_dirty();
return;
}
_ => {
for &index in case_blocks_list {
let mut b = mem::take(&mut expressions[index]);
if matches!(b.lhs, Expr::BoolConstant(true, ..)) {
// Promote the matched case
let mut statements = Stmt::Expr(b.rhs.take().into());
optimize_stmt(&mut statements, state, true);
*stmt = statements;
state.set_dirty();
return;
}
}
}
}
}
// Then check ranges
if !ranges.is_empty() {
// Only one range or all ranges without conditions
if ranges.len() == 1
|| ranges
.iter()
.all(|r| matches!(expressions[r.index()].lhs, Expr::BoolConstant(true, ..)))
{
if let Some(r) = ranges.iter().find(|r| r.contains(&value)) {
let range_block = &mut expressions[r.index()];
if matches!(range_block.lhs, Expr::BoolConstant(true, ..)) {
// Promote the matched case
let block = &mut expressions[r.index()];
let mut statements = Stmt::Expr(block.rhs.take().into());
optimize_stmt(&mut statements, state, true);
*stmt = statements;
} else {
let mut expr = range_block.lhs.take();
// switch const { range if condition => stmt, _ => def } => if condition { stmt } else { def }
optimize_expr(&mut expr, state, false);
let branch = def_case.map_or(StmtBlock::NONE, |index| {
let mut def_stmt = Stmt::Expr(expressions[index].rhs.take().into());
optimize_stmt(&mut def_stmt, state, true);
def_stmt.into()
});
let body = Stmt::Expr(expressions[r.index()].rhs.take().into()).into();
*stmt = Stmt::If(
FlowControl { expr, body, branch }.into(),
match_expr.start_position(),
);
}
state.set_dirty();
return;
}
} else {
// Multiple ranges - clear the table and just keep the right ranges
if !cases.is_empty() {
state.set_dirty();
cases.clear();
}
let old_ranges_len = ranges.len();
ranges.retain(|r| r.contains(&value));
if ranges.len() != old_ranges_len {
state.set_dirty();
}
for r in ranges {
let b = &mut expressions[r.index()];
optimize_expr(&mut b.lhs, state, false);
optimize_expr(&mut b.rhs, state, false);
}
return;
}
}
// Promote the default case
state.set_dirty();
match def_case {
Some(index) => {
let mut def_stmt = Stmt::Expr(expressions[*index].rhs.take().into());
optimize_stmt(&mut def_stmt, state, true);
*stmt = def_stmt;
}
_ => *stmt = Stmt::Block(StmtBlock::empty(*pos).into()),
}
}
// switch
Stmt::Switch(x, ..) => {
let (
match_expr,
SwitchCasesCollection {
expressions,
cases,
ranges,
def_case,
..
},
) = &mut **x;
optimize_expr(match_expr, state, false);
// Optimize blocks
for b in &mut *expressions {
optimize_expr(&mut b.lhs, state, false);
optimize_expr(&mut b.rhs, state, false);
if matches!(b.lhs, Expr::BoolConstant(false, ..)) && !b.rhs.is_unit() {
b.rhs = Expr::Unit(b.rhs.position());
state.set_dirty();
}
}
// Remove false cases
cases.retain(|_, list| {
// Remove all entries that have false conditions
list.retain(|index| {
if matches!(expressions[*index].lhs, Expr::BoolConstant(false, ..)) {
state.set_dirty();
false
} else {
true
}
});
// Remove all entries after a `true` condition
if let Some(n) = list.iter().position(|&index| {
matches!(expressions[index].lhs, Expr::BoolConstant(true, ..))
}) {
if n + 1 < list.len() {
state.set_dirty();
list.truncate(n + 1);
}
}
// Remove if no entry left
if list.is_empty() {
state.set_dirty();
false
} else {
true
}
});
// Remove false ranges
ranges.retain(|r| {
if matches!(expressions[r.index()].lhs, Expr::BoolConstant(false, ..)) {
state.set_dirty();
false
} else {
true
}
});
if let Some(index) = def_case {
optimize_expr(&mut expressions[*index].rhs, state, false);
}
// Remove unused block statements
expressions.iter_mut().enumerate().for_each(|(index, b)| {
if *def_case != Some(index)
&& cases.values().flat_map(|c| c.iter()).all(|&n| n != index)
&& ranges.iter().all(|r| r.index() != index)
&& !b.rhs.is_unit()
{
b.rhs = Expr::Unit(b.rhs.position());
state.set_dirty();
}
});
}
// while false { block } -> Noop
Stmt::While(x, ..) if matches!(x.expr, Expr::BoolConstant(false, ..)) => match x.expr {
Expr::BoolConstant(false, pos) => {
state.set_dirty();
*stmt = Stmt::Noop(pos);
}
_ => unreachable!("`Expr::BoolConstant"),
},
// while expr { block }
Stmt::While(x, ..) => {
let FlowControl { expr, body, .. } = &mut **x;
optimize_expr(expr, state, false);
if let Expr::BoolConstant(true, pos) = expr {
*expr = Expr::Unit(*pos);
}
*body.statements_mut() =
optimize_stmt_block(body.take_statements(), state, false, true, false);
}
// do { block } while|until expr
Stmt::Do(x, ..) => {
optimize_expr(&mut x.expr, state, false);
*x.body.statements_mut() =
optimize_stmt_block(x.body.take_statements(), state, false, true, false);
}
// for id in expr { block }
Stmt::For(x, ..) => {
optimize_expr(&mut x.2.expr, state, false);
*x.2.body.statements_mut() =
optimize_stmt_block(x.2.body.take_statements(), state, false, true, false);
}
// let id = expr;
Stmt::Var(x, options, ..) if !options.intersects(ASTFlags::CONSTANT) => {
optimize_expr(&mut x.1, state, false);
}
// import expr as var;
#[cfg(not(feature = "no_module"))]
Stmt::Import(x, ..) => optimize_expr(&mut x.0, state, false),
// { block }
Stmt::Block(block) => {
let mut stmts =
optimize_stmt_block(block.take_statements(), state, preserve_result, true, false);
match stmts.as_mut_slice() {
[] => {
state.set_dirty();
*stmt = Stmt::Noop(block.span().start());
}
// Only one statement which is not block-dependent - promote
[s] if !s.is_block_dependent() => {
state.set_dirty();
*stmt = s.take();
}
_ => *block.statements_mut() = stmts,
}
}
// try { pure try_block } catch ( var ) { catch_block } -> try_block
Stmt::TryCatch(x, ..) if x.body.iter().all(Stmt::is_pure) => {
// If try block is pure, there will never be any exceptions
state.set_dirty();
let statements = x.body.take_statements();
let block = StmtBlock::new_with_span(
optimize_stmt_block(statements, state, false, true, false),
x.body.span(),
);
*stmt = Stmt::Block(block.into());
}
// try { try_block } catch ( var ) { catch_block }
Stmt::TryCatch(x, ..) => {
*x.body.statements_mut() =
optimize_stmt_block(x.body.take_statements(), state, false, true, false);
*x.branch.statements_mut() =
optimize_stmt_block(x.branch.take_statements(), state, false, true, false);
}
// expr(stmt)
Stmt::Expr(expr) if matches!(**expr, Expr::Stmt(..)) => {
state.set_dirty();
match expr.as_mut() {
Expr::Stmt(block) if !block.is_empty() => {
let mut stmts_blk = mem::take(block.as_mut());
*stmts_blk.statements_mut() =
optimize_stmt_block(stmts_blk.take_statements(), state, true, true, false);
*stmt = Stmt::Block(stmts_blk.into());
}
Expr::Stmt(..) => *stmt = Stmt::Noop(expr.position()),
_ => unreachable!("`Expr::Stmt`"),
}
}
// expr(func())
Stmt::Expr(expr) if matches!(**expr, Expr::FnCall(..)) => {
state.set_dirty();
match expr.take() {
Expr::FnCall(x, pos) => *stmt = Stmt::FnCall(x, pos),
_ => unreachable!(),
}
}
Stmt::Expr(expr) => optimize_expr(expr, state, false),
// func(...)
Stmt::FnCall(..) => match stmt.take() {
Stmt::FnCall(x, pos) => {
let mut expr = Expr::FnCall(x, pos);
optimize_expr(&mut expr, state, false);
*stmt = match expr {
Expr::FnCall(x, pos) => Stmt::FnCall(x, pos),
_ => Stmt::Expr(expr.into()),
}
}
_ => unreachable!(),
},
// break expr;
Stmt::BreakLoop(Some(ref mut expr), ..) => optimize_expr(expr, state, false),
// return expr;
Stmt::Return(Some(ref mut expr), ..) => optimize_expr(expr, state, false),
// Share nothing
#[cfg(not(feature = "no_closure"))]
Stmt::Share(x) if x.is_empty() => {
state.set_dirty();
*stmt = Stmt::Noop(Position::NONE);
}
// Share constants
#[cfg(not(feature = "no_closure"))]
Stmt::Share(x) => {
let orig_len = x.len();
if state.propagate_constants {
x.retain(|(v, _)| state.find_literal_constant(v.as_str()).is_none());
if x.len() != orig_len {
state.set_dirty();
}
}
}
// All other statements - skip
_ => (),
}
}
// Convert a constant argument into [`Expr::DynamicConstant`].
fn move_constant_arg(arg_expr: &mut Expr) -> bool {
match arg_expr {
Expr::DynamicConstant(..)
| Expr::Unit(..)
| Expr::StringConstant(..)
| Expr::CharConstant(..)
| Expr::BoolConstant(..)
| Expr::IntegerConstant(..) => false,
#[cfg(not(feature = "no_float"))]
Expr::FloatConstant(..) => false,
_ => {
if let Some(value) = arg_expr.get_literal_value() {
*arg_expr = Expr::DynamicConstant(value.into(), arg_expr.start_position());
true
} else {
false
}
}
}
}
/// Optimize an [expression][Expr].
fn optimize_expr(expr: &mut Expr, state: &mut OptimizerState, _chaining: bool) {
// These keywords are handled specially
const DONT_EVAL_KEYWORDS: &[&str] = &[
KEYWORD_PRINT, // side effects
KEYWORD_DEBUG, // side effects
KEYWORD_EVAL, // arbitrary scripts
];
match expr {
// {}
Expr::Stmt(x) if x.is_empty() => { state.set_dirty(); *expr = Expr::Unit(x.position()) }
Expr::Stmt(x) if x.len() == 1 && matches!(x.statements()[0], Stmt::Expr(..)) => {
state.set_dirty();
match x.take_statements().remove(0) {
Stmt::Expr(mut e) => {
optimize_expr(&mut e, state, false);
*expr = *e;
}
_ => unreachable!("`Expr::Stmt`")
}
}
// { stmt; ... } - do not count promotion as dirty because it gets turned back into an array
Expr::Stmt(x) => {
*x.statements_mut() = optimize_stmt_block(x.take_statements(), state, true, true, false);
// { Stmt(Expr) } - promote
if let [ Stmt::Expr(e) ] = x.statements_mut().as_mut() { state.set_dirty(); *expr = e.take(); }
}
// ()?.rhs
#[cfg(not(feature = "no_object"))]
Expr::Dot(x, options, ..) if options.intersects(ASTFlags::NEGATED) && matches!(x.lhs, Expr::Unit(..)) => {
state.set_dirty();
*expr = x.lhs.take();
}
// lhs.rhs
#[cfg(not(feature = "no_object"))]
Expr::Dot(x, ..) if !_chaining => match (&mut x.lhs, &mut x.rhs) {
// map.string
(Expr::Map(m, pos), Expr::Property(p, ..)) 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();
*expr = mem::take(&mut m.0).into_iter().find(|(x, ..)| x.name == p.2)
.map_or_else(|| Expr::Unit(*pos), |(.., mut expr)| { expr.set_position(*pos); expr });
}
// var.rhs or this.rhs
(Expr::Variable(..) | Expr::ThisPtr(..), rhs) => optimize_expr(rhs, state, true),
// const.type_of()
(lhs, Expr::MethodCall(x, pos)) if lhs.is_constant() && x.name == KEYWORD_TYPE_OF && x.args.is_empty() => {
if let Some(value) = lhs.get_literal_value() {
state.set_dirty();
let typ = state.engine.map_type_name(value.type_name()).into();
*expr = Expr::from_dynamic(typ, *pos);
}
}
// const.is_shared()
#[cfg(not(feature = "no_closure"))]
(lhs, Expr::MethodCall(x, pos)) if lhs.is_constant() && x.name == crate::engine::KEYWORD_IS_SHARED && x.args.is_empty() => {
if lhs.get_literal_value().is_some() {
state.set_dirty();
*expr = Expr::from_dynamic(Dynamic::FALSE, *pos);
}
}
// lhs.rhs
(lhs, rhs) => { optimize_expr(lhs, state, false); optimize_expr(rhs, state, true); }
}
// ....lhs.rhs
#[cfg(not(feature = "no_object"))]
Expr::Dot(x,..) => { optimize_expr(&mut x.lhs, state, false); optimize_expr(&mut x.rhs, state, _chaining); }
// ()?[rhs]
#[cfg(not(feature = "no_index"))]
Expr::Index(x, options, ..) if options.intersects(ASTFlags::NEGATED) && matches!(x.lhs, Expr::Unit(..)) => {
state.set_dirty();
*expr = x.lhs.take();
}
// lhs[rhs]
#[cfg(not(feature = "no_index"))]
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
Expr::Index(x, ..) if !_chaining => match (&mut x.lhs, &mut x.rhs) {
// array[int]
(Expr::Array(a, pos), Expr::IntegerConstant(i, ..)) if *i >= 0 && *i <= crate::MAX_USIZE_INT && (*i as usize) < a.len() && 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();
let mut result = a[*i as usize].take();
result.set_position(*pos);
*expr = result;
}
// array[-int]
#[allow(clippy::unnecessary_cast)]