terser 5.6.0 → 5.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -41,34 +41,11 @@
41
41
 
42
42
  ***********************************************************************/
43
43
 
44
- "use strict";
45
-
46
- import {
47
- defaults,
48
- HOP,
49
- keep_name,
50
- make_node,
51
- makePredicate,
52
- map_add,
53
- MAP,
54
- member,
55
- noop,
56
- remove,
57
- return_false,
58
- return_null,
59
- return_this,
60
- return_true,
61
- string_template,
62
- regexp_source_fix,
63
- has_annotation
64
- } from "../utils/index.js";
65
- import { first_in_statement, } from "../utils/first_in_statement.js";
66
44
  import {
67
45
  AST_Accessor,
68
46
  AST_Array,
69
47
  AST_Arrow,
70
48
  AST_Assign,
71
- AST_Await,
72
49
  AST_BigInt,
73
50
  AST_Binary,
74
51
  AST_Block,
@@ -86,7 +63,6 @@ import {
86
63
  AST_Conditional,
87
64
  AST_Const,
88
65
  AST_Constant,
89
- AST_Continue,
90
66
  AST_Debugger,
91
67
  AST_Default,
92
68
  AST_DefaultAssign,
@@ -103,7 +79,6 @@ import {
103
79
  AST_Expansion,
104
80
  AST_Export,
105
81
  AST_False,
106
- AST_Finally,
107
82
  AST_For,
108
83
  AST_ForIn,
109
84
  AST_Function,
@@ -112,21 +87,17 @@ import {
112
87
  AST_Import,
113
88
  AST_Infinity,
114
89
  AST_IterationStatement,
115
- AST_Jump,
116
90
  AST_LabeledStatement,
117
91
  AST_Lambda,
118
92
  AST_Let,
119
- AST_LoopControl,
120
93
  AST_NaN,
121
94
  AST_New,
122
95
  AST_Node,
123
96
  AST_Null,
124
97
  AST_Number,
125
98
  AST_Object,
126
- AST_ObjectGetter,
127
99
  AST_ObjectKeyVal,
128
100
  AST_ObjectProperty,
129
- AST_ObjectSetter,
130
101
  AST_PrefixedTemplateString,
131
102
  AST_PropAccess,
132
103
  AST_RegExp,
@@ -138,12 +109,10 @@ import {
138
109
  AST_String,
139
110
  AST_Sub,
140
111
  AST_Switch,
141
- AST_SwitchBranch,
142
112
  AST_Symbol,
143
113
  AST_SymbolBlockDeclaration,
144
114
  AST_SymbolCatch,
145
115
  AST_SymbolClassProperty,
146
- AST_SymbolConst,
147
116
  AST_SymbolDeclaration,
148
117
  AST_SymbolDefun,
149
118
  AST_SymbolExport,
@@ -153,7 +122,6 @@ import {
153
122
  AST_SymbolMethod,
154
123
  AST_SymbolRef,
155
124
  AST_SymbolVar,
156
- AST_TemplateSegment,
157
125
  AST_TemplateString,
158
126
  AST_This,
159
127
  AST_Toplevel,
@@ -173,13 +141,28 @@ import {
173
141
  TreeWalker,
174
142
  walk,
175
143
  walk_abort,
176
- walk_body,
177
144
  walk_parent,
178
145
 
179
146
  _INLINE,
180
147
  _NOINLINE,
181
148
  _PURE
182
149
  } from "../ast.js";
150
+ import {
151
+ defaults,
152
+ HOP,
153
+ keep_name,
154
+ make_node,
155
+ makePredicate,
156
+ map_add,
157
+ MAP,
158
+ member,
159
+ remove,
160
+ return_false,
161
+ return_true,
162
+ regexp_source_fix,
163
+ has_annotation
164
+ } from "../utils/index.js";
165
+ import { first_in_statement } from "../utils/first_in_statement.js";
183
166
  import { equivalent_to } from "../equivalent-to.js";
184
167
  import {
185
168
  is_basic_identifier_string,
@@ -194,27 +177,52 @@ import {
194
177
  } from "../scope.js";
195
178
  import "../size.js";
196
179
 
197
- const UNUSED = 0b00000001;
198
- const TRUTHY = 0b00000010;
199
- const FALSY = 0b00000100;
200
- const UNDEFINED = 0b00001000;
201
- const INLINED = 0b00010000;
202
- // Nodes to which values are ever written. Used when keep_assign is part of the unused option string.
203
- const WRITE_ONLY= 0b00100000;
204
-
205
- // information specific to a single compression pass
206
- const SQUEEZED = 0b0000000100000000;
207
- const OPTIMIZED = 0b0000001000000000;
208
- const TOP = 0b0000010000000000;
209
-
210
- const CLEAR_BETWEEN_PASSES = SQUEEZED | OPTIMIZED | TOP;
211
-
212
- /*@__INLINE__*/
213
- const has_flag = (node, flag) => node.flags & flag;
214
- /*@__INLINE__*/
215
- const set_flag = (node, flag) => { node.flags |= flag; };
216
- /*@__INLINE__*/
217
- const clear_flag = (node, flag) => { node.flags &= ~flag; };
180
+ import "./evaluate.js";
181
+ import "./drop-side-effect-free.js";
182
+ import "./reduce-vars.js";
183
+ import {
184
+ is_undeclared_ref,
185
+ lazy_op,
186
+ is_nullish,
187
+ is_undefined,
188
+ is_lhs,
189
+ aborts,
190
+ } from "./inference.js";
191
+ import {
192
+ SQUEEZED,
193
+ OPTIMIZED,
194
+ INLINED,
195
+ CLEAR_BETWEEN_PASSES,
196
+ TOP,
197
+ WRITE_ONLY,
198
+ UNDEFINED,
199
+ UNUSED,
200
+ TRUTHY,
201
+ FALSY,
202
+
203
+ has_flag,
204
+ set_flag,
205
+ clear_flag,
206
+ } from "./compressor-flags.js";
207
+ import {
208
+ make_sequence,
209
+ best_of,
210
+ best_of_expression,
211
+ make_node_from_constant,
212
+ merge_sequence,
213
+ get_simple_key,
214
+ has_break_or_continue,
215
+ maintain_this_binding,
216
+ identifier_atom,
217
+ is_identifier_atom,
218
+ is_func_expr,
219
+ is_ref_of,
220
+ can_be_evicted_from_block,
221
+ as_statement_array,
222
+ is_iife_call,
223
+ is_recursive_ref
224
+ } from "./common.js";
225
+ import { tighten_body, trim_unreachable_code } from "./tighten-body.js";
218
226
 
219
227
  class Compressor extends TreeWalker {
220
228
  constructor(options, { false_by_default = false, mangle_options = false }) {
@@ -256,7 +264,7 @@ class Compressor extends TreeWalker {
256
264
  properties : !false_by_default,
257
265
  pure_getters : !false_by_default && "strict",
258
266
  pure_funcs : null,
259
- reduce_funcs : null, // legacy
267
+ reduce_funcs : !false_by_default,
260
268
  reduce_vars : !false_by_default,
261
269
  sequences : !false_by_default,
262
270
  side_effects : !false_by_default,
@@ -431,3299 +439,169 @@ class Compressor extends TreeWalker {
431
439
  // thus gives a consistent AST snapshot.
432
440
  descend(node, this);
433
441
  // Existing code relies on how AST_Node.optimize() worked, and omitting the
434
- // following replacement call would result in degraded efficiency of both
435
- // output and performance.
436
- descend(node, this);
437
- var opt = node.optimize(this);
438
- if (was_scope && opt instanceof AST_Scope) {
439
- opt.drop_unused(this);
440
- descend(opt, this);
441
- }
442
- if (opt === node) set_flag(opt, SQUEEZED);
443
- return opt;
444
- }
445
- }
446
-
447
- function def_optimize(node, optimizer) {
448
- node.DEFMETHOD("optimize", function(compressor) {
449
- var self = this;
450
- if (has_flag(self, OPTIMIZED)) return self;
451
- if (compressor.has_directive("use asm")) return self;
452
- var opt = optimizer(self, compressor);
453
- set_flag(opt, OPTIMIZED);
454
- return opt;
455
- });
456
- }
457
-
458
- def_optimize(AST_Node, function(self) {
459
- return self;
460
- });
461
-
462
- AST_Toplevel.DEFMETHOD("drop_console", function() {
463
- return this.transform(new TreeTransformer(function(self) {
464
- if (self.TYPE == "Call") {
465
- var exp = self.expression;
466
- if (exp instanceof AST_PropAccess) {
467
- var name = exp.expression;
468
- while (name.expression) {
469
- name = name.expression;
470
- }
471
- if (is_undeclared_ref(name) && name.name == "console") {
472
- return make_node(AST_Undefined, self);
473
- }
474
- }
475
- }
476
- }));
477
- });
478
-
479
- AST_Node.DEFMETHOD("equivalent_to", function(node) {
480
- return equivalent_to(this, node);
481
- });
482
-
483
- AST_Scope.DEFMETHOD("process_expression", function(insert, compressor) {
484
- var self = this;
485
- var tt = new TreeTransformer(function(node) {
486
- if (insert && node instanceof AST_SimpleStatement) {
487
- return make_node(AST_Return, node, {
488
- value: node.body
489
- });
490
- }
491
- if (!insert && node instanceof AST_Return) {
492
- if (compressor) {
493
- var value = node.value && node.value.drop_side_effect_free(compressor, true);
494
- return value ? make_node(AST_SimpleStatement, node, {
495
- body: value
496
- }) : make_node(AST_EmptyStatement, node);
497
- }
498
- return make_node(AST_SimpleStatement, node, {
499
- body: node.value || make_node(AST_UnaryPrefix, node, {
500
- operator: "void",
501
- expression: make_node(AST_Number, node, {
502
- value: 0
503
- })
504
- })
505
- });
506
- }
507
- if (node instanceof AST_Class || node instanceof AST_Lambda && node !== self) {
508
- return node;
509
- }
510
- if (node instanceof AST_Block) {
511
- var index = node.body.length - 1;
512
- if (index >= 0) {
513
- node.body[index] = node.body[index].transform(tt);
514
- }
515
- } else if (node instanceof AST_If) {
516
- node.body = node.body.transform(tt);
517
- if (node.alternative) {
518
- node.alternative = node.alternative.transform(tt);
519
- }
520
- } else if (node instanceof AST_With) {
521
- node.body = node.body.transform(tt);
522
- }
523
- return node;
524
- });
525
- self.transform(tt);
526
- });
527
-
528
- function read_property(obj, key) {
529
- key = get_value(key);
530
- if (key instanceof AST_Node) return;
531
-
532
- var value;
533
- if (obj instanceof AST_Array) {
534
- var elements = obj.elements;
535
- if (key == "length") return make_node_from_constant(elements.length, obj);
536
- if (typeof key == "number" && key in elements) value = elements[key];
537
- } else if (obj instanceof AST_Object) {
538
- key = "" + key;
539
- var props = obj.properties;
540
- for (var i = props.length; --i >= 0;) {
541
- var prop = props[i];
542
- if (!(prop instanceof AST_ObjectKeyVal)) return;
543
- if (!value && props[i].key === key) value = props[i].value;
544
- }
545
- }
546
-
547
- return value instanceof AST_SymbolRef && value.fixed_value() || value;
548
- }
549
-
550
- function is_modified(compressor, tw, node, value, level, immutable) {
551
- var parent = tw.parent(level);
552
- var lhs = is_lhs(node, parent);
553
- if (lhs) return lhs;
554
- if (!immutable
555
- && parent instanceof AST_Call
556
- && parent.expression === node
557
- && !(value instanceof AST_Arrow)
558
- && !(value instanceof AST_Class)
559
- && !parent.is_expr_pure(compressor)
560
- && (!(value instanceof AST_Function)
561
- || !(parent instanceof AST_New) && value.contains_this())) {
562
- return true;
563
- }
564
- if (parent instanceof AST_Array) {
565
- return is_modified(compressor, tw, parent, parent, level + 1);
566
- }
567
- if (parent instanceof AST_ObjectKeyVal && node === parent.value) {
568
- var obj = tw.parent(level + 1);
569
- return is_modified(compressor, tw, obj, obj, level + 2);
570
- }
571
- if (parent instanceof AST_PropAccess && parent.expression === node) {
572
- var prop = read_property(value, parent.property);
573
- return !immutable && is_modified(compressor, tw, parent, prop, level + 1);
574
- }
575
- }
576
-
577
- (function(def_reduce_vars) {
578
- def_reduce_vars(AST_Node, noop);
579
-
580
- function reset_def(compressor, def) {
581
- def.assignments = 0;
582
- def.chained = false;
583
- def.direct_access = false;
584
- def.escaped = 0;
585
- def.recursive_refs = 0;
586
- def.references = [];
587
- def.single_use = undefined;
588
- if (def.scope.pinned()) {
589
- def.fixed = false;
590
- } else if (def.orig[0] instanceof AST_SymbolConst || !compressor.exposed(def)) {
591
- def.fixed = def.init;
592
- } else {
593
- def.fixed = false;
594
- }
595
- }
596
-
597
- function reset_variables(tw, compressor, node) {
598
- node.variables.forEach(function(def) {
599
- reset_def(compressor, def);
600
- if (def.fixed === null) {
601
- tw.defs_to_safe_ids.set(def.id, tw.safe_ids);
602
- mark(tw, def, true);
603
- } else if (def.fixed) {
604
- tw.loop_ids.set(def.id, tw.in_loop);
605
- mark(tw, def, true);
606
- }
607
- });
608
- }
609
-
610
- function reset_block_variables(compressor, node) {
611
- if (node.block_scope) node.block_scope.variables.forEach((def) => {
612
- reset_def(compressor, def);
613
- });
614
- }
615
-
616
- function push(tw) {
617
- tw.safe_ids = Object.create(tw.safe_ids);
618
- }
619
-
620
- function pop(tw) {
621
- tw.safe_ids = Object.getPrototypeOf(tw.safe_ids);
622
- }
623
-
624
- function mark(tw, def, safe) {
625
- tw.safe_ids[def.id] = safe;
626
- }
627
-
628
- function safe_to_read(tw, def) {
629
- if (def.single_use == "m") return false;
630
- if (tw.safe_ids[def.id]) {
631
- if (def.fixed == null) {
632
- var orig = def.orig[0];
633
- if (orig instanceof AST_SymbolFunarg || orig.name == "arguments") return false;
634
- def.fixed = make_node(AST_Undefined, orig);
635
- }
636
- return true;
637
- }
638
- return def.fixed instanceof AST_Defun;
639
- }
640
-
641
- function safe_to_assign(tw, def, scope, value) {
642
- if (def.fixed === undefined) return true;
643
- let def_safe_ids;
644
- if (def.fixed === null
645
- && (def_safe_ids = tw.defs_to_safe_ids.get(def.id))
646
- ) {
647
- def_safe_ids[def.id] = false;
648
- tw.defs_to_safe_ids.delete(def.id);
649
- return true;
650
- }
651
- if (!HOP(tw.safe_ids, def.id)) return false;
652
- if (!safe_to_read(tw, def)) return false;
653
- if (def.fixed === false) return false;
654
- if (def.fixed != null && (!value || def.references.length > def.assignments)) return false;
655
- if (def.fixed instanceof AST_Defun) {
656
- return value instanceof AST_Node && def.fixed.parent_scope === scope;
657
- }
658
- return def.orig.every((sym) => {
659
- return !(sym instanceof AST_SymbolConst
660
- || sym instanceof AST_SymbolDefun
661
- || sym instanceof AST_SymbolLambda);
662
- });
663
- }
664
-
665
- function ref_once(tw, compressor, def) {
666
- return compressor.option("unused")
667
- && !def.scope.pinned()
668
- && def.references.length - def.recursive_refs == 1
669
- && tw.loop_ids.get(def.id) === tw.in_loop;
670
- }
671
-
672
- function is_immutable(value) {
673
- if (!value) return false;
674
- return value.is_constant()
675
- || value instanceof AST_Lambda
676
- || value instanceof AST_This;
677
- }
678
-
679
- // A definition "escapes" when its value can leave the point of use.
680
- // Example: `a = b || c`
681
- // In this example, "b" and "c" are escaping, because they're going into "a"
682
- //
683
- // def.escaped is != 0 when it escapes.
684
- //
685
- // When greater than 1, it means that N chained properties will be read off
686
- // of that def before an escape occurs. This is useful for evaluating
687
- // property accesses, where you need to know when to stop.
688
- function mark_escaped(tw, d, scope, node, value, level = 0, depth = 1) {
689
- var parent = tw.parent(level);
690
- if (value) {
691
- if (value.is_constant()) return;
692
- if (value instanceof AST_ClassExpression) return;
693
- }
694
-
695
- if (
696
- parent instanceof AST_Assign && (parent.operator === "=" || parent.logical) && node === parent.right
697
- || parent instanceof AST_Call && (node !== parent.expression || parent instanceof AST_New)
698
- || parent instanceof AST_Exit && node === parent.value && node.scope !== d.scope
699
- || parent instanceof AST_VarDef && node === parent.value
700
- || parent instanceof AST_Yield && node === parent.value && node.scope !== d.scope
701
- ) {
702
- if (depth > 1 && !(value && value.is_constant_expression(scope))) depth = 1;
703
- if (!d.escaped || d.escaped > depth) d.escaped = depth;
704
- return;
705
- } else if (
706
- parent instanceof AST_Array
707
- || parent instanceof AST_Await
708
- || parent instanceof AST_Binary && lazy_op.has(parent.operator)
709
- || parent instanceof AST_Conditional && node !== parent.condition
710
- || parent instanceof AST_Expansion
711
- || parent instanceof AST_Sequence && node === parent.tail_node()
712
- ) {
713
- mark_escaped(tw, d, scope, parent, parent, level + 1, depth);
714
- } else if (parent instanceof AST_ObjectKeyVal && node === parent.value) {
715
- var obj = tw.parent(level + 1);
716
-
717
- mark_escaped(tw, d, scope, obj, obj, level + 2, depth);
718
- } else if (parent instanceof AST_PropAccess && node === parent.expression) {
719
- value = read_property(value, parent.property);
720
-
721
- mark_escaped(tw, d, scope, parent, value, level + 1, depth + 1);
722
- if (value) return;
723
- }
724
-
725
- if (level > 0) return;
726
- if (parent instanceof AST_Sequence && node !== parent.tail_node()) return;
727
- if (parent instanceof AST_SimpleStatement) return;
728
-
729
- d.direct_access = true;
730
- }
731
-
732
- const suppress = node => walk(node, node => {
733
- if (!(node instanceof AST_Symbol)) return;
734
- var d = node.definition();
735
- if (!d) return;
736
- if (node instanceof AST_SymbolRef) d.references.push(node);
737
- d.fixed = false;
738
- });
739
- def_reduce_vars(AST_Accessor, function(tw, descend, compressor) {
740
- push(tw);
741
- reset_variables(tw, compressor, this);
742
- descend();
743
- pop(tw);
744
- return true;
745
- });
746
- def_reduce_vars(AST_Assign, function(tw, descend, compressor) {
747
- var node = this;
748
- if (node.left instanceof AST_Destructuring) {
749
- suppress(node.left);
750
- return;
751
- }
752
-
753
- const finish_walk = () => {
754
- if (node.logical) {
755
- node.left.walk(tw);
756
-
757
- push(tw);
758
- node.right.walk(tw);
759
- pop(tw);
760
-
761
- return true;
762
- }
763
- };
764
-
765
- var sym = node.left;
766
- if (!(sym instanceof AST_SymbolRef)) return finish_walk();
767
-
768
- var def = sym.definition();
769
- var safe = safe_to_assign(tw, def, sym.scope, node.right);
770
- def.assignments++;
771
- if (!safe) return finish_walk();
772
-
773
- var fixed = def.fixed;
774
- if (!fixed && node.operator != "=" && !node.logical) return finish_walk();
775
-
776
- var eq = node.operator == "=";
777
- var value = eq ? node.right : node;
778
- if (is_modified(compressor, tw, node, value, 0)) return finish_walk();
779
-
780
- def.references.push(sym);
781
-
782
- if (!node.logical) {
783
- if (!eq) def.chained = true;
784
-
785
- def.fixed = eq ? function() {
786
- return node.right;
787
- } : function() {
788
- return make_node(AST_Binary, node, {
789
- operator: node.operator.slice(0, -1),
790
- left: fixed instanceof AST_Node ? fixed : fixed(),
791
- right: node.right
792
- });
793
- };
794
- }
795
-
796
- if (node.logical) {
797
- mark(tw, def, false);
798
- push(tw);
799
- node.right.walk(tw);
800
- pop(tw);
801
- return true;
802
- }
803
-
804
- mark(tw, def, false);
805
- node.right.walk(tw);
806
- mark(tw, def, true);
807
-
808
- mark_escaped(tw, def, sym.scope, node, value, 0, 1);
809
-
810
- return true;
811
- });
812
- def_reduce_vars(AST_Binary, function(tw) {
813
- if (!lazy_op.has(this.operator)) return;
814
- this.left.walk(tw);
815
- push(tw);
816
- this.right.walk(tw);
817
- pop(tw);
818
- return true;
819
- });
820
- def_reduce_vars(AST_Block, function(tw, descend, compressor) {
821
- reset_block_variables(compressor, this);
822
- });
823
- def_reduce_vars(AST_Case, function(tw) {
824
- push(tw);
825
- this.expression.walk(tw);
826
- pop(tw);
827
- push(tw);
828
- walk_body(this, tw);
829
- pop(tw);
830
- return true;
831
- });
832
- def_reduce_vars(AST_Class, function(tw, descend) {
833
- clear_flag(this, INLINED);
834
- push(tw);
835
- descend();
836
- pop(tw);
837
- return true;
838
- });
839
- def_reduce_vars(AST_Conditional, function(tw) {
840
- this.condition.walk(tw);
841
- push(tw);
842
- this.consequent.walk(tw);
843
- pop(tw);
844
- push(tw);
845
- this.alternative.walk(tw);
846
- pop(tw);
847
- return true;
848
- });
849
-
850
- def_reduce_vars(AST_Chain, function(tw, descend) {
851
- // Chains' conditions apply left-to-right, cumulatively.
852
- // If we walk normally we don't go in that order because we would pop before pushing again
853
- // Solution: AST_PropAccess and AST_Call push when they are optional, and never pop.
854
- // Then we pop everything when they are done being walked.
855
- const safe_ids = tw.safe_ids;
856
-
857
- descend();
858
-
859
- // Unroll back to start
860
- tw.safe_ids = safe_ids;
861
- return true;
862
- });
863
- def_reduce_vars(AST_Call, function (tw) {
864
- // TODO this block should just be { return } but
865
- // for some reason the _walk function of AST_Call walks the callee last
866
-
867
- this.expression.walk(tw);
868
-
869
- if (this.optional) {
870
- // Never pop -- it's popped at AST_Chain above
871
- push(tw);
872
- }
873
-
874
- for (const arg of this.args) arg.walk(tw);
875
-
876
- return true;
877
- });
878
- def_reduce_vars(AST_PropAccess, function (tw) {
879
- if (!this.optional) return;
880
-
881
- this.expression.walk(tw);
882
-
883
- // Never pop -- it's popped at AST_Chain above
884
- push(tw);
885
-
886
- if (this.property instanceof AST_Node) this.property.walk(tw);
887
-
888
- return true;
889
- });
890
- def_reduce_vars(AST_Default, function(tw, descend) {
891
- push(tw);
892
- descend();
893
- pop(tw);
894
- return true;
895
- });
896
- function mark_lambda(tw, descend, compressor) {
897
- clear_flag(this, INLINED);
898
- push(tw);
899
- reset_variables(tw, compressor, this);
900
- if (this.uses_arguments) {
901
- descend();
902
- pop(tw);
903
- return;
904
- }
905
- var iife;
906
- if (!this.name
907
- && (iife = tw.parent()) instanceof AST_Call
908
- && iife.expression === this
909
- && !iife.args.some(arg => arg instanceof AST_Expansion)
910
- && this.argnames.every(arg_name => arg_name instanceof AST_Symbol)
911
- ) {
912
- // Virtually turn IIFE parameters into variable definitions:
913
- // (function(a,b) {...})(c,d) => (function() {var a=c,b=d; ...})()
914
- // So existing transformation rules can work on them.
915
- this.argnames.forEach((arg, i) => {
916
- if (!arg.definition) return;
917
- var d = arg.definition();
918
- // Avoid setting fixed when there's more than one origin for a variable value
919
- if (d.orig.length > 1) return;
920
- if (d.fixed === undefined && (!this.uses_arguments || tw.has_directive("use strict"))) {
921
- d.fixed = function() {
922
- return iife.args[i] || make_node(AST_Undefined, iife);
923
- };
924
- tw.loop_ids.set(d.id, tw.in_loop);
925
- mark(tw, d, true);
926
- } else {
927
- d.fixed = false;
928
- }
929
- });
930
- }
931
- descend();
932
- pop(tw);
933
- return true;
934
- }
935
-
936
- def_reduce_vars(AST_Lambda, mark_lambda);
937
-
938
- def_reduce_vars(AST_Do, function(tw, descend, compressor) {
939
- reset_block_variables(compressor, this);
940
- const saved_loop = tw.in_loop;
941
- tw.in_loop = this;
942
- push(tw);
943
- this.body.walk(tw);
944
- if (has_break_or_continue(this)) {
945
- pop(tw);
946
- push(tw);
947
- }
948
- this.condition.walk(tw);
949
- pop(tw);
950
- tw.in_loop = saved_loop;
951
- return true;
952
- });
953
- def_reduce_vars(AST_For, function(tw, descend, compressor) {
954
- reset_block_variables(compressor, this);
955
- if (this.init) this.init.walk(tw);
956
- const saved_loop = tw.in_loop;
957
- tw.in_loop = this;
958
- push(tw);
959
- if (this.condition) this.condition.walk(tw);
960
- this.body.walk(tw);
961
- if (this.step) {
962
- if (has_break_or_continue(this)) {
963
- pop(tw);
964
- push(tw);
965
- }
966
- this.step.walk(tw);
967
- }
968
- pop(tw);
969
- tw.in_loop = saved_loop;
970
- return true;
971
- });
972
- def_reduce_vars(AST_ForIn, function(tw, descend, compressor) {
973
- reset_block_variables(compressor, this);
974
- suppress(this.init);
975
- this.object.walk(tw);
976
- const saved_loop = tw.in_loop;
977
- tw.in_loop = this;
978
- push(tw);
979
- this.body.walk(tw);
980
- pop(tw);
981
- tw.in_loop = saved_loop;
982
- return true;
983
- });
984
-
985
- def_reduce_vars(AST_If, function(tw) {
986
- this.condition.walk(tw);
987
- push(tw);
988
- this.body.walk(tw);
989
- pop(tw);
990
- if (this.alternative) {
991
- push(tw);
992
- this.alternative.walk(tw);
993
- pop(tw);
994
- }
995
- return true;
996
- });
997
- def_reduce_vars(AST_LabeledStatement, function(tw) {
998
- push(tw);
999
- this.body.walk(tw);
1000
- pop(tw);
1001
- return true;
1002
- });
1003
- def_reduce_vars(AST_SymbolCatch, function() {
1004
- this.definition().fixed = false;
1005
- });
1006
-
1007
- def_reduce_vars(AST_SymbolRef, function(tw, descend, compressor) {
1008
- var d = this.definition();
1009
- d.references.push(this);
1010
- if (d.references.length == 1
1011
- && !d.fixed
1012
- && d.orig[0] instanceof AST_SymbolDefun) {
1013
- tw.loop_ids.set(d.id, tw.in_loop);
1014
- }
1015
- var fixed_value;
1016
- if (d.fixed === undefined || !safe_to_read(tw, d)) {
1017
- d.fixed = false;
1018
- } else if (d.fixed) {
1019
- fixed_value = this.fixed_value();
1020
- if (
1021
- fixed_value instanceof AST_Lambda
1022
- && recursive_ref(tw, d)
1023
- ) {
1024
- d.recursive_refs++;
1025
- } else if (fixed_value
1026
- && !compressor.exposed(d)
1027
- && ref_once(tw, compressor, d)
1028
- ) {
1029
- d.single_use =
1030
- fixed_value instanceof AST_Lambda && !fixed_value.pinned()
1031
- || fixed_value instanceof AST_Class
1032
- || d.scope === this.scope && fixed_value.is_constant_expression();
1033
- } else {
1034
- d.single_use = false;
1035
- }
1036
- if (is_modified(compressor, tw, this, fixed_value, 0, is_immutable(fixed_value))) {
1037
- if (d.single_use) {
1038
- d.single_use = "m";
1039
- } else {
1040
- d.fixed = false;
1041
- }
1042
- }
1043
- }
1044
- mark_escaped(tw, d, this.scope, this, fixed_value, 0, 1);
1045
- });
1046
- def_reduce_vars(AST_Toplevel, function(tw, descend, compressor) {
1047
- this.globals.forEach(function(def) {
1048
- reset_def(compressor, def);
1049
- });
1050
- reset_variables(tw, compressor, this);
1051
- });
1052
- def_reduce_vars(AST_Try, function(tw, descend, compressor) {
1053
- reset_block_variables(compressor, this);
1054
- push(tw);
1055
- walk_body(this, tw);
1056
- pop(tw);
1057
- if (this.bcatch) {
1058
- push(tw);
1059
- this.bcatch.walk(tw);
1060
- pop(tw);
1061
- }
1062
- if (this.bfinally) this.bfinally.walk(tw);
1063
- return true;
1064
- });
1065
- def_reduce_vars(AST_Unary, function(tw) {
1066
- var node = this;
1067
- if (node.operator !== "++" && node.operator !== "--") return;
1068
- var exp = node.expression;
1069
- if (!(exp instanceof AST_SymbolRef)) return;
1070
- var def = exp.definition();
1071
- var safe = safe_to_assign(tw, def, exp.scope, true);
1072
- def.assignments++;
1073
- if (!safe) return;
1074
- var fixed = def.fixed;
1075
- if (!fixed) return;
1076
- def.references.push(exp);
1077
- def.chained = true;
1078
- def.fixed = function() {
1079
- return make_node(AST_Binary, node, {
1080
- operator: node.operator.slice(0, -1),
1081
- left: make_node(AST_UnaryPrefix, node, {
1082
- operator: "+",
1083
- expression: fixed instanceof AST_Node ? fixed : fixed()
1084
- }),
1085
- right: make_node(AST_Number, node, {
1086
- value: 1
1087
- })
1088
- });
1089
- };
1090
- mark(tw, def, true);
1091
- return true;
1092
- });
1093
- def_reduce_vars(AST_VarDef, function(tw, descend) {
1094
- var node = this;
1095
- if (node.name instanceof AST_Destructuring) {
1096
- suppress(node.name);
1097
- return;
1098
- }
1099
- var d = node.name.definition();
1100
- if (node.value) {
1101
- if (safe_to_assign(tw, d, node.name.scope, node.value)) {
1102
- d.fixed = function() {
1103
- return node.value;
1104
- };
1105
- tw.loop_ids.set(d.id, tw.in_loop);
1106
- mark(tw, d, false);
1107
- descend();
1108
- mark(tw, d, true);
1109
- return true;
1110
- } else {
1111
- d.fixed = false;
1112
- }
1113
- }
1114
- });
1115
- def_reduce_vars(AST_While, function(tw, descend, compressor) {
1116
- reset_block_variables(compressor, this);
1117
- const saved_loop = tw.in_loop;
1118
- tw.in_loop = this;
1119
- push(tw);
1120
- descend();
1121
- pop(tw);
1122
- tw.in_loop = saved_loop;
1123
- return true;
1124
- });
1125
- })(function(node, func) {
1126
- node.DEFMETHOD("reduce_vars", func);
1127
- });
1128
-
1129
- AST_Toplevel.DEFMETHOD("reset_opt_flags", function(compressor) {
1130
- const self = this;
1131
- const reduce_vars = compressor.option("reduce_vars");
1132
-
1133
- const preparation = new TreeWalker(function(node, descend) {
1134
- clear_flag(node, CLEAR_BETWEEN_PASSES);
1135
- if (reduce_vars) {
1136
- if (compressor.top_retain
1137
- && node instanceof AST_Defun // Only functions are retained
1138
- && preparation.parent() === self
1139
- ) {
1140
- set_flag(node, TOP);
1141
- }
1142
- return node.reduce_vars(preparation, descend, compressor);
1143
- }
1144
- });
1145
- // Stack of look-up tables to keep track of whether a `SymbolDef` has been
1146
- // properly assigned before use:
1147
- // - `push()` & `pop()` when visiting conditional branches
1148
- preparation.safe_ids = Object.create(null);
1149
- preparation.in_loop = null;
1150
- preparation.loop_ids = new Map();
1151
- preparation.defs_to_safe_ids = new Map();
1152
- self.walk(preparation);
1153
- });
1154
-
1155
- AST_Symbol.DEFMETHOD("fixed_value", function() {
1156
- var fixed = this.thedef.fixed;
1157
- if (!fixed || fixed instanceof AST_Node) return fixed;
1158
- return fixed();
1159
- });
1160
-
1161
- AST_SymbolRef.DEFMETHOD("is_immutable", function() {
1162
- var orig = this.definition().orig;
1163
- return orig.length == 1 && orig[0] instanceof AST_SymbolLambda;
1164
- });
1165
-
1166
- function is_func_expr(node) {
1167
- return node instanceof AST_Arrow || node instanceof AST_Function;
1168
- }
1169
-
1170
- function is_lhs_read_only(lhs) {
1171
- if (lhs instanceof AST_This) return true;
1172
- if (lhs instanceof AST_SymbolRef) return lhs.definition().orig[0] instanceof AST_SymbolLambda;
1173
- if (lhs instanceof AST_PropAccess) {
1174
- lhs = lhs.expression;
1175
- if (lhs instanceof AST_SymbolRef) {
1176
- if (lhs.is_immutable()) return false;
1177
- lhs = lhs.fixed_value();
1178
- }
1179
- if (!lhs) return true;
1180
- if (lhs instanceof AST_RegExp) return false;
1181
- if (lhs instanceof AST_Constant) return true;
1182
- return is_lhs_read_only(lhs);
1183
- }
1184
- return false;
1185
- }
1186
-
1187
- function is_ref_of(ref, type) {
1188
- if (!(ref instanceof AST_SymbolRef)) return false;
1189
- var orig = ref.definition().orig;
1190
- for (var i = orig.length; --i >= 0;) {
1191
- if (orig[i] instanceof type) return true;
1192
- }
1193
- }
1194
-
1195
- function find_scope(tw) {
1196
- for (let i = 0;;i++) {
1197
- const p = tw.parent(i);
1198
- if (p instanceof AST_Toplevel) return p;
1199
- if (p instanceof AST_Lambda) return p;
1200
- if (p.block_scope) return p.block_scope;
1201
- }
1202
- }
1203
-
1204
- function find_variable(compressor, name) {
1205
- var scope, i = 0;
1206
- while (scope = compressor.parent(i++)) {
1207
- if (scope instanceof AST_Scope) break;
1208
- if (scope instanceof AST_Catch && scope.argname) {
1209
- scope = scope.argname.definition().scope;
1210
- break;
1211
- }
1212
- }
1213
- return scope.find_variable(name);
1214
- }
1215
-
1216
- function make_sequence(orig, expressions) {
1217
- if (expressions.length == 1) return expressions[0];
1218
- if (expressions.length == 0) throw new Error("trying to create a sequence with length zero!");
1219
- return make_node(AST_Sequence, orig, {
1220
- expressions: expressions.reduce(merge_sequence, [])
1221
- });
1222
- }
1223
-
1224
- function make_node_from_constant(val, orig) {
1225
- switch (typeof val) {
1226
- case "string":
1227
- return make_node(AST_String, orig, {
1228
- value: val
1229
- });
1230
- case "number":
1231
- if (isNaN(val)) return make_node(AST_NaN, orig);
1232
- if (isFinite(val)) {
1233
- return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, {
1234
- operator: "-",
1235
- expression: make_node(AST_Number, orig, { value: -val })
1236
- }) : make_node(AST_Number, orig, { value: val });
1237
- }
1238
- return val < 0 ? make_node(AST_UnaryPrefix, orig, {
1239
- operator: "-",
1240
- expression: make_node(AST_Infinity, orig)
1241
- }) : make_node(AST_Infinity, orig);
1242
- case "boolean":
1243
- return make_node(val ? AST_True : AST_False, orig);
1244
- case "undefined":
1245
- return make_node(AST_Undefined, orig);
1246
- default:
1247
- if (val === null) {
1248
- return make_node(AST_Null, orig, { value: null });
1249
- }
1250
- if (val instanceof RegExp) {
1251
- return make_node(AST_RegExp, orig, {
1252
- value: {
1253
- source: regexp_source_fix(val.source),
1254
- flags: val.flags
1255
- }
1256
- });
1257
- }
1258
- throw new Error(string_template("Can't handle constant of type: {type}", {
1259
- type: typeof val
1260
- }));
1261
- }
1262
- }
1263
-
1264
- // we shouldn't compress (1,func)(something) to
1265
- // func(something) because that changes the meaning of
1266
- // the func (becomes lexical instead of global).
1267
- function maintain_this_binding(parent, orig, val) {
1268
- if (parent instanceof AST_UnaryPrefix && parent.operator == "delete"
1269
- || parent instanceof AST_Call && parent.expression === orig
1270
- && (val instanceof AST_PropAccess || val instanceof AST_SymbolRef && val.name == "eval")) {
1271
- return make_sequence(orig, [ make_node(AST_Number, orig, { value: 0 }), val ]);
1272
- }
1273
- return val;
1274
- }
1275
-
1276
- function merge_sequence(array, node) {
1277
- if (node instanceof AST_Sequence) {
1278
- array.push(...node.expressions);
1279
- } else {
1280
- array.push(node);
1281
- }
1282
- return array;
1283
- }
1284
-
1285
- function as_statement_array(thing) {
1286
- if (thing === null) return [];
1287
- if (thing instanceof AST_BlockStatement) return thing.body;
1288
- if (thing instanceof AST_EmptyStatement) return [];
1289
- if (thing instanceof AST_Statement) return [ thing ];
1290
- throw new Error("Can't convert thing to statement array");
1291
- }
1292
-
1293
- function is_empty(thing) {
1294
- if (thing === null) return true;
1295
- if (thing instanceof AST_EmptyStatement) return true;
1296
- if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
1297
- return false;
1298
- }
1299
-
1300
- function can_be_evicted_from_block(node) {
1301
- return !(
1302
- node instanceof AST_DefClass ||
1303
- node instanceof AST_Defun ||
1304
- node instanceof AST_Let ||
1305
- node instanceof AST_Const ||
1306
- node instanceof AST_Export ||
1307
- node instanceof AST_Import
1308
- );
1309
- }
1310
-
1311
- function loop_body(x) {
1312
- if (x instanceof AST_IterationStatement) {
1313
- return x.body instanceof AST_BlockStatement ? x.body : x;
1314
- }
1315
- return x;
1316
- }
1317
-
1318
- function is_iife_call(node) {
1319
- // Used to determine whether the node can benefit from negation.
1320
- // Not the case with arrow functions (you need an extra set of parens).
1321
- if (node.TYPE != "Call") return false;
1322
- return node.expression instanceof AST_Function || is_iife_call(node.expression);
1323
- }
1324
-
1325
- function is_undeclared_ref(node) {
1326
- return node instanceof AST_SymbolRef && node.definition().undeclared;
1327
- }
1328
-
1329
- var global_names = makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");
1330
- AST_SymbolRef.DEFMETHOD("is_declared", function(compressor) {
1331
- return !this.definition().undeclared
1332
- || compressor.option("unsafe") && global_names.has(this.name);
1333
- });
1334
-
1335
- var identifier_atom = makePredicate("Infinity NaN undefined");
1336
- function is_identifier_atom(node) {
1337
- return node instanceof AST_Infinity
1338
- || node instanceof AST_NaN
1339
- || node instanceof AST_Undefined;
1340
- }
1341
-
1342
- // Tighten a bunch of statements together. Used whenever there is a block.
1343
- function tighten_body(statements, compressor) {
1344
- var in_loop, in_try;
1345
- var scope = compressor.find_parent(AST_Scope).get_defun_scope();
1346
- find_loop_scope_try();
1347
- var CHANGED, max_iter = 10;
1348
- do {
1349
- CHANGED = false;
1350
- eliminate_spurious_blocks(statements);
1351
- if (compressor.option("dead_code")) {
1352
- eliminate_dead_code(statements, compressor);
1353
- }
1354
- if (compressor.option("if_return")) {
1355
- handle_if_return(statements, compressor);
1356
- }
1357
- if (compressor.sequences_limit > 0) {
1358
- sequencesize(statements, compressor);
1359
- sequencesize_2(statements, compressor);
1360
- }
1361
- if (compressor.option("join_vars")) {
1362
- join_consecutive_vars(statements);
1363
- }
1364
- if (compressor.option("collapse_vars")) {
1365
- collapse(statements, compressor);
1366
- }
1367
- } while (CHANGED && max_iter-- > 0);
1368
-
1369
- function find_loop_scope_try() {
1370
- var node = compressor.self(), level = 0;
1371
- do {
1372
- if (node instanceof AST_Catch || node instanceof AST_Finally) {
1373
- level++;
1374
- } else if (node instanceof AST_IterationStatement) {
1375
- in_loop = true;
1376
- } else if (node instanceof AST_Scope) {
1377
- scope = node;
1378
- break;
1379
- } else if (node instanceof AST_Try) {
1380
- in_try = true;
1381
- }
1382
- } while (node = compressor.parent(level++));
1383
- }
1384
-
1385
- // Search from right to left for assignment-like expressions:
1386
- // - `var a = x;`
1387
- // - `a = x;`
1388
- // - `++a`
1389
- // For each candidate, scan from left to right for first usage, then try
1390
- // to fold assignment into the site for compression.
1391
- // Will not attempt to collapse assignments into or past code blocks
1392
- // which are not sequentially executed, e.g. loops and conditionals.
1393
- function collapse(statements, compressor) {
1394
- if (scope.pinned()) return statements;
1395
- var args;
1396
- var candidates = [];
1397
- var stat_index = statements.length;
1398
- var scanner = new TreeTransformer(function(node) {
1399
- if (abort) return node;
1400
- // Skip nodes before `candidate` as quickly as possible
1401
- if (!hit) {
1402
- if (node !== hit_stack[hit_index]) return node;
1403
- hit_index++;
1404
- if (hit_index < hit_stack.length) return handle_custom_scan_order(node);
1405
- hit = true;
1406
- stop_after = find_stop(node, 0);
1407
- if (stop_after === node) abort = true;
1408
- return node;
1409
- }
1410
- // Stop immediately if these node types are encountered
1411
- var parent = scanner.parent();
1412
- if (node instanceof AST_Assign
1413
- && (node.logical || node.operator != "=" && lhs.equivalent_to(node.left))
1414
- || node instanceof AST_Await
1415
- || node instanceof AST_Call && lhs instanceof AST_PropAccess && lhs.equivalent_to(node.expression)
1416
- || node instanceof AST_Debugger
1417
- || node instanceof AST_Destructuring
1418
- || node instanceof AST_Expansion
1419
- && node.expression instanceof AST_Symbol
1420
- && node.expression.definition().references.length > 1
1421
- || node instanceof AST_IterationStatement && !(node instanceof AST_For)
1422
- || node instanceof AST_LoopControl
1423
- || node instanceof AST_Try
1424
- || node instanceof AST_With
1425
- || node instanceof AST_Yield
1426
- || node instanceof AST_Export
1427
- || node instanceof AST_Class
1428
- || parent instanceof AST_For && node !== parent.init
1429
- || !replace_all
1430
- && (
1431
- node instanceof AST_SymbolRef
1432
- && !node.is_declared(compressor)
1433
- && !pure_prop_access_globals.has(node))
1434
- || node instanceof AST_SymbolRef
1435
- && parent instanceof AST_Call
1436
- && has_annotation(parent, _NOINLINE)
1437
- ) {
1438
- abort = true;
1439
- return node;
1440
- }
1441
- // Stop only if candidate is found within conditional branches
1442
- if (!stop_if_hit && (!lhs_local || !replace_all)
1443
- && (parent instanceof AST_Binary && lazy_op.has(parent.operator) && parent.left !== node
1444
- || parent instanceof AST_Conditional && parent.condition !== node
1445
- || parent instanceof AST_If && parent.condition !== node)) {
1446
- stop_if_hit = parent;
1447
- }
1448
- // Replace variable with assignment when found
1449
- if (can_replace
1450
- && !(node instanceof AST_SymbolDeclaration)
1451
- && lhs.equivalent_to(node)
1452
- ) {
1453
- if (stop_if_hit) {
1454
- abort = true;
1455
- return node;
1456
- }
1457
- if (is_lhs(node, parent)) {
1458
- if (value_def) replaced++;
1459
- return node;
1460
- } else {
1461
- replaced++;
1462
- if (value_def && candidate instanceof AST_VarDef) return node;
1463
- }
1464
- CHANGED = abort = true;
1465
- if (candidate instanceof AST_UnaryPostfix) {
1466
- return make_node(AST_UnaryPrefix, candidate, candidate);
1467
- }
1468
- if (candidate instanceof AST_VarDef) {
1469
- var def = candidate.name.definition();
1470
- var value = candidate.value;
1471
- if (def.references.length - def.replaced == 1 && !compressor.exposed(def)) {
1472
- def.replaced++;
1473
- if (funarg && is_identifier_atom(value)) {
1474
- return value.transform(compressor);
1475
- } else {
1476
- return maintain_this_binding(parent, node, value);
1477
- }
1478
- }
1479
- return make_node(AST_Assign, candidate, {
1480
- operator: "=",
1481
- logical: false,
1482
- left: make_node(AST_SymbolRef, candidate.name, candidate.name),
1483
- right: value
1484
- });
1485
- }
1486
- clear_flag(candidate, WRITE_ONLY);
1487
- return candidate;
1488
- }
1489
- // These node types have child nodes that execute sequentially,
1490
- // but are otherwise not safe to scan into or beyond them.
1491
- var sym;
1492
- if (node instanceof AST_Call
1493
- || node instanceof AST_Exit
1494
- && (side_effects || lhs instanceof AST_PropAccess || may_modify(lhs))
1495
- || node instanceof AST_PropAccess
1496
- && (side_effects || node.expression.may_throw_on_access(compressor))
1497
- || node instanceof AST_SymbolRef
1498
- && (lvalues.get(node.name) || side_effects && may_modify(node))
1499
- || node instanceof AST_VarDef && node.value
1500
- && (lvalues.has(node.name.name) || side_effects && may_modify(node.name))
1501
- || (sym = is_lhs(node.left, node))
1502
- && (sym instanceof AST_PropAccess || lvalues.has(sym.name))
1503
- || may_throw
1504
- && (in_try ? node.has_side_effects(compressor) : side_effects_external(node))) {
1505
- stop_after = node;
1506
- if (node instanceof AST_Scope) abort = true;
1507
- }
1508
- return handle_custom_scan_order(node);
1509
- }, function(node) {
1510
- if (abort) return;
1511
- if (stop_after === node) abort = true;
1512
- if (stop_if_hit === node) stop_if_hit = null;
1513
- });
1514
- var multi_replacer = new TreeTransformer(function(node) {
1515
- if (abort) return node;
1516
- // Skip nodes before `candidate` as quickly as possible
1517
- if (!hit) {
1518
- if (node !== hit_stack[hit_index]) return node;
1519
- hit_index++;
1520
- if (hit_index < hit_stack.length) return;
1521
- hit = true;
1522
- return node;
1523
- }
1524
- // Replace variable when found
1525
- if (node instanceof AST_SymbolRef
1526
- && node.name == def.name) {
1527
- if (!--replaced) abort = true;
1528
- if (is_lhs(node, multi_replacer.parent())) return node;
1529
- def.replaced++;
1530
- value_def.replaced--;
1531
- return candidate.value;
1532
- }
1533
- // Skip (non-executed) functions and (leading) default case in switch statements
1534
- if (node instanceof AST_Default || node instanceof AST_Scope) return node;
1535
- });
1536
- while (--stat_index >= 0) {
1537
- // Treat parameters as collapsible in IIFE, i.e.
1538
- // function(a, b){ ... }(x());
1539
- // would be translated into equivalent assignments:
1540
- // var a = x(), b = undefined;
1541
- if (stat_index == 0 && compressor.option("unused")) extract_args();
1542
- // Find collapsible assignments
1543
- var hit_stack = [];
1544
- extract_candidates(statements[stat_index]);
1545
- while (candidates.length > 0) {
1546
- hit_stack = candidates.pop();
1547
- var hit_index = 0;
1548
- var candidate = hit_stack[hit_stack.length - 1];
1549
- var value_def = null;
1550
- var stop_after = null;
1551
- var stop_if_hit = null;
1552
- var lhs = get_lhs(candidate);
1553
- if (!lhs || is_lhs_read_only(lhs) || lhs.has_side_effects(compressor)) continue;
1554
- // Locate symbols which may execute code outside of scanning range
1555
- var lvalues = get_lvalues(candidate);
1556
- var lhs_local = is_lhs_local(lhs);
1557
- if (lhs instanceof AST_SymbolRef) lvalues.set(lhs.name, false);
1558
- var side_effects = value_has_side_effects(candidate);
1559
- var replace_all = replace_all_symbols();
1560
- var may_throw = candidate.may_throw(compressor);
1561
- var funarg = candidate.name instanceof AST_SymbolFunarg;
1562
- var hit = funarg;
1563
- var abort = false, replaced = 0, can_replace = !args || !hit;
1564
- if (!can_replace) {
1565
- for (var j = compressor.self().argnames.lastIndexOf(candidate.name) + 1; !abort && j < args.length; j++) {
1566
- args[j].transform(scanner);
1567
- }
1568
- can_replace = true;
1569
- }
1570
- for (var i = stat_index; !abort && i < statements.length; i++) {
1571
- statements[i].transform(scanner);
1572
- }
1573
- if (value_def) {
1574
- var def = candidate.name.definition();
1575
- if (abort && def.references.length - def.replaced > replaced) replaced = false;
1576
- else {
1577
- abort = false;
1578
- hit_index = 0;
1579
- hit = funarg;
1580
- for (var i = stat_index; !abort && i < statements.length; i++) {
1581
- statements[i].transform(multi_replacer);
1582
- }
1583
- value_def.single_use = false;
1584
- }
1585
- }
1586
- if (replaced && !remove_candidate(candidate)) statements.splice(stat_index, 1);
1587
- }
1588
- }
1589
-
1590
- function handle_custom_scan_order(node) {
1591
- // Skip (non-executed) functions
1592
- if (node instanceof AST_Scope) return node;
1593
-
1594
- // Scan case expressions first in a switch statement
1595
- if (node instanceof AST_Switch) {
1596
- node.expression = node.expression.transform(scanner);
1597
- for (var i = 0, len = node.body.length; !abort && i < len; i++) {
1598
- var branch = node.body[i];
1599
- if (branch instanceof AST_Case) {
1600
- if (!hit) {
1601
- if (branch !== hit_stack[hit_index]) continue;
1602
- hit_index++;
1603
- }
1604
- branch.expression = branch.expression.transform(scanner);
1605
- if (!replace_all) break;
1606
- }
1607
- }
1608
- abort = true;
1609
- return node;
1610
- }
1611
- }
1612
-
1613
- function redefined_within_scope(def, scope) {
1614
- if (def.global) return false;
1615
- let cur_scope = def.scope;
1616
- while (cur_scope && cur_scope !== scope) {
1617
- if (cur_scope.variables.has(def.name)) return true;
1618
- cur_scope = cur_scope.parent_scope;
1619
- }
1620
- return false;
1621
- }
1622
-
1623
- function has_overlapping_symbol(fn, arg, fn_strict) {
1624
- var found = false, scan_this = !(fn instanceof AST_Arrow);
1625
- arg.walk(new TreeWalker(function(node, descend) {
1626
- if (found) return true;
1627
- if (node instanceof AST_SymbolRef && (fn.variables.has(node.name) || redefined_within_scope(node.definition(), fn))) {
1628
- var s = node.definition().scope;
1629
- if (s !== scope) while (s = s.parent_scope) {
1630
- if (s === scope) return true;
1631
- }
1632
- return found = true;
1633
- }
1634
- if ((fn_strict || scan_this) && node instanceof AST_This) {
1635
- return found = true;
1636
- }
1637
- if (node instanceof AST_Scope && !(node instanceof AST_Arrow)) {
1638
- var prev = scan_this;
1639
- scan_this = false;
1640
- descend();
1641
- scan_this = prev;
1642
- return true;
1643
- }
1644
- }));
1645
- return found;
1646
- }
1647
-
1648
- function extract_args() {
1649
- var iife, fn = compressor.self();
1650
- if (is_func_expr(fn)
1651
- && !fn.name
1652
- && !fn.uses_arguments
1653
- && !fn.pinned()
1654
- && (iife = compressor.parent()) instanceof AST_Call
1655
- && iife.expression === fn
1656
- && iife.args.every((arg) => !(arg instanceof AST_Expansion))
1657
- ) {
1658
- var fn_strict = compressor.has_directive("use strict");
1659
- if (fn_strict && !member(fn_strict, fn.body)) fn_strict = false;
1660
- var len = fn.argnames.length;
1661
- args = iife.args.slice(len);
1662
- var names = new Set();
1663
- for (var i = len; --i >= 0;) {
1664
- var sym = fn.argnames[i];
1665
- var arg = iife.args[i];
1666
- // The following two line fix is a duplicate of the fix at
1667
- // https://github.com/terser/terser/commit/011d3eb08cefe6922c7d1bdfa113fc4aeaca1b75
1668
- // This might mean that these two pieces of code (one here in collapse_vars and another in reduce_vars
1669
- // Might be doing the exact same thing.
1670
- const def = sym.definition && sym.definition();
1671
- const is_reassigned = def && def.orig.length > 1;
1672
- if (is_reassigned) continue;
1673
- args.unshift(make_node(AST_VarDef, sym, {
1674
- name: sym,
1675
- value: arg
1676
- }));
1677
- if (names.has(sym.name)) continue;
1678
- names.add(sym.name);
1679
- if (sym instanceof AST_Expansion) {
1680
- var elements = iife.args.slice(i);
1681
- if (elements.every((arg) =>
1682
- !has_overlapping_symbol(fn, arg, fn_strict)
1683
- )) {
1684
- candidates.unshift([ make_node(AST_VarDef, sym, {
1685
- name: sym.expression,
1686
- value: make_node(AST_Array, iife, {
1687
- elements: elements
1688
- })
1689
- }) ]);
1690
- }
1691
- } else {
1692
- if (!arg) {
1693
- arg = make_node(AST_Undefined, sym).transform(compressor);
1694
- } else if (arg instanceof AST_Lambda && arg.pinned()
1695
- || has_overlapping_symbol(fn, arg, fn_strict)
1696
- ) {
1697
- arg = null;
1698
- }
1699
- if (arg) candidates.unshift([ make_node(AST_VarDef, sym, {
1700
- name: sym,
1701
- value: arg
1702
- }) ]);
1703
- }
1704
- }
1705
- }
1706
- }
1707
-
1708
- function extract_candidates(expr) {
1709
- hit_stack.push(expr);
1710
- if (expr instanceof AST_Assign) {
1711
- if (!expr.left.has_side_effects(compressor)) {
1712
- candidates.push(hit_stack.slice());
1713
- }
1714
- extract_candidates(expr.right);
1715
- } else if (expr instanceof AST_Binary) {
1716
- extract_candidates(expr.left);
1717
- extract_candidates(expr.right);
1718
- } else if (expr instanceof AST_Call && !has_annotation(expr, _NOINLINE)) {
1719
- extract_candidates(expr.expression);
1720
- expr.args.forEach(extract_candidates);
1721
- } else if (expr instanceof AST_Case) {
1722
- extract_candidates(expr.expression);
1723
- } else if (expr instanceof AST_Conditional) {
1724
- extract_candidates(expr.condition);
1725
- extract_candidates(expr.consequent);
1726
- extract_candidates(expr.alternative);
1727
- } else if (expr instanceof AST_Definitions) {
1728
- var len = expr.definitions.length;
1729
- // limit number of trailing variable definitions for consideration
1730
- var i = len - 200;
1731
- if (i < 0) i = 0;
1732
- for (; i < len; i++) {
1733
- extract_candidates(expr.definitions[i]);
1734
- }
1735
- } else if (expr instanceof AST_DWLoop) {
1736
- extract_candidates(expr.condition);
1737
- if (!(expr.body instanceof AST_Block)) {
1738
- extract_candidates(expr.body);
1739
- }
1740
- } else if (expr instanceof AST_Exit) {
1741
- if (expr.value) extract_candidates(expr.value);
1742
- } else if (expr instanceof AST_For) {
1743
- if (expr.init) extract_candidates(expr.init);
1744
- if (expr.condition) extract_candidates(expr.condition);
1745
- if (expr.step) extract_candidates(expr.step);
1746
- if (!(expr.body instanceof AST_Block)) {
1747
- extract_candidates(expr.body);
1748
- }
1749
- } else if (expr instanceof AST_ForIn) {
1750
- extract_candidates(expr.object);
1751
- if (!(expr.body instanceof AST_Block)) {
1752
- extract_candidates(expr.body);
1753
- }
1754
- } else if (expr instanceof AST_If) {
1755
- extract_candidates(expr.condition);
1756
- if (!(expr.body instanceof AST_Block)) {
1757
- extract_candidates(expr.body);
1758
- }
1759
- if (expr.alternative && !(expr.alternative instanceof AST_Block)) {
1760
- extract_candidates(expr.alternative);
1761
- }
1762
- } else if (expr instanceof AST_Sequence) {
1763
- expr.expressions.forEach(extract_candidates);
1764
- } else if (expr instanceof AST_SimpleStatement) {
1765
- extract_candidates(expr.body);
1766
- } else if (expr instanceof AST_Switch) {
1767
- extract_candidates(expr.expression);
1768
- expr.body.forEach(extract_candidates);
1769
- } else if (expr instanceof AST_Unary) {
1770
- if (expr.operator == "++" || expr.operator == "--") {
1771
- candidates.push(hit_stack.slice());
1772
- }
1773
- } else if (expr instanceof AST_VarDef) {
1774
- if (expr.value) {
1775
- candidates.push(hit_stack.slice());
1776
- extract_candidates(expr.value);
1777
- }
1778
- }
1779
- hit_stack.pop();
1780
- }
1781
-
1782
- function find_stop(node, level, write_only) {
1783
- var parent = scanner.parent(level);
1784
- if (parent instanceof AST_Assign) {
1785
- if (write_only
1786
- && !parent.logical
1787
- && !(parent.left instanceof AST_PropAccess
1788
- || lvalues.has(parent.left.name))) {
1789
- return find_stop(parent, level + 1, write_only);
1790
- }
1791
- return node;
1792
- }
1793
- if (parent instanceof AST_Binary) {
1794
- if (write_only && (!lazy_op.has(parent.operator) || parent.left === node)) {
1795
- return find_stop(parent, level + 1, write_only);
1796
- }
1797
- return node;
1798
- }
1799
- if (parent instanceof AST_Call) return node;
1800
- if (parent instanceof AST_Case) return node;
1801
- if (parent instanceof AST_Conditional) {
1802
- if (write_only && parent.condition === node) {
1803
- return find_stop(parent, level + 1, write_only);
1804
- }
1805
- return node;
1806
- }
1807
- if (parent instanceof AST_Definitions) {
1808
- return find_stop(parent, level + 1, true);
1809
- }
1810
- if (parent instanceof AST_Exit) {
1811
- return write_only ? find_stop(parent, level + 1, write_only) : node;
1812
- }
1813
- if (parent instanceof AST_If) {
1814
- if (write_only && parent.condition === node) {
1815
- return find_stop(parent, level + 1, write_only);
1816
- }
1817
- return node;
1818
- }
1819
- if (parent instanceof AST_IterationStatement) return node;
1820
- if (parent instanceof AST_Sequence) {
1821
- return find_stop(parent, level + 1, parent.tail_node() !== node);
1822
- }
1823
- if (parent instanceof AST_SimpleStatement) {
1824
- return find_stop(parent, level + 1, true);
1825
- }
1826
- if (parent instanceof AST_Switch) return node;
1827
- if (parent instanceof AST_VarDef) return node;
1828
- return null;
1829
- }
1830
-
1831
- function mangleable_var(var_def) {
1832
- var value = var_def.value;
1833
- if (!(value instanceof AST_SymbolRef)) return;
1834
- if (value.name == "arguments") return;
1835
- var def = value.definition();
1836
- if (def.undeclared) return;
1837
- return value_def = def;
1838
- }
1839
-
1840
- function get_lhs(expr) {
1841
- if (expr instanceof AST_Assign && expr.logical) {
1842
- return false;
1843
- } else if (expr instanceof AST_VarDef && expr.name instanceof AST_SymbolDeclaration) {
1844
- var def = expr.name.definition();
1845
- if (!member(expr.name, def.orig)) return;
1846
- var referenced = def.references.length - def.replaced;
1847
- if (!referenced) return;
1848
- var declared = def.orig.length - def.eliminated;
1849
- if (declared > 1 && !(expr.name instanceof AST_SymbolFunarg)
1850
- || (referenced > 1 ? mangleable_var(expr) : !compressor.exposed(def))) {
1851
- return make_node(AST_SymbolRef, expr.name, expr.name);
1852
- }
1853
- } else {
1854
- const lhs = expr instanceof AST_Assign
1855
- ? expr.left
1856
- : expr.expression;
1857
- return !is_ref_of(lhs, AST_SymbolConst)
1858
- && !is_ref_of(lhs, AST_SymbolLet) && lhs;
1859
- }
1860
- }
1861
-
1862
- function get_rvalue(expr) {
1863
- if (expr instanceof AST_Assign) {
1864
- return expr.right;
1865
- } else {
1866
- return expr.value;
1867
- }
1868
- }
1869
-
1870
- function get_lvalues(expr) {
1871
- var lvalues = new Map();
1872
- if (expr instanceof AST_Unary) return lvalues;
1873
- var tw = new TreeWalker(function(node) {
1874
- var sym = node;
1875
- while (sym instanceof AST_PropAccess) sym = sym.expression;
1876
- if (sym instanceof AST_SymbolRef || sym instanceof AST_This) {
1877
- lvalues.set(sym.name, lvalues.get(sym.name) || is_modified(compressor, tw, node, node, 0));
1878
- }
1879
- });
1880
- get_rvalue(expr).walk(tw);
1881
- return lvalues;
1882
- }
1883
-
1884
- function remove_candidate(expr) {
1885
- if (expr.name instanceof AST_SymbolFunarg) {
1886
- var iife = compressor.parent(), argnames = compressor.self().argnames;
1887
- var index = argnames.indexOf(expr.name);
1888
- if (index < 0) {
1889
- iife.args.length = Math.min(iife.args.length, argnames.length - 1);
1890
- } else {
1891
- var args = iife.args;
1892
- if (args[index]) args[index] = make_node(AST_Number, args[index], {
1893
- value: 0
1894
- });
1895
- }
1896
- return true;
1897
- }
1898
- var found = false;
1899
- return statements[stat_index].transform(new TreeTransformer(function(node, descend, in_list) {
1900
- if (found) return node;
1901
- if (node === expr || node.body === expr) {
1902
- found = true;
1903
- if (node instanceof AST_VarDef) {
1904
- node.value = node.name instanceof AST_SymbolConst
1905
- ? make_node(AST_Undefined, node.value) // `const` always needs value.
1906
- : null;
1907
- return node;
1908
- }
1909
- return in_list ? MAP.skip : null;
1910
- }
1911
- }, function(node) {
1912
- if (node instanceof AST_Sequence) switch (node.expressions.length) {
1913
- case 0: return null;
1914
- case 1: return node.expressions[0];
1915
- }
1916
- }));
1917
- }
1918
-
1919
- function is_lhs_local(lhs) {
1920
- while (lhs instanceof AST_PropAccess) lhs = lhs.expression;
1921
- return lhs instanceof AST_SymbolRef
1922
- && lhs.definition().scope === scope
1923
- && !(in_loop
1924
- && (lvalues.has(lhs.name)
1925
- || candidate instanceof AST_Unary
1926
- || (candidate instanceof AST_Assign
1927
- && !candidate.logical
1928
- && candidate.operator != "=")));
1929
- }
1930
-
1931
- function value_has_side_effects(expr) {
1932
- if (expr instanceof AST_Unary) return unary_side_effects.has(expr.operator);
1933
- return get_rvalue(expr).has_side_effects(compressor);
1934
- }
1935
-
1936
- function replace_all_symbols() {
1937
- if (side_effects) return false;
1938
- if (value_def) return true;
1939
- if (lhs instanceof AST_SymbolRef) {
1940
- var def = lhs.definition();
1941
- if (def.references.length - def.replaced == (candidate instanceof AST_VarDef ? 1 : 2)) {
1942
- return true;
1943
- }
1944
- }
1945
- return false;
1946
- }
1947
-
1948
- function may_modify(sym) {
1949
- if (!sym.definition) return true; // AST_Destructuring
1950
- var def = sym.definition();
1951
- if (def.orig.length == 1 && def.orig[0] instanceof AST_SymbolDefun) return false;
1952
- if (def.scope.get_defun_scope() !== scope) return true;
1953
- return !def.references.every((ref) => {
1954
- var s = ref.scope.get_defun_scope();
1955
- // "block" scope within AST_Catch
1956
- if (s.TYPE == "Scope") s = s.parent_scope;
1957
- return s === scope;
1958
- });
1959
- }
1960
-
1961
- function side_effects_external(node, lhs) {
1962
- if (node instanceof AST_Assign) return side_effects_external(node.left, true);
1963
- if (node instanceof AST_Unary) return side_effects_external(node.expression, true);
1964
- if (node instanceof AST_VarDef) return node.value && side_effects_external(node.value);
1965
- if (lhs) {
1966
- if (node instanceof AST_Dot) return side_effects_external(node.expression, true);
1967
- if (node instanceof AST_Sub) return side_effects_external(node.expression, true);
1968
- if (node instanceof AST_SymbolRef) return node.definition().scope !== scope;
1969
- }
1970
- return false;
1971
- }
1972
- }
1973
-
1974
- function eliminate_spurious_blocks(statements) {
1975
- var seen_dirs = [];
1976
- for (var i = 0; i < statements.length;) {
1977
- var stat = statements[i];
1978
- if (stat instanceof AST_BlockStatement && stat.body.every(can_be_evicted_from_block)) {
1979
- CHANGED = true;
1980
- eliminate_spurious_blocks(stat.body);
1981
- statements.splice(i, 1, ...stat.body);
1982
- i += stat.body.length;
1983
- } else if (stat instanceof AST_EmptyStatement) {
1984
- CHANGED = true;
1985
- statements.splice(i, 1);
1986
- } else if (stat instanceof AST_Directive) {
1987
- if (seen_dirs.indexOf(stat.value) < 0) {
1988
- i++;
1989
- seen_dirs.push(stat.value);
1990
- } else {
1991
- CHANGED = true;
1992
- statements.splice(i, 1);
1993
- }
1994
- } else i++;
1995
- }
1996
- }
1997
-
1998
- function handle_if_return(statements, compressor) {
1999
- var self = compressor.self();
2000
- var multiple_if_returns = has_multiple_if_returns(statements);
2001
- var in_lambda = self instanceof AST_Lambda;
2002
- for (var i = statements.length; --i >= 0;) {
2003
- var stat = statements[i];
2004
- var j = next_index(i);
2005
- var next = statements[j];
2006
-
2007
- if (in_lambda && !next && stat instanceof AST_Return) {
2008
- if (!stat.value) {
2009
- CHANGED = true;
2010
- statements.splice(i, 1);
2011
- continue;
2012
- }
2013
- if (stat.value instanceof AST_UnaryPrefix && stat.value.operator == "void") {
2014
- CHANGED = true;
2015
- statements[i] = make_node(AST_SimpleStatement, stat, {
2016
- body: stat.value.expression
2017
- });
2018
- continue;
2019
- }
2020
- }
2021
-
2022
- if (stat instanceof AST_If) {
2023
- var ab = aborts(stat.body);
2024
- if (can_merge_flow(ab)) {
2025
- if (ab.label) {
2026
- remove(ab.label.thedef.references, ab);
2027
- }
2028
- CHANGED = true;
2029
- stat = stat.clone();
2030
- stat.condition = stat.condition.negate(compressor);
2031
- var body = as_statement_array_with_return(stat.body, ab);
2032
- stat.body = make_node(AST_BlockStatement, stat, {
2033
- body: as_statement_array(stat.alternative).concat(extract_functions())
2034
- });
2035
- stat.alternative = make_node(AST_BlockStatement, stat, {
2036
- body: body
2037
- });
2038
- statements[i] = stat.transform(compressor);
2039
- continue;
2040
- }
2041
-
2042
- var ab = aborts(stat.alternative);
2043
- if (can_merge_flow(ab)) {
2044
- if (ab.label) {
2045
- remove(ab.label.thedef.references, ab);
2046
- }
2047
- CHANGED = true;
2048
- stat = stat.clone();
2049
- stat.body = make_node(AST_BlockStatement, stat.body, {
2050
- body: as_statement_array(stat.body).concat(extract_functions())
2051
- });
2052
- var body = as_statement_array_with_return(stat.alternative, ab);
2053
- stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
2054
- body: body
2055
- });
2056
- statements[i] = stat.transform(compressor);
2057
- continue;
2058
- }
2059
- }
2060
-
2061
- if (stat instanceof AST_If && stat.body instanceof AST_Return) {
2062
- var value = stat.body.value;
2063
- //---
2064
- // pretty silly case, but:
2065
- // if (foo()) return; return; ==> foo(); return;
2066
- if (!value && !stat.alternative
2067
- && (in_lambda && !next || next instanceof AST_Return && !next.value)) {
2068
- CHANGED = true;
2069
- statements[i] = make_node(AST_SimpleStatement, stat.condition, {
2070
- body: stat.condition
2071
- });
2072
- continue;
2073
- }
2074
- //---
2075
- // if (foo()) return x; return y; ==> return foo() ? x : y;
2076
- if (value && !stat.alternative && next instanceof AST_Return && next.value) {
2077
- CHANGED = true;
2078
- stat = stat.clone();
2079
- stat.alternative = next;
2080
- statements[i] = stat.transform(compressor);
2081
- statements.splice(j, 1);
2082
- continue;
2083
- }
2084
- //---
2085
- // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
2086
- if (value && !stat.alternative
2087
- && (!next && in_lambda && multiple_if_returns
2088
- || next instanceof AST_Return)) {
2089
- CHANGED = true;
2090
- stat = stat.clone();
2091
- stat.alternative = next || make_node(AST_Return, stat, {
2092
- value: null
2093
- });
2094
- statements[i] = stat.transform(compressor);
2095
- if (next) statements.splice(j, 1);
2096
- continue;
2097
- }
2098
- //---
2099
- // if (a) return b; if (c) return d; e; ==> return a ? b : c ? d : void e;
2100
- //
2101
- // if sequences is not enabled, this can lead to an endless loop (issue #866).
2102
- // however, with sequences on this helps producing slightly better output for
2103
- // the example code.
2104
- var prev = statements[prev_index(i)];
2105
- if (compressor.option("sequences") && in_lambda && !stat.alternative
2106
- && prev instanceof AST_If && prev.body instanceof AST_Return
2107
- && next_index(j) == statements.length && next instanceof AST_SimpleStatement) {
2108
- CHANGED = true;
2109
- stat = stat.clone();
2110
- stat.alternative = make_node(AST_BlockStatement, next, {
2111
- body: [
2112
- next,
2113
- make_node(AST_Return, next, {
2114
- value: null
2115
- })
2116
- ]
2117
- });
2118
- statements[i] = stat.transform(compressor);
2119
- statements.splice(j, 1);
2120
- continue;
2121
- }
2122
- }
2123
- }
2124
-
2125
- function has_multiple_if_returns(statements) {
2126
- var n = 0;
2127
- for (var i = statements.length; --i >= 0;) {
2128
- var stat = statements[i];
2129
- if (stat instanceof AST_If && stat.body instanceof AST_Return) {
2130
- if (++n > 1) return true;
2131
- }
2132
- }
2133
- return false;
2134
- }
2135
-
2136
- function is_return_void(value) {
2137
- return !value || value instanceof AST_UnaryPrefix && value.operator == "void";
2138
- }
2139
-
2140
- function can_merge_flow(ab) {
2141
- if (!ab) return false;
2142
- for (var j = i + 1, len = statements.length; j < len; j++) {
2143
- var stat = statements[j];
2144
- if (stat instanceof AST_Const || stat instanceof AST_Let) return false;
2145
- }
2146
- var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null;
2147
- return ab instanceof AST_Return && in_lambda && is_return_void(ab.value)
2148
- || ab instanceof AST_Continue && self === loop_body(lct)
2149
- || ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct;
2150
- }
2151
-
2152
- function extract_functions() {
2153
- var tail = statements.slice(i + 1);
2154
- statements.length = i + 1;
2155
- return tail.filter(function(stat) {
2156
- if (stat instanceof AST_Defun) {
2157
- statements.push(stat);
2158
- return false;
2159
- }
2160
- return true;
2161
- });
2162
- }
2163
-
2164
- function as_statement_array_with_return(node, ab) {
2165
- var body = as_statement_array(node).slice(0, -1);
2166
- if (ab.value) {
2167
- body.push(make_node(AST_SimpleStatement, ab.value, {
2168
- body: ab.value.expression
2169
- }));
2170
- }
2171
- return body;
2172
- }
2173
-
2174
- function next_index(i) {
2175
- for (var j = i + 1, len = statements.length; j < len; j++) {
2176
- var stat = statements[j];
2177
- if (!(stat instanceof AST_Var && declarations_only(stat))) {
2178
- break;
2179
- }
2180
- }
2181
- return j;
2182
- }
2183
-
2184
- function prev_index(i) {
2185
- for (var j = i; --j >= 0;) {
2186
- var stat = statements[j];
2187
- if (!(stat instanceof AST_Var && declarations_only(stat))) {
2188
- break;
2189
- }
2190
- }
2191
- return j;
2192
- }
2193
- }
2194
-
2195
- function eliminate_dead_code(statements, compressor) {
2196
- var has_quit;
2197
- var self = compressor.self();
2198
- for (var i = 0, n = 0, len = statements.length; i < len; i++) {
2199
- var stat = statements[i];
2200
- if (stat instanceof AST_LoopControl) {
2201
- var lct = compressor.loopcontrol_target(stat);
2202
- if (stat instanceof AST_Break
2203
- && !(lct instanceof AST_IterationStatement)
2204
- && loop_body(lct) === self
2205
- || stat instanceof AST_Continue
2206
- && loop_body(lct) === self) {
2207
- if (stat.label) {
2208
- remove(stat.label.thedef.references, stat);
2209
- }
2210
- } else {
2211
- statements[n++] = stat;
2212
- }
2213
- } else {
2214
- statements[n++] = stat;
2215
- }
2216
- if (aborts(stat)) {
2217
- has_quit = statements.slice(i + 1);
2218
- break;
2219
- }
2220
- }
2221
- statements.length = n;
2222
- CHANGED = n != len;
2223
- if (has_quit) has_quit.forEach(function(stat) {
2224
- trim_unreachable_code(compressor, stat, statements);
2225
- });
2226
- }
2227
-
2228
- function declarations_only(node) {
2229
- return node.definitions.every((var_def) =>
2230
- !var_def.value
2231
- );
2232
- }
2233
-
2234
- function sequencesize(statements, compressor) {
2235
- if (statements.length < 2) return;
2236
- var seq = [], n = 0;
2237
- function push_seq() {
2238
- if (!seq.length) return;
2239
- var body = make_sequence(seq[0], seq);
2240
- statements[n++] = make_node(AST_SimpleStatement, body, { body: body });
2241
- seq = [];
2242
- }
2243
- for (var i = 0, len = statements.length; i < len; i++) {
2244
- var stat = statements[i];
2245
- if (stat instanceof AST_SimpleStatement) {
2246
- if (seq.length >= compressor.sequences_limit) push_seq();
2247
- var body = stat.body;
2248
- if (seq.length > 0) body = body.drop_side_effect_free(compressor);
2249
- if (body) merge_sequence(seq, body);
2250
- } else if (stat instanceof AST_Definitions && declarations_only(stat)
2251
- || stat instanceof AST_Defun) {
2252
- statements[n++] = stat;
2253
- } else {
2254
- push_seq();
2255
- statements[n++] = stat;
2256
- }
2257
- }
2258
- push_seq();
2259
- statements.length = n;
2260
- if (n != len) CHANGED = true;
2261
- }
2262
-
2263
- function to_simple_statement(block, decls) {
2264
- if (!(block instanceof AST_BlockStatement)) return block;
2265
- var stat = null;
2266
- for (var i = 0, len = block.body.length; i < len; i++) {
2267
- var line = block.body[i];
2268
- if (line instanceof AST_Var && declarations_only(line)) {
2269
- decls.push(line);
2270
- } else if (stat) {
2271
- return false;
2272
- } else {
2273
- stat = line;
2274
- }
2275
- }
2276
- return stat;
2277
- }
2278
-
2279
- function sequencesize_2(statements, compressor) {
2280
- function cons_seq(right) {
2281
- n--;
2282
- CHANGED = true;
2283
- var left = prev.body;
2284
- return make_sequence(left, [ left, right ]).transform(compressor);
2285
- }
2286
- var n = 0, prev;
2287
- for (var i = 0; i < statements.length; i++) {
2288
- var stat = statements[i];
2289
- if (prev) {
2290
- if (stat instanceof AST_Exit) {
2291
- stat.value = cons_seq(stat.value || make_node(AST_Undefined, stat).transform(compressor));
2292
- } else if (stat instanceof AST_For) {
2293
- if (!(stat.init instanceof AST_Definitions)) {
2294
- const abort = walk(prev.body, node => {
2295
- if (node instanceof AST_Scope) return true;
2296
- if (
2297
- node instanceof AST_Binary
2298
- && node.operator === "in"
2299
- ) {
2300
- return walk_abort;
2301
- }
2302
- });
2303
- if (!abort) {
2304
- if (stat.init) stat.init = cons_seq(stat.init);
2305
- else {
2306
- stat.init = prev.body;
2307
- n--;
2308
- CHANGED = true;
2309
- }
2310
- }
2311
- }
2312
- } else if (stat instanceof AST_ForIn) {
2313
- if (!(stat.init instanceof AST_Const) && !(stat.init instanceof AST_Let)) {
2314
- stat.object = cons_seq(stat.object);
2315
- }
2316
- } else if (stat instanceof AST_If) {
2317
- stat.condition = cons_seq(stat.condition);
2318
- } else if (stat instanceof AST_Switch) {
2319
- stat.expression = cons_seq(stat.expression);
2320
- } else if (stat instanceof AST_With) {
2321
- stat.expression = cons_seq(stat.expression);
2322
- }
2323
- }
2324
- if (compressor.option("conditionals") && stat instanceof AST_If) {
2325
- var decls = [];
2326
- var body = to_simple_statement(stat.body, decls);
2327
- var alt = to_simple_statement(stat.alternative, decls);
2328
- if (body !== false && alt !== false && decls.length > 0) {
2329
- var len = decls.length;
2330
- decls.push(make_node(AST_If, stat, {
2331
- condition: stat.condition,
2332
- body: body || make_node(AST_EmptyStatement, stat.body),
2333
- alternative: alt
2334
- }));
2335
- decls.unshift(n, 1);
2336
- [].splice.apply(statements, decls);
2337
- i += len;
2338
- n += len + 1;
2339
- prev = null;
2340
- CHANGED = true;
2341
- continue;
2342
- }
2343
- }
2344
- statements[n++] = stat;
2345
- prev = stat instanceof AST_SimpleStatement ? stat : null;
2346
- }
2347
- statements.length = n;
2348
- }
2349
-
2350
- function join_object_assignments(defn, body) {
2351
- if (!(defn instanceof AST_Definitions)) return;
2352
- var def = defn.definitions[defn.definitions.length - 1];
2353
- if (!(def.value instanceof AST_Object)) return;
2354
- var exprs;
2355
- if (body instanceof AST_Assign && !body.logical) {
2356
- exprs = [ body ];
2357
- } else if (body instanceof AST_Sequence) {
2358
- exprs = body.expressions.slice();
2359
- }
2360
- if (!exprs) return;
2361
- var trimmed = false;
2362
- do {
2363
- var node = exprs[0];
2364
- if (!(node instanceof AST_Assign)) break;
2365
- if (node.operator != "=") break;
2366
- if (!(node.left instanceof AST_PropAccess)) break;
2367
- var sym = node.left.expression;
2368
- if (!(sym instanceof AST_SymbolRef)) break;
2369
- if (def.name.name != sym.name) break;
2370
- if (!node.right.is_constant_expression(scope)) break;
2371
- var prop = node.left.property;
2372
- if (prop instanceof AST_Node) {
2373
- prop = prop.evaluate(compressor);
2374
- }
2375
- if (prop instanceof AST_Node) break;
2376
- prop = "" + prop;
2377
- var diff = compressor.option("ecma") < 2015
2378
- && compressor.has_directive("use strict") ? function(node) {
2379
- return node.key != prop && (node.key && node.key.name != prop);
2380
- } : function(node) {
2381
- return node.key && node.key.name != prop;
2382
- };
2383
- if (!def.value.properties.every(diff)) break;
2384
- var p = def.value.properties.filter(function (p) { return p.key === prop; })[0];
2385
- if (!p) {
2386
- def.value.properties.push(make_node(AST_ObjectKeyVal, node, {
2387
- key: prop,
2388
- value: node.right
2389
- }));
2390
- } else {
2391
- p.value = new AST_Sequence({
2392
- start: p.start,
2393
- expressions: [p.value.clone(), node.right.clone()],
2394
- end: p.end
2395
- });
2396
- }
2397
- exprs.shift();
2398
- trimmed = true;
2399
- } while (exprs.length);
2400
- return trimmed && exprs;
2401
- }
2402
-
2403
- function join_consecutive_vars(statements) {
2404
- var defs;
2405
- for (var i = 0, j = -1, len = statements.length; i < len; i++) {
2406
- var stat = statements[i];
2407
- var prev = statements[j];
2408
- if (stat instanceof AST_Definitions) {
2409
- if (prev && prev.TYPE == stat.TYPE) {
2410
- prev.definitions = prev.definitions.concat(stat.definitions);
2411
- CHANGED = true;
2412
- } else if (defs && defs.TYPE == stat.TYPE && declarations_only(stat)) {
2413
- defs.definitions = defs.definitions.concat(stat.definitions);
2414
- CHANGED = true;
2415
- } else {
2416
- statements[++j] = stat;
2417
- defs = stat;
2418
- }
2419
- } else if (stat instanceof AST_Exit) {
2420
- stat.value = extract_object_assignments(stat.value);
2421
- } else if (stat instanceof AST_For) {
2422
- var exprs = join_object_assignments(prev, stat.init);
2423
- if (exprs) {
2424
- CHANGED = true;
2425
- stat.init = exprs.length ? make_sequence(stat.init, exprs) : null;
2426
- statements[++j] = stat;
2427
- } else if (prev instanceof AST_Var && (!stat.init || stat.init.TYPE == prev.TYPE)) {
2428
- if (stat.init) {
2429
- prev.definitions = prev.definitions.concat(stat.init.definitions);
2430
- }
2431
- stat.init = prev;
2432
- statements[j] = stat;
2433
- CHANGED = true;
2434
- } else if (defs && stat.init && defs.TYPE == stat.init.TYPE && declarations_only(stat.init)) {
2435
- defs.definitions = defs.definitions.concat(stat.init.definitions);
2436
- stat.init = null;
2437
- statements[++j] = stat;
2438
- CHANGED = true;
2439
- } else {
2440
- statements[++j] = stat;
2441
- }
2442
- } else if (stat instanceof AST_ForIn) {
2443
- stat.object = extract_object_assignments(stat.object);
2444
- } else if (stat instanceof AST_If) {
2445
- stat.condition = extract_object_assignments(stat.condition);
2446
- } else if (stat instanceof AST_SimpleStatement) {
2447
- var exprs = join_object_assignments(prev, stat.body);
2448
- if (exprs) {
2449
- CHANGED = true;
2450
- if (!exprs.length) continue;
2451
- stat.body = make_sequence(stat.body, exprs);
2452
- }
2453
- statements[++j] = stat;
2454
- } else if (stat instanceof AST_Switch) {
2455
- stat.expression = extract_object_assignments(stat.expression);
2456
- } else if (stat instanceof AST_With) {
2457
- stat.expression = extract_object_assignments(stat.expression);
2458
- } else {
2459
- statements[++j] = stat;
2460
- }
2461
- }
2462
- statements.length = j + 1;
2463
-
2464
- function extract_object_assignments(value) {
2465
- statements[++j] = stat;
2466
- var exprs = join_object_assignments(prev, value);
2467
- if (exprs) {
2468
- CHANGED = true;
2469
- if (exprs.length) {
2470
- return make_sequence(value, exprs);
2471
- } else if (value instanceof AST_Sequence) {
2472
- return value.tail_node().left;
2473
- } else {
2474
- return value.left;
2475
- }
2476
- }
2477
- return value;
2478
- }
2479
- }
2480
- }
2481
-
2482
- function trim_unreachable_code(compressor, stat, target) {
2483
- walk(stat, node => {
2484
- if (node instanceof AST_Var) {
2485
- node.remove_initializers();
2486
- target.push(node);
2487
- return true;
2488
- }
2489
- if (
2490
- node instanceof AST_Defun
2491
- && (node === stat || !compressor.has_directive("use strict"))
2492
- ) {
2493
- target.push(node === stat ? node : make_node(AST_Var, node, {
2494
- definitions: [
2495
- make_node(AST_VarDef, node, {
2496
- name: make_node(AST_SymbolVar, node.name, node.name),
2497
- value: null
2498
- })
2499
- ]
2500
- }));
2501
- return true;
2502
- }
2503
- if (node instanceof AST_Export || node instanceof AST_Import) {
2504
- target.push(node);
2505
- return true;
2506
- }
2507
- if (node instanceof AST_Scope) {
2508
- return true;
2509
- }
2510
- });
2511
- }
2512
-
2513
- function get_value(key) {
2514
- if (key instanceof AST_Constant) {
2515
- return key.getValue();
2516
- }
2517
- if (key instanceof AST_UnaryPrefix
2518
- && key.operator == "void"
2519
- && key.expression instanceof AST_Constant) {
2520
- return;
2521
- }
2522
- return key;
2523
- }
2524
-
2525
- function is_undefined(node, compressor) {
2526
- return (
2527
- has_flag(node, UNDEFINED)
2528
- || node instanceof AST_Undefined
2529
- || node instanceof AST_UnaryPrefix
2530
- && node.operator == "void"
2531
- && !node.expression.has_side_effects(compressor)
2532
- );
2533
- }
2534
-
2535
- // may_throw_on_access()
2536
- // returns true if this node may be null, undefined or contain `AST_Accessor`
2537
- (function(def_may_throw_on_access) {
2538
- AST_Node.DEFMETHOD("may_throw_on_access", function(compressor) {
2539
- return !compressor.option("pure_getters")
2540
- || this._dot_throw(compressor);
2541
- });
2542
-
2543
- function is_strict(compressor) {
2544
- return /strict/.test(compressor.option("pure_getters"));
2545
- }
2546
-
2547
- def_may_throw_on_access(AST_Node, is_strict);
2548
- def_may_throw_on_access(AST_Null, return_true);
2549
- def_may_throw_on_access(AST_Undefined, return_true);
2550
- def_may_throw_on_access(AST_Constant, return_false);
2551
- def_may_throw_on_access(AST_Array, return_false);
2552
- def_may_throw_on_access(AST_Object, function(compressor) {
2553
- if (!is_strict(compressor)) return false;
2554
- for (var i = this.properties.length; --i >=0;)
2555
- if (this.properties[i]._dot_throw(compressor)) return true;
2556
- return false;
2557
- });
2558
- // Do not be as strict with classes as we are with objects.
2559
- // Hopefully the community is not going to abuse static getters and setters.
2560
- // https://github.com/terser/terser/issues/724#issuecomment-643655656
2561
- def_may_throw_on_access(AST_Class, return_false);
2562
- def_may_throw_on_access(AST_ObjectProperty, return_false);
2563
- def_may_throw_on_access(AST_ObjectGetter, return_true);
2564
- def_may_throw_on_access(AST_Expansion, function(compressor) {
2565
- return this.expression._dot_throw(compressor);
2566
- });
2567
- def_may_throw_on_access(AST_Function, return_false);
2568
- def_may_throw_on_access(AST_Arrow, return_false);
2569
- def_may_throw_on_access(AST_UnaryPostfix, return_false);
2570
- def_may_throw_on_access(AST_UnaryPrefix, function() {
2571
- return this.operator == "void";
2572
- });
2573
- def_may_throw_on_access(AST_Binary, function(compressor) {
2574
- return (this.operator == "&&" || this.operator == "||" || this.operator == "??")
2575
- && (this.left._dot_throw(compressor) || this.right._dot_throw(compressor));
2576
- });
2577
- def_may_throw_on_access(AST_Assign, function(compressor) {
2578
- if (this.logical) return true;
2579
-
2580
- return this.operator == "="
2581
- && this.right._dot_throw(compressor);
2582
- });
2583
- def_may_throw_on_access(AST_Conditional, function(compressor) {
2584
- return this.consequent._dot_throw(compressor)
2585
- || this.alternative._dot_throw(compressor);
2586
- });
2587
- def_may_throw_on_access(AST_Dot, function(compressor) {
2588
- if (!is_strict(compressor)) return false;
2589
- if (this.expression instanceof AST_Function && this.property == "prototype") return false;
2590
- return true;
2591
- });
2592
- def_may_throw_on_access(AST_Chain, function(compressor) {
2593
- return this.expression._dot_throw(compressor);
2594
- });
2595
- def_may_throw_on_access(AST_Sequence, function(compressor) {
2596
- return this.tail_node()._dot_throw(compressor);
2597
- });
2598
- def_may_throw_on_access(AST_SymbolRef, function(compressor) {
2599
- if (this.name === "arguments") return false;
2600
- if (has_flag(this, UNDEFINED)) return true;
2601
- if (!is_strict(compressor)) return false;
2602
- if (is_undeclared_ref(this) && this.is_declared(compressor)) return false;
2603
- if (this.is_immutable()) return false;
2604
- var fixed = this.fixed_value();
2605
- return !fixed || fixed._dot_throw(compressor);
2606
- });
2607
- })(function(node, func) {
2608
- node.DEFMETHOD("_dot_throw", func);
2609
- });
2610
-
2611
- /* -----[ boolean/negation helpers ]----- */
2612
-
2613
- // methods to determine whether an expression has a boolean result type
2614
- (function(def_is_boolean) {
2615
- const unary_bool = makePredicate("! delete");
2616
- const binary_bool = makePredicate("in instanceof == != === !== < <= >= >");
2617
- def_is_boolean(AST_Node, return_false);
2618
- def_is_boolean(AST_UnaryPrefix, function() {
2619
- return unary_bool.has(this.operator);
2620
- });
2621
- def_is_boolean(AST_Binary, function() {
2622
- return binary_bool.has(this.operator)
2623
- || lazy_op.has(this.operator)
2624
- && this.left.is_boolean()
2625
- && this.right.is_boolean();
2626
- });
2627
- def_is_boolean(AST_Conditional, function() {
2628
- return this.consequent.is_boolean() && this.alternative.is_boolean();
2629
- });
2630
- def_is_boolean(AST_Assign, function() {
2631
- return this.operator == "=" && this.right.is_boolean();
2632
- });
2633
- def_is_boolean(AST_Sequence, function() {
2634
- return this.tail_node().is_boolean();
2635
- });
2636
- def_is_boolean(AST_True, return_true);
2637
- def_is_boolean(AST_False, return_true);
2638
- })(function(node, func) {
2639
- node.DEFMETHOD("is_boolean", func);
2640
- });
2641
-
2642
- // methods to determine if an expression has a numeric result type
2643
- (function(def_is_number) {
2644
- def_is_number(AST_Node, return_false);
2645
- def_is_number(AST_Number, return_true);
2646
- var unary = makePredicate("+ - ~ ++ --");
2647
- def_is_number(AST_Unary, function() {
2648
- return unary.has(this.operator);
2649
- });
2650
- var binary = makePredicate("- * / % & | ^ << >> >>>");
2651
- def_is_number(AST_Binary, function(compressor) {
2652
- return binary.has(this.operator) || this.operator == "+"
2653
- && this.left.is_number(compressor)
2654
- && this.right.is_number(compressor);
2655
- });
2656
- def_is_number(AST_Assign, function(compressor) {
2657
- return binary.has(this.operator.slice(0, -1))
2658
- || this.operator == "=" && this.right.is_number(compressor);
2659
- });
2660
- def_is_number(AST_Sequence, function(compressor) {
2661
- return this.tail_node().is_number(compressor);
2662
- });
2663
- def_is_number(AST_Conditional, function(compressor) {
2664
- return this.consequent.is_number(compressor) && this.alternative.is_number(compressor);
2665
- });
2666
- })(function(node, func) {
2667
- node.DEFMETHOD("is_number", func);
2668
- });
2669
-
2670
- // methods to determine if an expression has a string result type
2671
- (function(def_is_string) {
2672
- def_is_string(AST_Node, return_false);
2673
- def_is_string(AST_String, return_true);
2674
- def_is_string(AST_TemplateString, return_true);
2675
- def_is_string(AST_UnaryPrefix, function() {
2676
- return this.operator == "typeof";
2677
- });
2678
- def_is_string(AST_Binary, function(compressor) {
2679
- return this.operator == "+" &&
2680
- (this.left.is_string(compressor) || this.right.is_string(compressor));
2681
- });
2682
- def_is_string(AST_Assign, function(compressor) {
2683
- return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
2684
- });
2685
- def_is_string(AST_Sequence, function(compressor) {
2686
- return this.tail_node().is_string(compressor);
2687
- });
2688
- def_is_string(AST_Conditional, function(compressor) {
2689
- return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
2690
- });
2691
- })(function(node, func) {
2692
- node.DEFMETHOD("is_string", func);
2693
- });
2694
-
2695
- var lazy_op = makePredicate("&& || ??");
2696
- var unary_side_effects = makePredicate("delete ++ --");
2697
-
2698
- function is_lhs(node, parent) {
2699
- if (parent instanceof AST_Unary && unary_side_effects.has(parent.operator)) return parent.expression;
2700
- if (parent instanceof AST_Assign && parent.left === node) return node;
2701
- }
2702
-
2703
- (function(def_find_defs) {
2704
- function to_node(value, orig) {
2705
- if (value instanceof AST_Node) return make_node(value.CTOR, orig, value);
2706
- if (Array.isArray(value)) return make_node(AST_Array, orig, {
2707
- elements: value.map(function(value) {
2708
- return to_node(value, orig);
2709
- })
2710
- });
2711
- if (value && typeof value == "object") {
2712
- var props = [];
2713
- for (var key in value) if (HOP(value, key)) {
2714
- props.push(make_node(AST_ObjectKeyVal, orig, {
2715
- key: key,
2716
- value: to_node(value[key], orig)
2717
- }));
2718
- }
2719
- return make_node(AST_Object, orig, {
2720
- properties: props
2721
- });
2722
- }
2723
- return make_node_from_constant(value, orig);
2724
- }
2725
-
2726
- AST_Toplevel.DEFMETHOD("resolve_defines", function(compressor) {
2727
- if (!compressor.option("global_defs")) return this;
2728
- this.figure_out_scope({ ie8: compressor.option("ie8") });
2729
- return this.transform(new TreeTransformer(function(node) {
2730
- var def = node._find_defs(compressor, "");
2731
- if (!def) return;
2732
- var level = 0, child = node, parent;
2733
- while (parent = this.parent(level++)) {
2734
- if (!(parent instanceof AST_PropAccess)) break;
2735
- if (parent.expression !== child) break;
2736
- child = parent;
2737
- }
2738
- if (is_lhs(child, parent)) {
2739
- return;
2740
- }
2741
- return def;
2742
- }));
2743
- });
2744
- def_find_defs(AST_Node, noop);
2745
- def_find_defs(AST_Chain, function(compressor, suffix) {
2746
- return this.expression._find_defs(compressor, suffix);
2747
- });
2748
- def_find_defs(AST_Dot, function(compressor, suffix) {
2749
- return this.expression._find_defs(compressor, "." + this.property + suffix);
2750
- });
2751
- def_find_defs(AST_SymbolDeclaration, function() {
2752
- if (!this.global()) return;
2753
- });
2754
- def_find_defs(AST_SymbolRef, function(compressor, suffix) {
2755
- if (!this.global()) return;
2756
- var defines = compressor.option("global_defs");
2757
- var name = this.name + suffix;
2758
- if (HOP(defines, name)) return to_node(defines[name], this);
2759
- });
2760
- })(function(node, func) {
2761
- node.DEFMETHOD("_find_defs", func);
2762
- });
2763
-
2764
- function best_of_expression(ast1, ast2) {
2765
- return ast1.size() > ast2.size() ? ast2 : ast1;
2766
- }
2767
-
2768
- function best_of_statement(ast1, ast2) {
2769
- return best_of_expression(
2770
- make_node(AST_SimpleStatement, ast1, {
2771
- body: ast1
2772
- }),
2773
- make_node(AST_SimpleStatement, ast2, {
2774
- body: ast2
2775
- })
2776
- ).body;
2777
- }
2778
-
2779
- function best_of(compressor, ast1, ast2) {
2780
- return (first_in_statement(compressor) ? best_of_statement : best_of_expression)(ast1, ast2);
2781
- }
2782
-
2783
- function convert_to_predicate(obj) {
2784
- const out = new Map();
2785
- for (var key of Object.keys(obj)) {
2786
- out.set(key, makePredicate(obj[key]));
2787
- }
2788
- return out;
2789
- }
2790
-
2791
- var object_fns = [
2792
- "constructor",
2793
- "toString",
2794
- "valueOf",
2795
- ];
2796
- var native_fns = convert_to_predicate({
2797
- Array: [
2798
- "indexOf",
2799
- "join",
2800
- "lastIndexOf",
2801
- "slice",
2802
- ].concat(object_fns),
2803
- Boolean: object_fns,
2804
- Function: object_fns,
2805
- Number: [
2806
- "toExponential",
2807
- "toFixed",
2808
- "toPrecision",
2809
- ].concat(object_fns),
2810
- Object: object_fns,
2811
- RegExp: [
2812
- "test",
2813
- ].concat(object_fns),
2814
- String: [
2815
- "charAt",
2816
- "charCodeAt",
2817
- "concat",
2818
- "indexOf",
2819
- "italics",
2820
- "lastIndexOf",
2821
- "match",
2822
- "replace",
2823
- "search",
2824
- "slice",
2825
- "split",
2826
- "substr",
2827
- "substring",
2828
- "toLowerCase",
2829
- "toUpperCase",
2830
- "trim",
2831
- ].concat(object_fns),
2832
- });
2833
- var static_fns = convert_to_predicate({
2834
- Array: [
2835
- "isArray",
2836
- ],
2837
- Math: [
2838
- "abs",
2839
- "acos",
2840
- "asin",
2841
- "atan",
2842
- "ceil",
2843
- "cos",
2844
- "exp",
2845
- "floor",
2846
- "log",
2847
- "round",
2848
- "sin",
2849
- "sqrt",
2850
- "tan",
2851
- "atan2",
2852
- "pow",
2853
- "max",
2854
- "min",
2855
- ],
2856
- Number: [
2857
- "isFinite",
2858
- "isNaN",
2859
- ],
2860
- Object: [
2861
- "create",
2862
- "getOwnPropertyDescriptor",
2863
- "getOwnPropertyNames",
2864
- "getPrototypeOf",
2865
- "isExtensible",
2866
- "isFrozen",
2867
- "isSealed",
2868
- "keys",
2869
- ],
2870
- String: [
2871
- "fromCharCode",
2872
- ],
2873
- });
2874
-
2875
- // methods to evaluate a constant expression
2876
- (function(def_eval) {
2877
- // If the node has been successfully reduced to a constant,
2878
- // then its value is returned; otherwise the element itself
2879
- // is returned.
2880
- // They can be distinguished as constant value is never a
2881
- // descendant of AST_Node.
2882
- AST_Node.DEFMETHOD("evaluate", function(compressor) {
2883
- if (!compressor.option("evaluate")) return this;
2884
- var val = this._eval(compressor, 1);
2885
- if (!val || val instanceof RegExp) return val;
2886
- if (typeof val == "function" || typeof val == "object") return this;
2887
- return val;
2888
- });
2889
- var unaryPrefix = makePredicate("! ~ - + void");
2890
- AST_Node.DEFMETHOD("is_constant", function() {
2891
- // Accomodate when compress option evaluate=false
2892
- // as well as the common constant expressions !0 and -1
2893
- if (this instanceof AST_Constant) {
2894
- return !(this instanceof AST_RegExp);
2895
- } else {
2896
- return this instanceof AST_UnaryPrefix
2897
- && this.expression instanceof AST_Constant
2898
- && unaryPrefix.has(this.operator);
2899
- }
2900
- });
2901
- def_eval(AST_Statement, function() {
2902
- throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
2903
- });
2904
- def_eval(AST_Lambda, return_this);
2905
- def_eval(AST_Class, return_this);
2906
- def_eval(AST_Node, return_this);
2907
- def_eval(AST_Constant, function() {
2908
- return this.getValue();
2909
- });
2910
- def_eval(AST_BigInt, return_this);
2911
- def_eval(AST_RegExp, function(compressor) {
2912
- let evaluated = compressor.evaluated_regexps.get(this);
2913
- if (evaluated === undefined) {
2914
- try {
2915
- evaluated = (0, eval)(this.print_to_string());
2916
- } catch (e) {
2917
- evaluated = null;
2918
- }
2919
- compressor.evaluated_regexps.set(this, evaluated);
2920
- }
2921
- return evaluated || this;
2922
- });
2923
- def_eval(AST_TemplateString, function() {
2924
- if (this.segments.length !== 1) return this;
2925
- return this.segments[0].value;
2926
- });
2927
- def_eval(AST_Function, function(compressor) {
2928
- if (compressor.option("unsafe")) {
2929
- var fn = function() {};
2930
- fn.node = this;
2931
- fn.toString = function() {
2932
- return this.node.print_to_string();
2933
- };
2934
- return fn;
2935
- }
2936
- return this;
2937
- });
2938
- def_eval(AST_Array, function(compressor, depth) {
2939
- if (compressor.option("unsafe")) {
2940
- var elements = [];
2941
- for (var i = 0, len = this.elements.length; i < len; i++) {
2942
- var element = this.elements[i];
2943
- var value = element._eval(compressor, depth);
2944
- if (element === value) return this;
2945
- elements.push(value);
2946
- }
2947
- return elements;
2948
- }
2949
- return this;
2950
- });
2951
- def_eval(AST_Object, function(compressor, depth) {
2952
- if (compressor.option("unsafe")) {
2953
- var val = {};
2954
- for (var i = 0, len = this.properties.length; i < len; i++) {
2955
- var prop = this.properties[i];
2956
- if (prop instanceof AST_Expansion) return this;
2957
- var key = prop.key;
2958
- if (key instanceof AST_Symbol) {
2959
- key = key.name;
2960
- } else if (key instanceof AST_Node) {
2961
- key = key._eval(compressor, depth);
2962
- if (key === prop.key) return this;
2963
- }
2964
- if (typeof Object.prototype[key] === "function") {
2965
- return this;
2966
- }
2967
- if (prop.value instanceof AST_Function) continue;
2968
- val[key] = prop.value._eval(compressor, depth);
2969
- if (val[key] === prop.value) return this;
2970
- }
2971
- return val;
2972
- }
2973
- return this;
2974
- });
2975
- var non_converting_unary = makePredicate("! typeof void");
2976
- def_eval(AST_UnaryPrefix, function(compressor, depth) {
2977
- var e = this.expression;
2978
- // Function would be evaluated to an array and so typeof would
2979
- // incorrectly return 'object'. Hence making is a special case.
2980
- if (compressor.option("typeofs")
2981
- && this.operator == "typeof"
2982
- && (e instanceof AST_Lambda
2983
- || e instanceof AST_SymbolRef
2984
- && e.fixed_value() instanceof AST_Lambda)) {
2985
- return typeof function() {};
2986
- }
2987
- if (!non_converting_unary.has(this.operator)) depth++;
2988
- e = e._eval(compressor, depth);
2989
- if (e === this.expression) return this;
2990
- switch (this.operator) {
2991
- case "!": return !e;
2992
- case "typeof":
2993
- // typeof <RegExp> returns "object" or "function" on different platforms
2994
- // so cannot evaluate reliably
2995
- if (e instanceof RegExp) return this;
2996
- return typeof e;
2997
- case "void": return void e;
2998
- case "~": return ~e;
2999
- case "-": return -e;
3000
- case "+": return +e;
3001
- }
3002
- return this;
3003
- });
3004
- var non_converting_binary = makePredicate("&& || ?? === !==");
3005
- const identity_comparison = makePredicate("== != === !==");
3006
- const has_identity = value =>
3007
- typeof value === "object"
3008
- || typeof value === "function"
3009
- || typeof value === "symbol";
3010
-
3011
- def_eval(AST_Binary, function(compressor, depth) {
3012
- if (!non_converting_binary.has(this.operator)) depth++;
3013
-
3014
- var left = this.left._eval(compressor, depth);
3015
- if (left === this.left) return this;
3016
- var right = this.right._eval(compressor, depth);
3017
- if (right === this.right) return this;
3018
- var result;
3019
-
3020
- if (
3021
- left != null
3022
- && right != null
3023
- && identity_comparison.has(this.operator)
3024
- && has_identity(left)
3025
- && has_identity(right)
3026
- && typeof left === typeof right
3027
- ) {
3028
- // Do not compare by reference
3029
- return this;
3030
- }
3031
-
3032
- switch (this.operator) {
3033
- case "&&" : result = left && right; break;
3034
- case "||" : result = left || right; break;
3035
- case "??" : result = left != null ? left : right; break;
3036
- case "|" : result = left | right; break;
3037
- case "&" : result = left & right; break;
3038
- case "^" : result = left ^ right; break;
3039
- case "+" : result = left + right; break;
3040
- case "*" : result = left * right; break;
3041
- case "**" : result = Math.pow(left, right); break;
3042
- case "/" : result = left / right; break;
3043
- case "%" : result = left % right; break;
3044
- case "-" : result = left - right; break;
3045
- case "<<" : result = left << right; break;
3046
- case ">>" : result = left >> right; break;
3047
- case ">>>" : result = left >>> right; break;
3048
- case "==" : result = left == right; break;
3049
- case "===" : result = left === right; break;
3050
- case "!=" : result = left != right; break;
3051
- case "!==" : result = left !== right; break;
3052
- case "<" : result = left < right; break;
3053
- case "<=" : result = left <= right; break;
3054
- case ">" : result = left > right; break;
3055
- case ">=" : result = left >= right; break;
3056
- default:
3057
- return this;
3058
- }
3059
- if (isNaN(result) && compressor.find_parent(AST_With)) {
3060
- // leave original expression as is
3061
- return this;
3062
- }
3063
- return result;
3064
- });
3065
- def_eval(AST_Conditional, function(compressor, depth) {
3066
- var condition = this.condition._eval(compressor, depth);
3067
- if (condition === this.condition) return this;
3068
- var node = condition ? this.consequent : this.alternative;
3069
- var value = node._eval(compressor, depth);
3070
- return value === node ? this : value;
3071
- });
3072
-
3073
- // Set of AST_SymbolRef which are currently being evaluated.
3074
- // Avoids infinite recursion of ._eval()
3075
- const reentrant_ref_eval = new Set();
3076
- def_eval(AST_SymbolRef, function(compressor, depth) {
3077
- if (reentrant_ref_eval.has(this)) return this;
3078
-
3079
- var fixed = this.fixed_value();
3080
- if (!fixed) return this;
3081
-
3082
- reentrant_ref_eval.add(this);
3083
- const value = fixed._eval(compressor, depth);
3084
- reentrant_ref_eval.delete(this);
3085
-
3086
- if (value === fixed) return this;
3087
-
3088
- if (value && typeof value == "object") {
3089
- var escaped = this.definition().escaped;
3090
- if (escaped && depth > escaped) return this;
3091
- }
3092
- return value;
3093
- });
3094
- var global_objs = { Array, Math, Number, Object, String };
3095
- var static_values = convert_to_predicate({
3096
- Math: [
3097
- "E",
3098
- "LN10",
3099
- "LN2",
3100
- "LOG2E",
3101
- "LOG10E",
3102
- "PI",
3103
- "SQRT1_2",
3104
- "SQRT2",
3105
- ],
3106
- Number: [
3107
- "MAX_VALUE",
3108
- "MIN_VALUE",
3109
- "NaN",
3110
- "NEGATIVE_INFINITY",
3111
- "POSITIVE_INFINITY",
3112
- ],
3113
- });
3114
- def_eval(AST_PropAccess, function(compressor, depth) {
3115
- if (this.optional) {
3116
- const obj = this.expression._eval(compressor, depth);
3117
- if (obj == null) return undefined;
3118
- }
3119
- if (compressor.option("unsafe")) {
3120
- var key = this.property;
3121
- if (key instanceof AST_Node) {
3122
- key = key._eval(compressor, depth);
3123
- if (key === this.property) return this;
3124
- }
3125
- var exp = this.expression;
3126
- var val;
3127
- if (is_undeclared_ref(exp)) {
3128
-
3129
- var aa;
3130
- var first_arg = exp.name === "hasOwnProperty"
3131
- && key === "call"
3132
- && (aa = compressor.parent() && compressor.parent().args)
3133
- && (aa && aa[0]
3134
- && aa[0].evaluate(compressor));
3135
-
3136
- first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg;
3137
-
3138
- if (first_arg == null || first_arg.thedef && first_arg.thedef.undeclared) {
3139
- return this.clone();
3140
- }
3141
- var static_value = static_values.get(exp.name);
3142
- if (!static_value || !static_value.has(key)) return this;
3143
- val = global_objs[exp.name];
3144
- } else {
3145
- val = exp._eval(compressor, depth + 1);
3146
- if (!val || val === exp || !HOP(val, key)) return this;
3147
- if (typeof val == "function") switch (key) {
3148
- case "name":
3149
- return val.node.name ? val.node.name.name : "";
3150
- case "length":
3151
- return val.node.argnames.length;
3152
- default:
3153
- return this;
3154
- }
3155
- }
3156
- return val[key];
3157
- }
3158
- return this;
3159
- });
3160
- def_eval(AST_Chain, function(compressor, depth) {
3161
- const evaluated = this.expression._eval(compressor, depth);
3162
- return evaluated === this.expression ? this : evaluated;
3163
- });
3164
- def_eval(AST_Call, function(compressor, depth) {
3165
- var exp = this.expression;
3166
- if (this.optional) {
3167
- const callee = this.expression._eval(compressor, depth);
3168
- if (callee == null) return undefined;
3169
- }
3170
- if (compressor.option("unsafe") && exp instanceof AST_PropAccess) {
3171
- var key = exp.property;
3172
- if (key instanceof AST_Node) {
3173
- key = key._eval(compressor, depth);
3174
- if (key === exp.property) return this;
3175
- }
3176
- var val;
3177
- var e = exp.expression;
3178
- if (is_undeclared_ref(e)) {
3179
- var first_arg =
3180
- e.name === "hasOwnProperty" &&
3181
- key === "call" &&
3182
- (this.args[0] && this.args[0].evaluate(compressor));
3183
-
3184
- first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg;
3185
-
3186
- if ((first_arg == null || first_arg.thedef && first_arg.thedef.undeclared)) {
3187
- return this.clone();
3188
- }
3189
- var static_fn = static_fns.get(e.name);
3190
- if (!static_fn || !static_fn.has(key)) return this;
3191
- val = global_objs[e.name];
3192
- } else {
3193
- val = e._eval(compressor, depth + 1);
3194
- if (val === e || !val) return this;
3195
- var native_fn = native_fns.get(val.constructor.name);
3196
- if (!native_fn || !native_fn.has(key)) return this;
3197
- }
3198
- var args = [];
3199
- for (var i = 0, len = this.args.length; i < len; i++) {
3200
- var arg = this.args[i];
3201
- var value = arg._eval(compressor, depth);
3202
- if (arg === value) return this;
3203
- args.push(value);
3204
- }
3205
- try {
3206
- return val[key].apply(val, args);
3207
- } catch (ex) {
3208
- // We don't really care
3209
- }
3210
- }
3211
- return this;
3212
- });
3213
- def_eval(AST_New, return_this);
3214
- })(function(node, func) {
3215
- node.DEFMETHOD("_eval", func);
3216
- });
3217
-
3218
- // method to negate an expression
3219
- (function(def_negate) {
3220
- function basic_negation(exp) {
3221
- return make_node(AST_UnaryPrefix, exp, {
3222
- operator: "!",
3223
- expression: exp
3224
- });
3225
- }
3226
- function best(orig, alt, first_in_statement) {
3227
- var negated = basic_negation(orig);
3228
- if (first_in_statement) {
3229
- var stat = make_node(AST_SimpleStatement, alt, {
3230
- body: alt
3231
- });
3232
- return best_of_expression(negated, stat) === stat ? alt : negated;
3233
- }
3234
- return best_of_expression(negated, alt);
3235
- }
3236
- def_negate(AST_Node, function() {
3237
- return basic_negation(this);
3238
- });
3239
- def_negate(AST_Statement, function() {
3240
- throw new Error("Cannot negate a statement");
3241
- });
3242
- def_negate(AST_Function, function() {
3243
- return basic_negation(this);
3244
- });
3245
- def_negate(AST_Arrow, function() {
3246
- return basic_negation(this);
3247
- });
3248
- def_negate(AST_UnaryPrefix, function() {
3249
- if (this.operator == "!")
3250
- return this.expression;
3251
- return basic_negation(this);
3252
- });
3253
- def_negate(AST_Sequence, function(compressor) {
3254
- var expressions = this.expressions.slice();
3255
- expressions.push(expressions.pop().negate(compressor));
3256
- return make_sequence(this, expressions);
3257
- });
3258
- def_negate(AST_Conditional, function(compressor, first_in_statement) {
3259
- var self = this.clone();
3260
- self.consequent = self.consequent.negate(compressor);
3261
- self.alternative = self.alternative.negate(compressor);
3262
- return best(this, self, first_in_statement);
3263
- });
3264
- def_negate(AST_Binary, function(compressor, first_in_statement) {
3265
- var self = this.clone(), op = this.operator;
3266
- if (compressor.option("unsafe_comps")) {
3267
- switch (op) {
3268
- case "<=" : self.operator = ">" ; return self;
3269
- case "<" : self.operator = ">=" ; return self;
3270
- case ">=" : self.operator = "<" ; return self;
3271
- case ">" : self.operator = "<=" ; return self;
3272
- }
3273
- }
3274
- switch (op) {
3275
- case "==" : self.operator = "!="; return self;
3276
- case "!=" : self.operator = "=="; return self;
3277
- case "===": self.operator = "!=="; return self;
3278
- case "!==": self.operator = "==="; return self;
3279
- case "&&":
3280
- self.operator = "||";
3281
- self.left = self.left.negate(compressor, first_in_statement);
3282
- self.right = self.right.negate(compressor);
3283
- return best(this, self, first_in_statement);
3284
- case "||":
3285
- self.operator = "&&";
3286
- self.left = self.left.negate(compressor, first_in_statement);
3287
- self.right = self.right.negate(compressor);
3288
- return best(this, self, first_in_statement);
3289
- case "??":
3290
- self.right = self.right.negate(compressor);
3291
- return best(this, self, first_in_statement);
3292
- }
3293
- return basic_negation(this);
3294
- });
3295
- })(function(node, func) {
3296
- node.DEFMETHOD("negate", function(compressor, first_in_statement) {
3297
- return func.call(this, compressor, first_in_statement);
3298
- });
3299
- });
3300
-
3301
- var global_pure_fns = makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError");
3302
- AST_Call.DEFMETHOD("is_expr_pure", function(compressor) {
3303
- if (compressor.option("unsafe")) {
3304
- var expr = this.expression;
3305
- var first_arg = (this.args && this.args[0] && this.args[0].evaluate(compressor));
3306
- if (
3307
- expr.expression && expr.expression.name === "hasOwnProperty" &&
3308
- (first_arg == null || first_arg.thedef && first_arg.thedef.undeclared)
3309
- ) {
3310
- return false;
3311
- }
3312
- if (is_undeclared_ref(expr) && global_pure_fns.has(expr.name)) return true;
3313
- let static_fn;
3314
- if (expr instanceof AST_Dot
3315
- && is_undeclared_ref(expr.expression)
3316
- && (static_fn = static_fns.get(expr.expression.name))
3317
- && static_fn.has(expr.property)) {
3318
- return true;
3319
- }
3320
- }
3321
- return !!has_annotation(this, _PURE) || !compressor.pure_funcs(this);
3322
- });
3323
- AST_Node.DEFMETHOD("is_call_pure", return_false);
3324
- AST_Dot.DEFMETHOD("is_call_pure", function(compressor) {
3325
- if (!compressor.option("unsafe")) return;
3326
- const expr = this.expression;
3327
- let map;
3328
- if (expr instanceof AST_Array) {
3329
- map = native_fns.get("Array");
3330
- } else if (expr.is_boolean()) {
3331
- map = native_fns.get("Boolean");
3332
- } else if (expr.is_number(compressor)) {
3333
- map = native_fns.get("Number");
3334
- } else if (expr instanceof AST_RegExp) {
3335
- map = native_fns.get("RegExp");
3336
- } else if (expr.is_string(compressor)) {
3337
- map = native_fns.get("String");
3338
- } else if (!this.may_throw_on_access(compressor)) {
3339
- map = native_fns.get("Object");
3340
- }
3341
- return map && map.has(this.property);
3342
- });
3343
-
3344
- const pure_prop_access_globals = new Set([
3345
- "Number",
3346
- "String",
3347
- "Array",
3348
- "Object",
3349
- "Function",
3350
- "Promise",
3351
- ]);
3352
- // determine if expression has side effects
3353
- (function(def_has_side_effects) {
3354
- def_has_side_effects(AST_Node, return_true);
3355
-
3356
- def_has_side_effects(AST_EmptyStatement, return_false);
3357
- def_has_side_effects(AST_Constant, return_false);
3358
- def_has_side_effects(AST_This, return_false);
3359
-
3360
- function any(list, compressor) {
3361
- for (var i = list.length; --i >= 0;)
3362
- if (list[i].has_side_effects(compressor))
3363
- return true;
3364
- return false;
3365
- }
3366
-
3367
- def_has_side_effects(AST_Block, function(compressor) {
3368
- return any(this.body, compressor);
3369
- });
3370
- def_has_side_effects(AST_Call, function(compressor) {
3371
- if (
3372
- !this.is_expr_pure(compressor)
3373
- && (!this.expression.is_call_pure(compressor)
3374
- || this.expression.has_side_effects(compressor))
3375
- ) {
3376
- return true;
3377
- }
3378
- return any(this.args, compressor);
3379
- });
3380
- def_has_side_effects(AST_Switch, function(compressor) {
3381
- return this.expression.has_side_effects(compressor)
3382
- || any(this.body, compressor);
3383
- });
3384
- def_has_side_effects(AST_Case, function(compressor) {
3385
- return this.expression.has_side_effects(compressor)
3386
- || any(this.body, compressor);
3387
- });
3388
- def_has_side_effects(AST_Try, function(compressor) {
3389
- return any(this.body, compressor)
3390
- || this.bcatch && this.bcatch.has_side_effects(compressor)
3391
- || this.bfinally && this.bfinally.has_side_effects(compressor);
3392
- });
3393
- def_has_side_effects(AST_If, function(compressor) {
3394
- return this.condition.has_side_effects(compressor)
3395
- || this.body && this.body.has_side_effects(compressor)
3396
- || this.alternative && this.alternative.has_side_effects(compressor);
3397
- });
3398
- def_has_side_effects(AST_LabeledStatement, function(compressor) {
3399
- return this.body.has_side_effects(compressor);
3400
- });
3401
- def_has_side_effects(AST_SimpleStatement, function(compressor) {
3402
- return this.body.has_side_effects(compressor);
3403
- });
3404
- def_has_side_effects(AST_Lambda, return_false);
3405
- def_has_side_effects(AST_Class, function (compressor) {
3406
- if (this.extends && this.extends.has_side_effects(compressor)) {
3407
- return true;
3408
- }
3409
- return any(this.properties, compressor);
3410
- });
3411
- def_has_side_effects(AST_Binary, function(compressor) {
3412
- return this.left.has_side_effects(compressor)
3413
- || this.right.has_side_effects(compressor);
3414
- });
3415
- def_has_side_effects(AST_Assign, return_true);
3416
- def_has_side_effects(AST_Conditional, function(compressor) {
3417
- return this.condition.has_side_effects(compressor)
3418
- || this.consequent.has_side_effects(compressor)
3419
- || this.alternative.has_side_effects(compressor);
3420
- });
3421
- def_has_side_effects(AST_Unary, function(compressor) {
3422
- return unary_side_effects.has(this.operator)
3423
- || this.expression.has_side_effects(compressor);
3424
- });
3425
- def_has_side_effects(AST_SymbolRef, function(compressor) {
3426
- return !this.is_declared(compressor) && !pure_prop_access_globals.has(this.name);
3427
- });
3428
- def_has_side_effects(AST_SymbolClassProperty, return_false);
3429
- def_has_side_effects(AST_SymbolDeclaration, return_false);
3430
- def_has_side_effects(AST_Object, function(compressor) {
3431
- return any(this.properties, compressor);
3432
- });
3433
- def_has_side_effects(AST_ObjectProperty, function(compressor) {
3434
- return (
3435
- this.computed_key() && this.key.has_side_effects(compressor)
3436
- || this.value && this.value.has_side_effects(compressor)
3437
- );
3438
- });
3439
- def_has_side_effects(AST_ClassProperty, function(compressor) {
3440
- return (
3441
- this.computed_key() && this.key.has_side_effects(compressor)
3442
- || this.static && this.value && this.value.has_side_effects(compressor)
3443
- );
3444
- });
3445
- def_has_side_effects(AST_ConciseMethod, function(compressor) {
3446
- return this.computed_key() && this.key.has_side_effects(compressor);
3447
- });
3448
- def_has_side_effects(AST_ObjectGetter, function(compressor) {
3449
- return this.computed_key() && this.key.has_side_effects(compressor);
3450
- });
3451
- def_has_side_effects(AST_ObjectSetter, function(compressor) {
3452
- return this.computed_key() && this.key.has_side_effects(compressor);
3453
- });
3454
- def_has_side_effects(AST_Array, function(compressor) {
3455
- return any(this.elements, compressor);
3456
- });
3457
- def_has_side_effects(AST_Dot, function(compressor) {
3458
- return !this.optional && this.expression.may_throw_on_access(compressor)
3459
- || this.expression.has_side_effects(compressor);
3460
- });
3461
- def_has_side_effects(AST_Sub, function(compressor) {
3462
- if (this.optional && is_nullish(this.expression)) {
3463
- return false;
3464
- }
3465
-
3466
- return !this.optional && this.expression.may_throw_on_access(compressor)
3467
- || this.expression.has_side_effects(compressor)
3468
- || this.property.has_side_effects(compressor);
3469
- });
3470
- def_has_side_effects(AST_Chain, function (compressor) {
3471
- return this.expression.has_side_effects(compressor);
3472
- });
3473
- def_has_side_effects(AST_Sequence, function(compressor) {
3474
- return any(this.expressions, compressor);
3475
- });
3476
- def_has_side_effects(AST_Definitions, function(compressor) {
3477
- return any(this.definitions, compressor);
3478
- });
3479
- def_has_side_effects(AST_VarDef, function() {
3480
- return this.value;
3481
- });
3482
- def_has_side_effects(AST_TemplateSegment, return_false);
3483
- def_has_side_effects(AST_TemplateString, function(compressor) {
3484
- return any(this.segments, compressor);
3485
- });
3486
- })(function(node, func) {
3487
- node.DEFMETHOD("has_side_effects", func);
3488
- });
3489
-
3490
- // determine if expression may throw
3491
- (function(def_may_throw) {
3492
- def_may_throw(AST_Node, return_true);
3493
-
3494
- def_may_throw(AST_Constant, return_false);
3495
- def_may_throw(AST_EmptyStatement, return_false);
3496
- def_may_throw(AST_Lambda, return_false);
3497
- def_may_throw(AST_SymbolDeclaration, return_false);
3498
- def_may_throw(AST_This, return_false);
3499
-
3500
- function any(list, compressor) {
3501
- for (var i = list.length; --i >= 0;)
3502
- if (list[i].may_throw(compressor))
3503
- return true;
3504
- return false;
3505
- }
3506
-
3507
- def_may_throw(AST_Class, function(compressor) {
3508
- if (this.extends && this.extends.may_throw(compressor)) return true;
3509
- return any(this.properties, compressor);
3510
- });
3511
-
3512
- def_may_throw(AST_Array, function(compressor) {
3513
- return any(this.elements, compressor);
3514
- });
3515
- def_may_throw(AST_Assign, function(compressor) {
3516
- if (this.right.may_throw(compressor)) return true;
3517
- if (!compressor.has_directive("use strict")
3518
- && this.operator == "="
3519
- && this.left instanceof AST_SymbolRef) {
3520
- return false;
3521
- }
3522
- return this.left.may_throw(compressor);
3523
- });
3524
- def_may_throw(AST_Binary, function(compressor) {
3525
- return this.left.may_throw(compressor)
3526
- || this.right.may_throw(compressor);
3527
- });
3528
- def_may_throw(AST_Block, function(compressor) {
3529
- return any(this.body, compressor);
3530
- });
3531
- def_may_throw(AST_Call, function(compressor) {
3532
- if (this.optional && is_nullish(this.expression)) return false;
3533
- if (any(this.args, compressor)) return true;
3534
- if (this.is_expr_pure(compressor)) return false;
3535
- if (this.expression.may_throw(compressor)) return true;
3536
- return !(this.expression instanceof AST_Lambda)
3537
- || any(this.expression.body, compressor);
3538
- });
3539
- def_may_throw(AST_Case, function(compressor) {
3540
- return this.expression.may_throw(compressor)
3541
- || any(this.body, compressor);
3542
- });
3543
- def_may_throw(AST_Conditional, function(compressor) {
3544
- return this.condition.may_throw(compressor)
3545
- || this.consequent.may_throw(compressor)
3546
- || this.alternative.may_throw(compressor);
3547
- });
3548
- def_may_throw(AST_Definitions, function(compressor) {
3549
- return any(this.definitions, compressor);
3550
- });
3551
- def_may_throw(AST_If, function(compressor) {
3552
- return this.condition.may_throw(compressor)
3553
- || this.body && this.body.may_throw(compressor)
3554
- || this.alternative && this.alternative.may_throw(compressor);
3555
- });
3556
- def_may_throw(AST_LabeledStatement, function(compressor) {
3557
- return this.body.may_throw(compressor);
3558
- });
3559
- def_may_throw(AST_Object, function(compressor) {
3560
- return any(this.properties, compressor);
3561
- });
3562
- def_may_throw(AST_ObjectProperty, function(compressor) {
3563
- // TODO key may throw too
3564
- return this.value ? this.value.may_throw(compressor) : false;
3565
- });
3566
- def_may_throw(AST_ClassProperty, function(compressor) {
3567
- return (
3568
- this.computed_key() && this.key.may_throw(compressor)
3569
- || this.static && this.value && this.value.may_throw(compressor)
3570
- );
3571
- });
3572
- def_may_throw(AST_ConciseMethod, function(compressor) {
3573
- return this.computed_key() && this.key.may_throw(compressor);
3574
- });
3575
- def_may_throw(AST_ObjectGetter, function(compressor) {
3576
- return this.computed_key() && this.key.may_throw(compressor);
3577
- });
3578
- def_may_throw(AST_ObjectSetter, function(compressor) {
3579
- return this.computed_key() && this.key.may_throw(compressor);
3580
- });
3581
- def_may_throw(AST_Return, function(compressor) {
3582
- return this.value && this.value.may_throw(compressor);
3583
- });
3584
- def_may_throw(AST_Sequence, function(compressor) {
3585
- return any(this.expressions, compressor);
3586
- });
3587
- def_may_throw(AST_SimpleStatement, function(compressor) {
3588
- return this.body.may_throw(compressor);
3589
- });
3590
- def_may_throw(AST_Dot, function(compressor) {
3591
- return !this.optional && this.expression.may_throw_on_access(compressor)
3592
- || this.expression.may_throw(compressor);
3593
- });
3594
- def_may_throw(AST_Sub, function(compressor) {
3595
- if (this.optional && is_nullish(this.expression)) return false;
442
+ // following replacement call would result in degraded efficiency of both
443
+ // output and performance.
444
+ descend(node, this);
445
+ var opt = node.optimize(this);
446
+ if (was_scope && opt instanceof AST_Scope) {
447
+ opt.drop_unused(this);
448
+ descend(opt, this);
449
+ }
450
+ if (opt === node) set_flag(opt, SQUEEZED);
451
+ return opt;
452
+ }
453
+ }
3596
454
 
3597
- return !this.optional && this.expression.may_throw_on_access(compressor)
3598
- || this.expression.may_throw(compressor)
3599
- || this.property.may_throw(compressor);
3600
- });
3601
- def_may_throw(AST_Chain, function(compressor) {
3602
- return this.expression.may_throw(compressor);
3603
- });
3604
- def_may_throw(AST_Switch, function(compressor) {
3605
- return this.expression.may_throw(compressor)
3606
- || any(this.body, compressor);
3607
- });
3608
- def_may_throw(AST_SymbolRef, function(compressor) {
3609
- return !this.is_declared(compressor) && !pure_prop_access_globals.has(this.name);
3610
- });
3611
- def_may_throw(AST_SymbolClassProperty, return_false);
3612
- def_may_throw(AST_Try, function(compressor) {
3613
- return this.bcatch ? this.bcatch.may_throw(compressor) : any(this.body, compressor)
3614
- || this.bfinally && this.bfinally.may_throw(compressor);
3615
- });
3616
- def_may_throw(AST_Unary, function(compressor) {
3617
- if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef)
3618
- return false;
3619
- return this.expression.may_throw(compressor);
3620
- });
3621
- def_may_throw(AST_VarDef, function(compressor) {
3622
- if (!this.value) return false;
3623
- return this.value.may_throw(compressor);
455
+ function def_optimize(node, optimizer) {
456
+ node.DEFMETHOD("optimize", function(compressor) {
457
+ var self = this;
458
+ if (has_flag(self, OPTIMIZED)) return self;
459
+ if (compressor.has_directive("use asm")) return self;
460
+ var opt = optimizer(self, compressor);
461
+ set_flag(opt, OPTIMIZED);
462
+ return opt;
3624
463
  });
3625
- })(function(node, func) {
3626
- node.DEFMETHOD("may_throw", func);
464
+ }
465
+
466
+ def_optimize(AST_Node, function(self) {
467
+ return self;
3627
468
  });
3628
469
 
3629
- // determine if expression is constant
3630
- (function(def_is_constant_expression) {
3631
- function all_refs_local(scope) {
3632
- let result = true;
3633
- walk(this, node => {
3634
- if (node instanceof AST_SymbolRef) {
3635
- if (has_flag(this, INLINED)) {
3636
- result = false;
3637
- return walk_abort;
470
+ AST_Toplevel.DEFMETHOD("drop_console", function() {
471
+ return this.transform(new TreeTransformer(function(self) {
472
+ if (self.TYPE == "Call") {
473
+ var exp = self.expression;
474
+ if (exp instanceof AST_PropAccess) {
475
+ var name = exp.expression;
476
+ while (name.expression) {
477
+ name = name.expression;
3638
478
  }
3639
- var def = node.definition();
3640
- if (
3641
- member(def, this.enclosed)
3642
- && !this.variables.has(def.name)
3643
- ) {
3644
- if (scope) {
3645
- var scope_def = scope.find_variable(node);
3646
- if (def.undeclared ? !scope_def : scope_def === def) {
3647
- result = "f";
3648
- return true;
3649
- }
3650
- }
3651
- result = false;
3652
- return walk_abort;
479
+ if (is_undeclared_ref(name) && name.name == "console") {
480
+ return make_node(AST_Undefined, self);
3653
481
  }
3654
- return true;
3655
- }
3656
- if (node instanceof AST_This && this instanceof AST_Arrow) {
3657
- // TODO check arguments too!
3658
- result = false;
3659
- return walk_abort;
3660
482
  }
3661
- });
3662
- return result;
3663
- }
3664
-
3665
- def_is_constant_expression(AST_Node, return_false);
3666
- def_is_constant_expression(AST_Constant, return_true);
3667
- def_is_constant_expression(AST_Class, function(scope) {
3668
- if (this.extends && !this.extends.is_constant_expression(scope)) {
3669
- return false;
3670
483
  }
484
+ }));
485
+ });
3671
486
 
3672
- for (const prop of this.properties) {
3673
- if (prop.computed_key() && !prop.key.is_constant_expression(scope)) {
3674
- return false;
487
+ AST_Node.DEFMETHOD("equivalent_to", function(node) {
488
+ return equivalent_to(this, node);
489
+ });
490
+
491
+ AST_Scope.DEFMETHOD("process_expression", function(insert, compressor) {
492
+ var self = this;
493
+ var tt = new TreeTransformer(function(node) {
494
+ if (insert && node instanceof AST_SimpleStatement) {
495
+ return make_node(AST_Return, node, {
496
+ value: node.body
497
+ });
498
+ }
499
+ if (!insert && node instanceof AST_Return) {
500
+ if (compressor) {
501
+ var value = node.value && node.value.drop_side_effect_free(compressor, true);
502
+ return value
503
+ ? make_node(AST_SimpleStatement, node, { body: value })
504
+ : make_node(AST_EmptyStatement, node);
3675
505
  }
3676
- if (prop.static && prop.value && !prop.value.is_constant_expression(scope)) {
3677
- return false;
506
+ return make_node(AST_SimpleStatement, node, {
507
+ body: node.value || make_node(AST_UnaryPrefix, node, {
508
+ operator: "void",
509
+ expression: make_node(AST_Number, node, {
510
+ value: 0
511
+ })
512
+ })
513
+ });
514
+ }
515
+ if (node instanceof AST_Class || node instanceof AST_Lambda && node !== self) {
516
+ return node;
517
+ }
518
+ if (node instanceof AST_Block) {
519
+ var index = node.body.length - 1;
520
+ if (index >= 0) {
521
+ node.body[index] = node.body[index].transform(tt);
522
+ }
523
+ } else if (node instanceof AST_If) {
524
+ node.body = node.body.transform(tt);
525
+ if (node.alternative) {
526
+ node.alternative = node.alternative.transform(tt);
3678
527
  }
528
+ } else if (node instanceof AST_With) {
529
+ node.body = node.body.transform(tt);
3679
530
  }
3680
-
3681
- return all_refs_local.call(this, scope);
3682
- });
3683
- def_is_constant_expression(AST_Lambda, all_refs_local);
3684
- def_is_constant_expression(AST_Unary, function() {
3685
- return this.expression.is_constant_expression();
3686
- });
3687
- def_is_constant_expression(AST_Binary, function() {
3688
- return this.left.is_constant_expression()
3689
- && this.right.is_constant_expression();
3690
- });
3691
- def_is_constant_expression(AST_Array, function() {
3692
- return this.elements.every((l) => l.is_constant_expression());
3693
- });
3694
- def_is_constant_expression(AST_Object, function() {
3695
- return this.properties.every((l) => l.is_constant_expression());
531
+ return node;
3696
532
  });
3697
- def_is_constant_expression(AST_ObjectProperty, function() {
3698
- return !!(!(this.key instanceof AST_Node) && this.value && this.value.is_constant_expression());
533
+ self.transform(tt);
534
+ });
535
+
536
+ AST_Toplevel.DEFMETHOD("reset_opt_flags", function(compressor) {
537
+ const self = this;
538
+ const reduce_vars = compressor.option("reduce_vars");
539
+
540
+ const preparation = new TreeWalker(function(node, descend) {
541
+ clear_flag(node, CLEAR_BETWEEN_PASSES);
542
+ if (reduce_vars) {
543
+ if (compressor.top_retain
544
+ && node instanceof AST_Defun // Only functions are retained
545
+ && preparation.parent() === self
546
+ ) {
547
+ set_flag(node, TOP);
548
+ }
549
+ return node.reduce_vars(preparation, descend, compressor);
550
+ }
3699
551
  });
3700
- })(function(node, func) {
3701
- node.DEFMETHOD("is_constant_expression", func);
552
+ // Stack of look-up tables to keep track of whether a `SymbolDef` has been
553
+ // properly assigned before use:
554
+ // - `push()` & `pop()` when visiting conditional branches
555
+ preparation.safe_ids = Object.create(null);
556
+ preparation.in_loop = null;
557
+ preparation.loop_ids = new Map();
558
+ preparation.defs_to_safe_ids = new Map();
559
+ self.walk(preparation);
560
+ });
561
+
562
+ AST_Symbol.DEFMETHOD("fixed_value", function() {
563
+ var fixed = this.thedef.fixed;
564
+ if (!fixed || fixed instanceof AST_Node) return fixed;
565
+ return fixed();
566
+ });
567
+
568
+ AST_SymbolRef.DEFMETHOD("is_immutable", function() {
569
+ var orig = this.definition().orig;
570
+ return orig.length == 1 && orig[0] instanceof AST_SymbolLambda;
3702
571
  });
3703
572
 
3704
- // tell me if a statement aborts
3705
- function aborts(thing) {
3706
- return thing && thing.aborts();
573
+ function find_scope(tw) {
574
+ for (let i = 0;;i++) {
575
+ const p = tw.parent(i);
576
+ if (p instanceof AST_Toplevel) return p;
577
+ if (p instanceof AST_Lambda) return p;
578
+ if (p.block_scope) return p.block_scope;
579
+ }
3707
580
  }
3708
- (function(def_aborts) {
3709
- def_aborts(AST_Statement, return_null);
3710
- def_aborts(AST_Jump, return_this);
3711
- function block_aborts() {
3712
- for (var i = 0; i < this.body.length; i++) {
3713
- if (aborts(this.body[i])) {
3714
- return this.body[i];
3715
- }
581
+
582
+ function find_variable(compressor, name) {
583
+ var scope, i = 0;
584
+ while (scope = compressor.parent(i++)) {
585
+ if (scope instanceof AST_Scope) break;
586
+ if (scope instanceof AST_Catch && scope.argname) {
587
+ scope = scope.argname.definition().scope;
588
+ break;
3716
589
  }
3717
- return null;
3718
590
  }
3719
- def_aborts(AST_Import, function() { return null; });
3720
- def_aborts(AST_BlockStatement, block_aborts);
3721
- def_aborts(AST_SwitchBranch, block_aborts);
3722
- def_aborts(AST_If, function() {
3723
- return this.alternative && aborts(this.body) && aborts(this.alternative) && this;
3724
- });
3725
- })(function(node, func) {
3726
- node.DEFMETHOD("aborts", func);
591
+ return scope.find_variable(name);
592
+ }
593
+
594
+ function is_empty(thing) {
595
+ if (thing === null) return true;
596
+ if (thing instanceof AST_EmptyStatement) return true;
597
+ if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
598
+ return false;
599
+ }
600
+
601
+ var global_names = makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");
602
+ AST_SymbolRef.DEFMETHOD("is_declared", function(compressor) {
603
+ return !this.definition().undeclared
604
+ || compressor.option("unsafe") && global_names.has(this.name);
3727
605
  });
3728
606
 
3729
607
  /* -----[ optimizers ]----- */
@@ -4365,7 +1243,7 @@ AST_Scope.DEFMETHOD("hoist_properties", function(compressor) {
4365
1243
  ) {
4366
1244
  const defs = defs_by_id.get(node.expression.definition().id);
4367
1245
  if (defs) {
4368
- const def = defs.get(String(get_value(node.property)));
1246
+ const def = defs.get(String(get_simple_key(node.property)));
4369
1247
  const sym = make_node(AST_SymbolRef, node, {
4370
1248
  name: def.name,
4371
1249
  scope: node.expression.scope,
@@ -4379,223 +1257,6 @@ AST_Scope.DEFMETHOD("hoist_properties", function(compressor) {
4379
1257
  return self.transform(hoister);
4380
1258
  });
4381
1259
 
4382
- // drop_side_effect_free()
4383
- // remove side-effect-free parts which only affects return value
4384
- (function(def_drop_side_effect_free) {
4385
- // Drop side-effect-free elements from an array of expressions.
4386
- // Returns an array of expressions with side-effects or null
4387
- // if all elements were dropped. Note: original array may be
4388
- // returned if nothing changed.
4389
- function trim(nodes, compressor, first_in_statement) {
4390
- var len = nodes.length;
4391
- if (!len) return null;
4392
- var ret = [], changed = false;
4393
- for (var i = 0; i < len; i++) {
4394
- var node = nodes[i].drop_side_effect_free(compressor, first_in_statement);
4395
- changed |= node !== nodes[i];
4396
- if (node) {
4397
- ret.push(node);
4398
- first_in_statement = false;
4399
- }
4400
- }
4401
- return changed ? ret.length ? ret : null : nodes;
4402
- }
4403
-
4404
- def_drop_side_effect_free(AST_Node, return_this);
4405
- def_drop_side_effect_free(AST_Constant, return_null);
4406
- def_drop_side_effect_free(AST_This, return_null);
4407
- def_drop_side_effect_free(AST_Call, function(compressor, first_in_statement) {
4408
- if (this.optional && is_nullish(this.expression)) {
4409
- return make_node(AST_Undefined, this);
4410
- }
4411
-
4412
- if (!this.is_expr_pure(compressor)) {
4413
- if (this.expression.is_call_pure(compressor)) {
4414
- var exprs = this.args.slice();
4415
- exprs.unshift(this.expression.expression);
4416
- exprs = trim(exprs, compressor, first_in_statement);
4417
- return exprs && make_sequence(this, exprs);
4418
- }
4419
- if (is_func_expr(this.expression)
4420
- && (!this.expression.name || !this.expression.name.definition().references.length)) {
4421
- var node = this.clone();
4422
- node.expression.process_expression(false, compressor);
4423
- return node;
4424
- }
4425
- return this;
4426
- }
4427
- var args = trim(this.args, compressor, first_in_statement);
4428
- return args && make_sequence(this, args);
4429
- });
4430
- def_drop_side_effect_free(AST_Accessor, return_null);
4431
- def_drop_side_effect_free(AST_Function, return_null);
4432
- def_drop_side_effect_free(AST_Arrow, return_null);
4433
- def_drop_side_effect_free(AST_Class, function (compressor) {
4434
- const with_effects = [];
4435
- const trimmed_extends = this.extends && this.extends.drop_side_effect_free(compressor);
4436
- if (trimmed_extends) with_effects.push(trimmed_extends);
4437
- for (const prop of this.properties) {
4438
- const trimmed_prop = prop.drop_side_effect_free(compressor);
4439
- if (trimmed_prop) with_effects.push(trimmed_prop);
4440
- }
4441
- if (!with_effects.length) return null;
4442
- return make_sequence(this, with_effects);
4443
- });
4444
- def_drop_side_effect_free(AST_Binary, function(compressor, first_in_statement) {
4445
- var right = this.right.drop_side_effect_free(compressor);
4446
- if (!right) return this.left.drop_side_effect_free(compressor, first_in_statement);
4447
- if (lazy_op.has(this.operator)) {
4448
- if (right === this.right) return this;
4449
- var node = this.clone();
4450
- node.right = right;
4451
- return node;
4452
- } else {
4453
- var left = this.left.drop_side_effect_free(compressor, first_in_statement);
4454
- if (!left) return this.right.drop_side_effect_free(compressor, first_in_statement);
4455
- return make_sequence(this, [ left, right ]);
4456
- }
4457
- });
4458
- def_drop_side_effect_free(AST_Assign, function(compressor) {
4459
- if (this.logical) return this;
4460
-
4461
- var left = this.left;
4462
- if (left.has_side_effects(compressor)
4463
- || compressor.has_directive("use strict")
4464
- && left instanceof AST_PropAccess
4465
- && left.expression.is_constant()) {
4466
- return this;
4467
- }
4468
- set_flag(this, WRITE_ONLY);
4469
- while (left instanceof AST_PropAccess) {
4470
- left = left.expression;
4471
- }
4472
- if (left.is_constant_expression(compressor.find_parent(AST_Scope))) {
4473
- return this.right.drop_side_effect_free(compressor);
4474
- }
4475
- return this;
4476
- });
4477
- def_drop_side_effect_free(AST_Conditional, function(compressor) {
4478
- var consequent = this.consequent.drop_side_effect_free(compressor);
4479
- var alternative = this.alternative.drop_side_effect_free(compressor);
4480
- if (consequent === this.consequent && alternative === this.alternative) return this;
4481
- if (!consequent) return alternative ? make_node(AST_Binary, this, {
4482
- operator: "||",
4483
- left: this.condition,
4484
- right: alternative
4485
- }) : this.condition.drop_side_effect_free(compressor);
4486
- if (!alternative) return make_node(AST_Binary, this, {
4487
- operator: "&&",
4488
- left: this.condition,
4489
- right: consequent
4490
- });
4491
- var node = this.clone();
4492
- node.consequent = consequent;
4493
- node.alternative = alternative;
4494
- return node;
4495
- });
4496
- def_drop_side_effect_free(AST_Unary, function(compressor, first_in_statement) {
4497
- if (unary_side_effects.has(this.operator)) {
4498
- if (!this.expression.has_side_effects(compressor)) {
4499
- set_flag(this, WRITE_ONLY);
4500
- } else {
4501
- clear_flag(this, WRITE_ONLY);
4502
- }
4503
- return this;
4504
- }
4505
- if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef) return null;
4506
- var expression = this.expression.drop_side_effect_free(compressor, first_in_statement);
4507
- if (first_in_statement && expression && is_iife_call(expression)) {
4508
- if (expression === this.expression && this.operator == "!") return this;
4509
- return expression.negate(compressor, first_in_statement);
4510
- }
4511
- return expression;
4512
- });
4513
- def_drop_side_effect_free(AST_SymbolRef, function(compressor) {
4514
- const safe_access = this.is_declared(compressor)
4515
- || pure_prop_access_globals.has(this.name);
4516
- return safe_access ? null : this;
4517
- });
4518
- def_drop_side_effect_free(AST_Object, function(compressor, first_in_statement) {
4519
- var values = trim(this.properties, compressor, first_in_statement);
4520
- return values && make_sequence(this, values);
4521
- });
4522
- def_drop_side_effect_free(AST_ObjectProperty, function(compressor, first_in_statement) {
4523
- const computed_key = this instanceof AST_ObjectKeyVal && this.key instanceof AST_Node;
4524
- const key = computed_key && this.key.drop_side_effect_free(compressor, first_in_statement);
4525
- const value = this.value && this.value.drop_side_effect_free(compressor, first_in_statement);
4526
- if (key && value) {
4527
- return make_sequence(this, [key, value]);
4528
- }
4529
- return key || value;
4530
- });
4531
- def_drop_side_effect_free(AST_ClassProperty, function (compressor) {
4532
- const key = this.computed_key() && this.key.drop_side_effect_free(compressor);
4533
-
4534
- const value = this.static && this.value
4535
- && this.value.drop_side_effect_free(compressor);
4536
-
4537
- if (key && value) return make_sequence(this, [key, value]);
4538
- return key || value || null;
4539
- });
4540
- def_drop_side_effect_free(AST_ConciseMethod, function () {
4541
- return this.computed_key() ? this.key : null;
4542
- });
4543
- def_drop_side_effect_free(AST_ObjectGetter, function () {
4544
- return this.computed_key() ? this.key : null;
4545
- });
4546
- def_drop_side_effect_free(AST_ObjectSetter, function () {
4547
- return this.computed_key() ? this.key : null;
4548
- });
4549
- def_drop_side_effect_free(AST_Array, function(compressor, first_in_statement) {
4550
- var values = trim(this.elements, compressor, first_in_statement);
4551
- return values && make_sequence(this, values);
4552
- });
4553
- def_drop_side_effect_free(AST_Dot, function(compressor, first_in_statement) {
4554
- if (this.optional) {
4555
- return is_nullish(this.expression) ? make_node(AST_Undefined, this) : this;
4556
- }
4557
- if (this.expression.may_throw_on_access(compressor)) return this;
4558
-
4559
- return this.expression.drop_side_effect_free(compressor, first_in_statement);
4560
- });
4561
- def_drop_side_effect_free(AST_Sub, function(compressor, first_in_statement) {
4562
- if (this.optional) {
4563
- return is_nullish(this.expression) ? make_node(AST_Undefined, this): this;
4564
- }
4565
- if (this.expression.may_throw_on_access(compressor)) return this;
4566
-
4567
- var expression = this.expression.drop_side_effect_free(compressor, first_in_statement);
4568
- if (!expression) return this.property.drop_side_effect_free(compressor, first_in_statement);
4569
- var property = this.property.drop_side_effect_free(compressor);
4570
- if (!property) return expression;
4571
- return make_sequence(this, [ expression, property ]);
4572
- });
4573
- def_drop_side_effect_free(AST_Chain, function (compressor, first_in_statement) {
4574
- return this.expression.drop_side_effect_free(compressor, first_in_statement);
4575
- });
4576
- def_drop_side_effect_free(AST_Sequence, function(compressor) {
4577
- var last = this.tail_node();
4578
- var expr = last.drop_side_effect_free(compressor);
4579
- if (expr === last) return this;
4580
- var expressions = this.expressions.slice(0, -1);
4581
- if (expr) expressions.push(expr);
4582
- if (!expressions.length) {
4583
- return make_node(AST_Number, this, { value: 0 });
4584
- }
4585
- return make_sequence(this, expressions);
4586
- });
4587
- def_drop_side_effect_free(AST_Expansion, function(compressor, first_in_statement) {
4588
- return this.expression.drop_side_effect_free(compressor, first_in_statement);
4589
- });
4590
- def_drop_side_effect_free(AST_TemplateSegment, return_null);
4591
- def_drop_side_effect_free(AST_TemplateString, function(compressor) {
4592
- var values = trim(this.segments, compressor, first_in_statement);
4593
- return values && make_sequence(this, values);
4594
- });
4595
- })(function(node, func) {
4596
- node.DEFMETHOD("drop_side_effect_free", func);
4597
- });
4598
-
4599
1260
  def_optimize(AST_SimpleStatement, function(self, compressor) {
4600
1261
  if (compressor.option("side_effects")) {
4601
1262
  var body = self.body;
@@ -4614,20 +1275,6 @@ def_optimize(AST_While, function(self, compressor) {
4614
1275
  return compressor.option("loops") ? make_node(AST_For, self, self).optimize(compressor) : self;
4615
1276
  });
4616
1277
 
4617
- function has_break_or_continue(loop, parent) {
4618
- var found = false;
4619
- var tw = new TreeWalker(function(node) {
4620
- if (found || node instanceof AST_Scope) return true;
4621
- if (node instanceof AST_LoopControl && tw.loopcontrol_target(node) === loop) {
4622
- return found = true;
4623
- }
4624
- });
4625
- if (parent instanceof AST_LabeledStatement) tw.push(parent);
4626
- tw.push(loop);
4627
- loop.body.walk(tw);
4628
- return found;
4629
- }
4630
-
4631
1278
  def_optimize(AST_Do, function(self, compressor) {
4632
1279
  if (!compressor.option("loops")) return self;
4633
1280
  var cond = self.condition.tail_node().evaluate(compressor);
@@ -5085,11 +1732,11 @@ def_optimize(AST_Definitions, function(self) {
5085
1732
  return self;
5086
1733
  });
5087
1734
 
5088
- def_optimize(AST_VarDef, function(self) {
1735
+ def_optimize(AST_VarDef, function(self, compressor) {
5089
1736
  if (
5090
1737
  self.name instanceof AST_SymbolLet
5091
1738
  && self.value != null
5092
- && is_undefined(self.value)
1739
+ && is_undefined(self.value, compressor)
5093
1740
  ) {
5094
1741
  self.value = null;
5095
1742
  }
@@ -5127,7 +1774,7 @@ def_optimize(AST_Call, function(self, compressor) {
5127
1774
  }
5128
1775
  }
5129
1776
 
5130
- if (self.optional && is_nullish(fn)) {
1777
+ if (self.optional && is_nullish(fn, compressor)) {
5131
1778
  return make_node(AST_Undefined, self);
5132
1779
  }
5133
1780
 
@@ -5429,7 +2076,7 @@ def_optimize(AST_Call, function(self, compressor) {
5429
2076
 
5430
2077
  var stat = is_func && fn.body[0];
5431
2078
  var is_regular_func = is_func && !fn.is_generator && !fn.async;
5432
- var can_inline = is_regular_func && compressor.option("inline") && !self.is_expr_pure(compressor);
2079
+ var can_inline = is_regular_func && compressor.option("inline") && !self.is_callee_pure(compressor);
5433
2080
  if (can_inline && stat instanceof AST_Return) {
5434
2081
  let returned = stat.value;
5435
2082
  if (!returned || returned.is_constant_expression()) {
@@ -5489,7 +2136,7 @@ def_optimize(AST_Call, function(self, compressor) {
5489
2136
  || has_annotation(self, _INLINE)
5490
2137
  || compressor.option("unused")
5491
2138
  && (def = exp.definition()).references.length == 1
5492
- && !recursive_ref(compressor, def)
2139
+ && !is_recursive_ref(compressor, def)
5493
2140
  && fn.is_constant_expression(exp.scope))
5494
2141
  && !has_annotation(self, _PURE | _NOINLINE)
5495
2142
  && !fn.contains_this()
@@ -5739,12 +2386,14 @@ def_optimize(AST_Call, function(self, compressor) {
5739
2386
  flatten_args(decls, expressions);
5740
2387
  flatten_vars(decls, expressions);
5741
2388
  expressions.push(returned_value);
2389
+
5742
2390
  if (decls.length) {
5743
2391
  const i = scope.body.indexOf(compressor.parent(level - 1)) + 1;
5744
2392
  scope.body.splice(i, 0, make_node(AST_Var, fn, {
5745
2393
  definitions: decls
5746
2394
  }));
5747
2395
  }
2396
+
5748
2397
  return expressions.map(exp => exp.clone(true));
5749
2398
  }
5750
2399
  });
@@ -6153,7 +2802,7 @@ def_optimize(AST_Binary, function(self, compressor) {
6153
2802
  }
6154
2803
  break;
6155
2804
  case "??":
6156
- if (is_nullish(self.left)) {
2805
+ if (is_nullish(self.left, compressor)) {
6157
2806
  return self.right;
6158
2807
  }
6159
2808
 
@@ -6399,20 +3048,6 @@ def_optimize(AST_SymbolExport, function(self) {
6399
3048
  return self;
6400
3049
  });
6401
3050
 
6402
- function recursive_ref(compressor, def) {
6403
- var node;
6404
- for (var i = 0; node = compressor.parent(i); i++) {
6405
- if (
6406
- node instanceof AST_Lambda
6407
- || node instanceof AST_Class
6408
- ) {
6409
- var name = node.name;
6410
- if (name && name.definition() === def) break;
6411
- }
6412
- }
6413
- return node;
6414
- }
6415
-
6416
3051
  function within_array_or_object_literal(compressor) {
6417
3052
  var node, level = 0;
6418
3053
  while (node = compressor.parent(level++)) {
@@ -6455,21 +3090,28 @@ def_optimize(AST_SymbolRef, function(self, compressor) {
6455
3090
  let fixed = self.fixed_value();
6456
3091
  let single_use = def.single_use
6457
3092
  && !(parent instanceof AST_Call
6458
- && (parent.is_expr_pure(compressor))
3093
+ && (parent.is_callee_pure(compressor))
6459
3094
  || has_annotation(parent, _NOINLINE))
6460
3095
  && !(parent instanceof AST_Export
6461
3096
  && fixed instanceof AST_Lambda
6462
3097
  && fixed.name);
6463
3098
 
3099
+ if (single_use && fixed instanceof AST_Node) {
3100
+ single_use =
3101
+ !fixed.has_side_effects(compressor)
3102
+ && !fixed.may_throw(compressor);
3103
+ }
3104
+
6464
3105
  if (single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) {
6465
3106
  if (retain_top_func(fixed, compressor)) {
6466
3107
  single_use = false;
6467
3108
  } else if (def.scope !== self.scope
6468
3109
  && (def.escaped == 1
6469
3110
  || has_flag(fixed, INLINED)
6470
- || within_array_or_object_literal(compressor))) {
3111
+ || within_array_or_object_literal(compressor)
3112
+ || !compressor.option("reduce_funcs"))) {
6471
3113
  single_use = false;
6472
- } else if (recursive_ref(compressor, def)) {
3114
+ } else if (is_recursive_ref(compressor, def)) {
6473
3115
  single_use = false;
6474
3116
  } else if (def.scope !== self.scope || def.orig[0] instanceof AST_SymbolFunarg) {
6475
3117
  single_use = fixed.is_constant_expression(self.scope);
@@ -6483,6 +3125,7 @@ def_optimize(AST_SymbolRef, function(self, compressor) {
6483
3125
  }
6484
3126
  }
6485
3127
  }
3128
+
6486
3129
  if (single_use && fixed instanceof AST_Lambda) {
6487
3130
  single_use =
6488
3131
  def.scope === self.scope
@@ -6492,15 +3135,6 @@ def_optimize(AST_SymbolRef, function(self, compressor) {
6492
3135
  && !scope_encloses_variables_in_this_scope(nearest_scope, fixed)
6493
3136
  && !(fixed.name && fixed.name.definition().recursive_refs > 0);
6494
3137
  }
6495
- if (single_use && fixed instanceof AST_Class) {
6496
- const extends_inert = !fixed.extends
6497
- || !fixed.extends.may_throw(compressor)
6498
- && !fixed.extends.has_side_effects(compressor);
6499
- single_use = extends_inert
6500
- && !fixed.properties.some(prop =>
6501
- prop.may_throw(compressor) || prop.has_side_effects(compressor)
6502
- );
6503
- }
6504
3138
 
6505
3139
  if (single_use && fixed) {
6506
3140
  if (fixed instanceof AST_DefClass) {
@@ -6577,6 +3211,7 @@ def_optimize(AST_SymbolRef, function(self, compressor) {
6577
3211
  }
6578
3212
  }
6579
3213
  }
3214
+
6580
3215
  return self;
6581
3216
  });
6582
3217
 
@@ -6761,23 +3396,6 @@ def_optimize(AST_DefaultAssign, function(self, compressor) {
6761
3396
  return self;
6762
3397
  });
6763
3398
 
6764
- function is_nullish(node) {
6765
- let fixed;
6766
- return (
6767
- node instanceof AST_Null
6768
- || is_undefined(node)
6769
- || (
6770
- node instanceof AST_SymbolRef
6771
- && (fixed = node.definition().fixed) instanceof AST_Node
6772
- && is_nullish(fixed)
6773
- )
6774
- // Recurse into those optional chains!
6775
- || node instanceof AST_PropAccess && node.optional && is_nullish(node.expression)
6776
- || node instanceof AST_Call && node.optional && is_nullish(node.expression)
6777
- || node instanceof AST_Chain && is_nullish(node.expression)
6778
- );
6779
- }
6780
-
6781
3399
  function is_nullish_check(check, check_subject, compressor) {
6782
3400
  if (check_subject.may_throw(compressor)) return false;
6783
3401
 
@@ -6789,8 +3407,8 @@ function is_nullish_check(check, check_subject, compressor) {
6789
3407
  && check.operator === "=="
6790
3408
  // which side is nullish?
6791
3409
  && (
6792
- (nullish_side = is_nullish(check.left) && check.left)
6793
- || (nullish_side = is_nullish(check.right) && check.right)
3410
+ (nullish_side = is_nullish(check.left, compressor) && check.left)
3411
+ || (nullish_side = is_nullish(check.right, compressor) && check.right)
6794
3412
  )
6795
3413
  // is the other side the same as the check_subject
6796
3414
  && (
@@ -6828,12 +3446,12 @@ function is_nullish_check(check, check_subject, compressor) {
6828
3446
  null_cmp = cmp;
6829
3447
  defined_side = cmp.left;
6830
3448
  }
6831
- if (is_undefined(cmp.left)) {
3449
+ if (is_undefined(cmp.left, compressor)) {
6832
3450
  found++;
6833
3451
  undefined_cmp = cmp;
6834
3452
  defined_side = cmp.right;
6835
3453
  }
6836
- if (is_undefined(cmp.right)) {
3454
+ if (is_undefined(cmp.right, compressor)) {
6837
3455
  found++;
6838
3456
  undefined_cmp = cmp;
6839
3457
  defined_side = cmp.left;
@@ -7028,7 +3646,8 @@ def_optimize(AST_Conditional, function(self, compressor) {
7028
3646
  right: alternative
7029
3647
  }).optimize(compressor);
7030
3648
  }
7031
- var in_bool = compressor.in_boolean_context();
3649
+
3650
+ const in_bool = compressor.in_boolean_context();
7032
3651
  if (is_true(self.consequent)) {
7033
3652
  if (is_false(self.alternative)) {
7034
3653
  // c ? true : false ---> !!c
@@ -7163,27 +3782,40 @@ function safe_to_flatten(value, compressor) {
7163
3782
 
7164
3783
  AST_PropAccess.DEFMETHOD("flatten_object", function(key, compressor) {
7165
3784
  if (!compressor.option("properties")) return;
3785
+ if (key === "__proto__") return;
3786
+
7166
3787
  var arrows = compressor.option("unsafe_arrows") && compressor.option("ecma") >= 2015;
7167
3788
  var expr = this.expression;
7168
3789
  if (expr instanceof AST_Object) {
7169
3790
  var props = expr.properties;
3791
+
7170
3792
  for (var i = props.length; --i >= 0;) {
7171
3793
  var prop = props[i];
3794
+
7172
3795
  if ("" + (prop instanceof AST_ConciseMethod ? prop.key.name : prop.key) == key) {
7173
- if (!props.every((prop) => {
7174
- return prop instanceof AST_ObjectKeyVal
7175
- || arrows && prop instanceof AST_ConciseMethod && !prop.is_generator;
7176
- })) break;
7177
- if (!safe_to_flatten(prop.value, compressor)) break;
3796
+ const all_props_flattenable = props.every((p) =>
3797
+ (p instanceof AST_ObjectKeyVal
3798
+ || arrows && p instanceof AST_ConciseMethod && !p.is_generator
3799
+ )
3800
+ && !p.computed_key()
3801
+ );
3802
+
3803
+ if (!all_props_flattenable) return;
3804
+ if (!safe_to_flatten(prop.value, compressor)) return;
3805
+
7178
3806
  return make_node(AST_Sub, this, {
7179
3807
  expression: make_node(AST_Array, expr, {
7180
3808
  elements: props.map(function(prop) {
7181
3809
  var v = prop.value;
7182
- if (v instanceof AST_Accessor) v = make_node(AST_Function, v, v);
3810
+ if (v instanceof AST_Accessor) {
3811
+ v = make_node(AST_Function, v, v);
3812
+ }
3813
+
7183
3814
  var k = prop.key;
7184
3815
  if (k instanceof AST_Node && !(k instanceof AST_SymbolMethod)) {
7185
3816
  return make_sequence(prop, [ k, v ]);
7186
3817
  }
3818
+
7187
3819
  return v;
7188
3820
  })
7189
3821
  }),
@@ -7321,7 +3953,7 @@ def_optimize(AST_Sub, function(self, compressor) {
7321
3953
  ev = make_node_from_constant(ev, self).optimize(compressor);
7322
3954
  return best_of(compressor, ev, self);
7323
3955
  }
7324
- if (self.optional && is_nullish(self.expression)) {
3956
+ if (self.optional && is_nullish(self.expression, compressor)) {
7325
3957
  return make_node(AST_Undefined, self);
7326
3958
  }
7327
3959
  return self;
@@ -7395,7 +4027,7 @@ def_optimize(AST_Dot, function(self, compressor) {
7395
4027
  ev = make_node_from_constant(ev, self).optimize(compressor);
7396
4028
  return best_of(compressor, ev, self);
7397
4029
  }
7398
- if (self.optional && is_nullish(self.expression)) {
4030
+ if (self.optional && is_nullish(self.expression, compressor)) {
7399
4031
  return make_node(AST_Undefined, self);
7400
4032
  }
7401
4033
  return self;
@@ -7439,7 +4071,7 @@ def_optimize(AST_Array, function(self, compressor) {
7439
4071
  return self;
7440
4072
  });
7441
4073
 
7442
- function inline_object_prop_spread(props) {
4074
+ function inline_object_prop_spread(props, compressor) {
7443
4075
  for (var i = 0; i < props.length; i++) {
7444
4076
  var prop = props[i];
7445
4077
  if (prop instanceof AST_Expansion) {
@@ -7457,6 +4089,9 @@ function inline_object_prop_spread(props) {
7457
4089
  // non-iterable value silently does nothing; it is thus safe
7458
4090
  // to remove. AST_String is the only iterable AST_Constant.
7459
4091
  props.splice(i, 1);
4092
+ } else if (is_nullish(expr, compressor)) {
4093
+ // Likewise, null and undefined can be silently removed.
4094
+ props.splice(i, 1);
7460
4095
  }
7461
4096
  }
7462
4097
  }
@@ -7467,7 +4102,7 @@ def_optimize(AST_Object, function(self, compressor) {
7467
4102
  if (optimized !== self) {
7468
4103
  return optimized;
7469
4104
  }
7470
- inline_object_prop_spread(self.properties);
4105
+ inline_object_prop_spread(self.properties, compressor);
7471
4106
  return self;
7472
4107
  });
7473
4108
 
@@ -7560,7 +4195,7 @@ def_optimize(AST_TemplateString, function(self, compressor) {
7560
4195
  && (
7561
4196
  segments[1].is_string(compressor)
7562
4197
  || segments[1].is_number(compressor)
7563
- || is_nullish(segments[1])
4198
+ || is_nullish(segments[1], compressor)
7564
4199
  || compressor.option("unsafe")
7565
4200
  )
7566
4201
  ) {