-
-
Notifications
You must be signed in to change notification settings - Fork 225
/
index.js
1348 lines (1167 loc) · 39.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
const some = require("lodash/some");
const { markEvalScopes, hasEval } = require("babel-helper-mark-eval-scopes");
const removeUseStrict = require("./remove-use-strict");
const evaluate = require("babel-helper-evaluate-path");
function evaluateTruthy(path) {
const res = evaluate(path);
if (res.confident) return !!res.value;
}
function prevSiblings(path) {
const parentPath = path.parentPath;
const siblings = [];
let key = parentPath.key;
while ((path = parentPath.getSibling(--key)).type) {
siblings.push(path);
}
return siblings;
}
function forEachAncestor(path, callback) {
while ((path = path.parentPath)) {
callback(path);
}
}
module.exports = ({ types: t, traverse }) => {
const removeOrVoid = require("babel-helper-remove-or-void")(t);
const shouldRevisit = Symbol("shouldRevisit");
// this is used for tracking fn params that can be removed
// as traversal takes place from left and
// unused params can be removed only on the right
const markForRemoval = Symbol("markForRemoval");
const main = {
// remove side effectless statement
ExpressionStatement(path) {
if (path.get("expression").isPure()) {
removeOrVoid(path);
}
},
Function: {
// Let's take all the vars in a function that are not in the top level scope and hoist them
// with the first var declaration in the top-level scope. This transform in itself may
// not yield much returns (or even can be marginally harmful to size). However it's great
// for taking away statements from blocks that can be only expressions which the `simplify`
// plugin can turn into other things (e.g. if => conditional).
exit(path) {
// This hurts gzip size.
if (!this.optimizeRawSize) {
return;
}
const { node, scope } = path;
const seen = new Set();
const declars = [];
const mutations = [];
for (const name in scope.bindings) {
const binding = scope.bindings[name];
if (!binding.path.isVariableDeclarator()) {
continue;
}
const declarPath = binding.path.parentPath;
if (seen.has(declarPath)) {
continue;
}
seen.add(declarPath);
if (declarPath.parentPath.isForInStatement()) {
continue;
}
if (declarPath.parentPath.parentPath.isFunction()) {
continue;
}
if (!declarPath.node || !declarPath.node.declarations) {
continue;
}
const assignmentSequence = [];
for (const declar of declarPath.node.declarations) {
declars.push(declar);
if (declar.init) {
assignmentSequence.push(
t.assignmentExpression("=", declar.id, declar.init)
);
mutations.push(() => {
declar.init = null;
});
}
}
if (assignmentSequence.length) {
mutations.push(() =>
declarPath.replaceWith(t.sequenceExpression(assignmentSequence))
);
} else {
mutations.push(() => removeOrVoid(declarPath));
}
}
if (declars.length) {
mutations.forEach(f => f());
for (const statement of node.body.body) {
if (t.isVariableDeclaration(statement)) {
statement.declarations.push(...declars);
return;
}
}
const varDecl = t.variableDeclaration("var", declars);
node.body.body.unshift(varDecl);
}
}
},
// Remove bindings with no references.
Scope: {
exit(path) {
if (path.node[shouldRevisit]) {
delete path.node[shouldRevisit];
path.visit();
}
},
enter(path) {
if (path.isProgram()) {
return;
}
if (hasEval(path.scope)) {
return;
}
const { scope } = path;
// if the scope is created by a function, we obtain its
// parameter list
const canRemoveParams = path.isFunction() && path.node.kind !== "set";
const paramsList = canRemoveParams ? path.get("params") : [];
for (let i = paramsList.length - 1; i >= 0; i--) {
const param = paramsList[i];
if (param.isIdentifier()) {
const binding = scope.bindings[param.node.name];
if (!binding) continue;
if (binding.referenced) {
// when the first binding is referenced (right to left)
// exit without marking anything after this
break;
}
binding[markForRemoval] = true;
continue;
} else if (param.isAssignmentPattern()) {
const left = param.get("left");
const right = param.get("right");
if (left.isIdentifier() && right.isPure()) {
const binding = scope.bindings[left.node.name];
if (binding.referenced) {
// when the first binding is referenced (right to left)
// exit without marking anything after this
break;
}
binding[markForRemoval] = true;
continue;
}
}
// other patterns - assignment, object have side-effects
// and cannot be safely removed
break;
}
for (const name in scope.bindings) {
const binding = scope.bindings[name];
if (!binding.referenced && binding.kind !== "module") {
if (
binding.kind === "param" &&
(this.keepFnArgs || !binding[markForRemoval])
) {
continue;
} else if (binding.path.isVariableDeclarator()) {
const declaration = binding.path.parentPath;
const maybeBlockParent = declaration.parentPath;
if (
maybeBlockParent &&
maybeBlockParent.isForXStatement({
left: declaration.node
})
) {
// Can't remove if in a for-in/for-of/for-await statement `for (var x in wat)`.
continue;
}
} else if (!scope.isPure(binding.path.node)) {
// TODO: AssignmentPattern are marked as impure and unused ids aren't removed yet
continue;
} else if (
binding.path.isFunctionExpression() ||
binding.path.isClassExpression()
) {
// `bar(function foo() {})` foo is not referenced but it's used.
continue;
} else if (
// ClassDeclaration has binding in two scopes
// 1. The scope in which it is declared
// 2. The class's own scope
binding.path.isClassDeclaration() &&
binding.path === scope.path
) {
continue;
}
const mutations = [];
let bail = false;
// Make sure none of the assignments value is used
binding.constantViolations.forEach(p => {
if (bail || p === binding.path) {
return;
}
if (!p.parentPath.isExpressionStatement()) {
bail = true;
}
if (p.isAssignmentExpression()) {
if (
t.isArrayPattern(p.node.left) ||
t.isObjectPattern(p.node.left)
) {
bail = true;
} else if (p.get("right").isPure()) {
mutations.push(() => removeOrVoid(p));
} else {
mutations.push(() => p.replaceWith(p.get("right")));
}
}
});
if (bail) {
continue;
}
if (binding.path.isVariableDeclarator()) {
if (!binding.path.get("id").isIdentifier()) {
// deopt for object and array pattern
continue;
}
// if declarator has some impure init expression
// var x = foo();
// => foo();
if (
binding.path.node.init &&
!scope.isPure(binding.path.node.init) &&
binding.path.parentPath.node.declarations
) {
// binding path has more than one declarations
if (binding.path.parentPath.node.declarations.length !== 1) {
continue;
}
binding.path.parentPath.replaceWith(binding.path.node.init);
} else {
updateReferences(binding.path, this);
removeOrVoid(binding.path);
}
} else {
updateReferences(binding.path, this);
removeOrVoid(binding.path);
}
mutations.forEach(f => f());
scope.removeBinding(name);
} else if (binding.constant) {
if (
binding.path.isFunctionDeclaration() ||
(binding.path.isVariableDeclarator() &&
binding.path.get("init").isFunction())
) {
const fun = binding.path.isFunctionDeclaration()
? binding.path
: binding.path.get("init");
let allInside = true;
for (const ref of binding.referencePaths) {
if (!ref.find(p => p.node === fun.node)) {
allInside = false;
break;
}
}
if (allInside) {
scope.removeBinding(name);
updateReferences(binding.path, this);
removeOrVoid(binding.path);
continue;
}
}
if (
binding.references === 1 &&
binding.kind !== "param" &&
binding.kind !== "module" &&
binding.constant
) {
let replacement = binding.path.node;
let replacementPath = binding.path;
let isReferencedBefore = false;
const refPath = binding.referencePaths[0];
if (t.isVariableDeclarator(replacement)) {
const _prevSiblings = prevSiblings(replacementPath);
// traverse ancestors of a reference checking if it's before declaration
forEachAncestor(refPath, ancestor => {
if (_prevSiblings.indexOf(ancestor) > -1) {
isReferencedBefore = true;
}
});
// deopt if reference is in different scope than binding
// since we don't know if it's sync or async execution
// (i.e. whether value has been assigned to a reference or not)
if (isReferencedBefore && refPath.scope !== binding.scope) {
continue;
}
// simulate hoisting by replacing value
// with undefined if declaration is after reference
replacement = isReferencedBefore
? t.unaryExpression("void", t.numericLiteral(0), true)
: replacement.init;
// Bail out for ArrayPattern and ObjectPattern
// TODO: maybe a more intelligent approach instead of simply bailing out
if (!replacementPath.get("id").isIdentifier()) {
continue;
}
replacementPath = replacementPath.get("init");
}
if (!replacement) {
continue;
}
if (!scope.isPure(replacement, true) && !isReferencedBefore) {
continue;
}
let bail = false;
if (replacementPath.isIdentifier()) {
const binding = scope.getBinding(replacement.name);
// the reference should be in the same scope
// and the replacement should be a constant - this is to
// ensure that the duplication of replacement is not affected
// https://github.com/babel/minify/issues/685
bail = !(
binding &&
refPath.scope.getBinding(replacement.name) === binding &&
binding.constantViolations.length === 0
);
} else if (replacementPath.isThisExpression()) {
bail = true;
} else {
replacementPath.traverse({
Function(path) {
path.skip();
},
ThisExpression(path) {
bail = true;
path.stop();
},
ReferencedIdentifier({ node }) {
const binding = scope.getBinding(node.name);
if (
binding &&
refPath.scope.getBinding(node.name) === binding
) {
bail = binding.constantViolations.length > 0;
if (bail) {
path.stop();
}
}
}
});
}
if (bail) {
continue;
}
let parent = binding.path.parent;
if (t.isVariableDeclaration(parent)) {
parent = binding.path.parentPath.parent;
}
// 1. Make sure we share the parent with the node. In other words it's lexically defined
// and not in an if statement or otherwise.
// 2. If the replacement is an object then we have to make sure we are not in a loop or a function
// because otherwise we'll be inlining and doing a lot more allocation than we have to
// which would also could affect correctness in that they are not the same reference.
let mayLoop = false;
const sharesRoot = refPath.find(({ node }) => {
if (!mayLoop) {
mayLoop =
t.isWhileStatement(node) ||
t.isFor(node) ||
t.isFunction(node);
}
return node === parent;
});
// Anything that inherits from Object.
const isObj = n =>
t.isFunction(n) ||
t.isObjectExpression(n) ||
t.isArrayExpression(n) ||
t.isRegExpLiteral(n);
const isReplacementObj =
isObj(replacement) || some(replacement, isObj);
if (!sharesRoot || (isReplacementObj && mayLoop)) {
continue;
}
// check if it's safe to replace
// To solve https://github.com/babel/minify/issues/691
// Here we bail for property checks using the "in" operator
// This is because - `in` is a side-effect-free operation but the property
// could be deleted between the replacementPath and referencePath
// It is expensive to compute the delete operation and we bail for
// all the binary "in" operations
let inExpression = replacementPath.isBinaryExpression({
operator: "in"
});
if (!inExpression) {
replacementPath.traverse({
Function(path) {
path.skip();
},
BinaryExpression(path) {
if (path.node.operator === "in") {
inExpression = true;
path.stop();
}
}
});
}
if (inExpression) {
continue;
}
const replaced = replace(binding.referencePaths[0], {
binding,
scope,
replacement,
replacementPath
});
if (replaced) {
scope.removeBinding(name);
if (binding.path.node) {
removeOrVoid(binding.path);
}
}
}
}
} // end-for-of
}
},
// Remove unreachable code.
BlockStatement(path) {
const paths = path.get("body");
let purge = false;
for (let i = 0; i < paths.length; i++) {
const p = paths[i];
if (!purge && p.isCompletionStatement()) {
purge = true;
continue;
}
if (purge && !canExistAfterCompletion(p)) {
removeOrVoid(p);
}
}
},
// Double check unreachable code and remove return statements that
// have no semantic meaning
ReturnStatement(path) {
const { node } = path;
if (!path.inList) {
return;
}
// Not last in its block? (See BlockStatement visitor)
if (
path.container.length - 1 !== path.key &&
!canExistAfterCompletion(path.getSibling(path.key + 1)) &&
path.parentPath.isBlockStatement()
) {
// This is probably a new oppurtinity by some other transform
// let's call the block visitor on this again before proceeding.
path.parentPath.pushContext(path.context);
path.parentPath.visit();
path.parentPath.popContext();
return;
}
if (node.argument) {
return;
}
let noNext = true;
let parentPath = path.parentPath;
while (parentPath && !parentPath.isFunction() && noNext) {
// https://github.com/babel/minify/issues/265
if (hasLoopParent(parentPath)) {
noNext = false;
break;
}
const nextPath = parentPath.getSibling(parentPath.key + 1);
if (nextPath.node) {
if (nextPath.isReturnStatement()) {
nextPath.pushContext(path.context);
nextPath.visit();
nextPath.popContext();
if (parentPath.getSibling(parentPath.key + 1).node) {
noNext = false;
break;
}
} else {
noNext = false;
break;
}
}
parentPath = parentPath.parentPath;
}
if (noNext) {
removeOrVoid(path);
}
},
ConditionalExpression(path) {
const { node } = path;
const evaluateTest = evaluateTruthy(path.get("test"));
if (evaluateTest === true) {
path.replaceWith(node.consequent);
} else if (evaluateTest === false) {
path.replaceWith(node.alternate);
}
},
SwitchStatement: {
exit(path) {
const discriminantPath = path.get("discriminant");
const evaluated = evaluate(discriminantPath, { tdz: this.tdz });
if (!evaluated.confident) return;
// the simplify transformation might have brought in the previous
// expressions into the switch's test expression and instead of
// bailing out of impure path, we collect the impurities of it's
// a sequence expression and bail out if the primary test itself
// is impure
let beforeTest = [];
if (t.isSequenceExpression(discriminantPath.node)) {
const expressions = discriminantPath.get("expressions");
const lastExpression = expressions[expressions.length - 1];
if (!lastExpression.isPure()) {
return;
}
beforeTest = [
t.expressionStatement(
t.sequenceExpression(
expressions
.slice(0, expressions.length - 1)
.map(path => path.node)
)
)
];
} else if (!discriminantPath.isPure()) {
return;
}
const discriminant = evaluated.value;
const cases = path.get("cases");
let matchingCaseIndex = -1;
let defaultCaseIndex = -1;
for (let i = 0; i < cases.length; i++) {
const test = cases[i].get("test");
// handle default case
if (test.node === null) {
defaultCaseIndex = i;
continue;
}
const testResult = evaluate(test, {
tdz: this.tdz
});
// if we are not able to deternine a test during
// compile time, we terminate immediately
if (!testResult.confident) return;
if (testResult.value === discriminant) {
matchingCaseIndex = i;
break;
}
}
let result;
if (matchingCaseIndex === -1) {
if (defaultCaseIndex === -1) {
path.skip();
path.replaceWithMultiple(extractVars(path));
return;
} else {
result = getStatementsUntilBreak(defaultCaseIndex);
}
} else {
result = getStatementsUntilBreak(matchingCaseIndex);
}
if (result.bail) return;
// we extract vars from the entire switch statement
// and there will be duplicates which
// will be again removed by DCE
replaceSwitch([
...extractVars(path),
...beforeTest,
...result.statements
]);
function getStatementsUntilBreak(start) {
const result = { bail: false, statements: [] };
for (let i = start; i < cases.length; i++) {
const consequent = cases[i].get("consequent");
for (let j = 0; j < consequent.length; j++) {
const _isBreaking = isBreaking(consequent[j], path);
if (_isBreaking.bail) {
result.bail = true;
return result;
}
if (_isBreaking.break) {
// compute no more
// exit out of the loop
return result;
} else {
result.statements.push(consequent[j].node);
}
}
}
return result;
}
function replaceSwitch(statements) {
let isBlockRequired = false;
for (let i = 0; i < statements.length; i++) {
if (t.isVariableDeclaration(statements[i], { kind: "let" })) {
isBlockRequired = true;
break;
}
if (t.isVariableDeclaration(statements[i], { kind: "const" })) {
isBlockRequired = true;
break;
}
}
if (isBlockRequired) {
path.replaceWith(t.BlockStatement(statements));
} else {
path.replaceWithMultiple(statements);
}
}
}
},
WhileStatement(path) {
const test = path.get("test");
const result = evaluate(test, { tdz: this.tdz });
if (result.confident && test.isPure() && !result.value) {
path.replaceWithMultiple(extractVars(path.get("body")));
}
},
ForStatement(path) {
const test = path.get("test");
if (!test.isPure()) return;
const result = evaluate(test, { tdz: this.tdz });
if (result.confident) {
if (result.value) {
test.remove();
} else {
const init = path.get("init");
if (init.node && !init.isPure()) {
path.replaceWith(init);
} else {
path.remove();
}
}
}
},
DoWhileStatement(path) {
const test = path.get("test");
const result = evaluate(test, { tdz: this.tdz });
if (result.confident && test.isPure() && !result.value) {
const body = path.get("body");
if (body.isBlockStatement()) {
const stmts = body.get("body");
for (const stmt of stmts) {
const _isBreaking = isBreaking(stmt, path);
if (_isBreaking.bail || _isBreaking.break) return;
const _isContinuing = isContinuing(stmt, path);
if (_isContinuing.bail || isContinuing.continue) return;
}
path.replaceWith(body.node);
} else if (body.isBreakStatement()) {
const _isBreaking = isBreaking(body, path);
if (_isBreaking.bail) return;
if (_isBreaking.break) path.remove();
} else if (body.isContinueStatement()) {
return;
} else {
path.replaceWith(body.node);
}
}
},
// Join assignment and definition when in sequence.
// var x; x = 1; -> var x = 1;
AssignmentExpression(path) {
if (
!path.get("left").isIdentifier() ||
!path.parentPath.isExpressionStatement()
) {
return;
}
const prev = path.parentPath.getSibling(path.parentPath.key - 1);
if (!(prev && prev.isVariableDeclaration())) {
return;
}
const declars = prev.node.declarations;
if (
declars.length !== 1 ||
declars[0].init ||
declars[0].id.name !== path.get("left").node.name
) {
return;
}
declars[0].init = path.node.right;
removeOrVoid(path);
},
// Remove named function expression name. While this is dangerous as it changes
// `function.name` all minifiers do it and hence became a standard.
FunctionExpression(path) {
if (!this.keepFnName) {
removeUnreferencedId(path);
}
},
// remove class names
ClassExpression(path) {
if (!this.keepClassName) {
removeUnreferencedId(path);
}
},
// Put the `var` in the left if feasible.
ForInStatement(path) {
const left = path.get("left");
if (!left.isIdentifier()) {
return;
}
const binding = path.scope.getBinding(left.node.name);
if (!binding) {
return;
}
if (
binding.scope.getFunctionParent() !== path.scope.getFunctionParent()
) {
return;
}
if (!binding.path.isVariableDeclarator()) {
return;
}
if (
binding.path.parentPath.parentPath.isForInStatement({
left: binding.path.parent
})
) {
return;
}
// If it has company then it's probably more efficient to keep.
if (binding.path.parent.declarations.length > 1) {
return;
}
// meh
if (binding.path.node.init) {
return;
}
removeOrVoid(binding.path);
path.node.left = t.variableDeclaration("var", [
t.variableDeclarator(left.node)
]);
binding.path = path.get("left").get("declarations")[0];
}
};
return {
name: "minify-dead-code-elimination",
visitor: {
Function: {
exit(path) {
/**
* Use exit handler to traverse in a dfs post-order fashion
* to remove use strict
*/
const body = path.get("body");
if (body.isBlockStatement()) {
removeUseStrict(body);
}
}
},
IfStatement: {
exit(path, { opts: { tdz = false } = {} }) {
const consequent = path.get("consequent");
const alternate = path.get("alternate");
const test = path.get("test");
const evalResult = evaluate(test, { tdz });
const isPure = test.isPure();
const replacements = [];
if (evalResult.confident && !isPure && test.isSequenceExpression()) {
replacements.push(
t.expressionStatement(extractSequenceImpure(test))
);
}
// we can check if a test will be truthy 100% and if so then we can inline
// the consequent and completely ignore the alternate
//
// if (true) { foo; } -> { foo; }
// if ("foo") { foo; } -> { foo; }
//
if (evalResult.confident && evalResult.value) {
path.replaceWithMultiple([
...replacements,
...toStatements(consequent),
...extractVars(alternate)
]);
return;
}
// we can check if a test will be falsy 100% and if so we can inline the
// alternate if there is one and completely remove the consequent
//
// if ("") { bar; } else { foo; } -> { foo; }
// if ("") { bar; } ->
//
if (evalResult.confident && !evalResult.value) {
if (alternate.node) {
path.replaceWithMultiple([
...replacements,
...toStatements(alternate),
...extractVars(consequent)
]);
return;
} else {
path.replaceWithMultiple([
...replacements,
...extractVars(consequent)
]);
}
}
// remove alternate blocks that are empty
//
// if (foo) { foo; } else {} -> if (foo) { foo; }
//
if (alternate.isBlockStatement() && !alternate.node.body.length) {
alternate.remove();
// For if-statements babel-traverse replaces with an empty block
path.node.alternate = null;
}
// if the consequent block is empty turn alternate blocks into a consequent
// and flip the test
//
// if (foo) {} else { bar; } -> if (!foo) { bar; }
//
if (
consequent.isBlockStatement() &&
!consequent.node.body.length &&
alternate.isBlockStatement() &&
alternate.node.body.length
) {
consequent.replaceWith(alternate.node);
alternate.remove();
// For if-statements babel-traverse replaces with an empty block
path.node.alternate = null;
test.replaceWith(t.unaryExpression("!", test.node, true));
}
}
},
EmptyStatement(path) {
if (path.parentPath.isBlockStatement() || path.parentPath.isProgram()) {
path.remove();
}
},
Program: {
exit(
path,
{
opts: {
// set defaults
optimizeRawSize = false,
keepFnName = false,
keepClassName = false,
keepFnArgs = false,
tdz = false
} = {}
} = {}
) {
(traverse.clearCache || traverse.cache.clear)();
path.scope.crawl();
markEvalScopes(path);
// We need to run this plugin in isolation.
path.traverse(main, {
functionToBindings: new Map(),
optimizeRawSize,
keepFnName,
keepClassName,
keepFnArgs,
tdz
});
}
}
}
};
function toStatements(path) {
const { node } = path;
if (path.isBlockStatement()) {
let hasBlockScoped = false;
for (let i = 0; i < node.body.length; i++) {