-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
PeepholeFoldConstants.java
1428 lines (1249 loc) · 41.5 KB
/
PeepholeFoldConstants.java
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
/*
* Copyright 2004 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.javascript.jscomp.NodeUtil.ValueType;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.TernaryValue;
/**
* Peephole optimization to fold constants (e.g. x + 1 + 7 --> x + 8).
*
*/
class PeepholeFoldConstants extends AbstractPeepholeOptimization {
// TODO(johnlenz): optimizations should not be emiting errors. Move these to
// a check pass.
static final DiagnosticType INVALID_GETELEM_INDEX_ERROR =
DiagnosticType.warning(
"JSC_INVALID_GETELEM_INDEX_ERROR",
"Array index not integer: {0}");
static final DiagnosticType INDEX_OUT_OF_BOUNDS_ERROR =
DiagnosticType.warning(
"JSC_INDEX_OUT_OF_BOUNDS_ERROR",
"Array index out of bounds: {0}");
static final DiagnosticType NEGATING_A_NON_NUMBER_ERROR =
DiagnosticType.warning(
"JSC_NEGATING_A_NON_NUMBER_ERROR",
"Can''t negate non-numeric value: {0}");
static final DiagnosticType FRACTIONAL_BITWISE_OPERAND =
DiagnosticType.warning(
"JSC_FRACTIONAL_BITWISE_OPERAND",
"Fractional bitwise operand: {0}");
private static final double MAX_FOLD_NUMBER = Math.pow(2, 53);
private final boolean late;
private final boolean shouldUseTypes;
/**
* @param late When late is false, this mean we are currently running before
* most of the other optimizations. In this case we would avoid optimizations
* that would make the code harder to analyze. When this is true, we would
* do anything to minimize for size.
*/
PeepholeFoldConstants(boolean late, boolean shouldUseTypes) {
this.late = late;
this.shouldUseTypes = shouldUseTypes;
}
@Override
Node optimizeSubtree(Node subtree) {
switch (subtree.getToken()) {
case CALL:
return tryFoldCall(subtree);
case NEW:
return tryFoldCtorCall(subtree);
case TYPEOF:
return tryFoldTypeof(subtree);
case NOT:
case POS:
case NEG:
case BITNOT:
tryReduceOperandsForOp(subtree);
return tryFoldUnaryOperator(subtree);
case VOID:
return tryReduceVoid(subtree);
default:
tryReduceOperandsForOp(subtree);
return tryFoldBinaryOperator(subtree);
}
}
private Node tryFoldBinaryOperator(Node subtree) {
Node left = subtree.getFirstChild();
if (left == null) {
return subtree;
}
Node right = left.getNext();
if (right == null) {
return subtree;
}
// If we've reached here, node is truly a binary operator.
switch (subtree.getToken()) {
case GETPROP:
return tryFoldGetProp(subtree, left, right);
case GETELEM:
return tryFoldGetElem(subtree, left, right);
case INSTANCEOF:
return tryFoldInstanceof(subtree, left, right);
case AND:
case OR:
return tryFoldAndOr(subtree, left, right);
case LSH:
case RSH:
case URSH:
return tryFoldShift(subtree, left, right);
case ASSIGN:
return tryFoldAssign(subtree, left, right);
case ASSIGN_BITOR:
case ASSIGN_BITXOR:
case ASSIGN_BITAND:
case ASSIGN_LSH:
case ASSIGN_RSH:
case ASSIGN_URSH:
case ASSIGN_ADD:
case ASSIGN_SUB:
case ASSIGN_MUL:
case ASSIGN_DIV:
case ASSIGN_MOD:
return tryUnfoldAssignOp(subtree, left, right);
case ADD:
return tryFoldAdd(subtree, left, right);
case SUB:
case DIV:
case MOD:
return tryFoldArithmeticOp(subtree, left, right);
case MUL:
case BITAND:
case BITOR:
case BITXOR:
Node result = tryFoldArithmeticOp(subtree, left, right);
if (result != subtree) {
return result;
}
return tryFoldLeftChildOp(subtree, left, right);
case LT:
case GT:
case LE:
case GE:
case EQ:
case NE:
case SHEQ:
case SHNE:
return tryFoldComparison(subtree, left, right);
default:
return subtree;
}
}
private Node tryReduceVoid(Node n) {
Node child = n.getFirstChild();
if ((!child.isNumber() || child.getDouble() != 0.0) && !mayHaveSideEffects(n)) {
n.replaceChild(child, IR.number(0));
reportCodeChange();
}
return n;
}
private void tryReduceOperandsForOp(Node n) {
switch (n.getToken()) {
case ADD:
Node left = n.getFirstChild();
Node right = n.getLastChild();
if (!NodeUtil.mayBeString(left, shouldUseTypes)
&& !NodeUtil.mayBeString(right, shouldUseTypes)) {
tryConvertOperandsToNumber(n);
}
break;
case ASSIGN_BITOR:
case ASSIGN_BITXOR:
case ASSIGN_BITAND:
// TODO(johnlenz): convert these to integers.
case ASSIGN_LSH:
case ASSIGN_RSH:
case ASSIGN_URSH:
case ASSIGN_SUB:
case ASSIGN_MUL:
case ASSIGN_MOD:
case ASSIGN_DIV:
tryConvertToNumber(n.getLastChild());
break;
case BITNOT:
case BITOR:
case BITXOR:
case BITAND:
case LSH:
case RSH:
case URSH:
case SUB:
case MUL:
case MOD:
case DIV:
case POS:
case NEG:
tryConvertOperandsToNumber(n);
break;
default:
break;
}
}
private void tryConvertOperandsToNumber(Node n) {
Node next;
for (Node c = n.getFirstChild(); c != null; c = next) {
next = c.getNext();
tryConvertToNumber(c);
}
}
private void tryConvertToNumber(Node n) {
switch (n.getToken()) {
case NUMBER:
// Nothing to do
return;
case AND:
case OR:
case COMMA:
tryConvertToNumber(n.getLastChild());
return;
case HOOK:
tryConvertToNumber(n.getSecondChild());
tryConvertToNumber(n.getLastChild());
return;
case NAME:
if (!NodeUtil.isUndefined(n)) {
return;
}
break;
default:
break;
}
Double result = NodeUtil.getNumberValue(n, shouldUseTypes);
if (result == null) {
return;
}
double value = result;
Node replacement = NodeUtil.numberNode(value, n);
if (replacement.isEquivalentTo(n)) {
return;
}
n.replaceWith(replacement);
reportCodeChange();
}
/**
* Folds 'typeof(foo)' if foo is a literal, e.g.
* typeof("bar") --> "string"
* typeof(6) --> "number"
*/
private Node tryFoldTypeof(Node originalTypeofNode) {
Preconditions.checkArgument(originalTypeofNode.isTypeOf());
Node argumentNode = originalTypeofNode.getFirstChild();
if (argumentNode == null || !NodeUtil.isLiteralValue(argumentNode, true)) {
return originalTypeofNode;
}
String typeNameString = null;
switch (argumentNode.getToken()) {
case FUNCTION:
typeNameString = "function";
break;
case STRING:
typeNameString = "string";
break;
case NUMBER:
typeNameString = "number";
break;
case TRUE:
case FALSE:
typeNameString = "boolean";
break;
case NULL:
case OBJECTLIT:
case ARRAYLIT:
typeNameString = "object";
break;
case VOID:
typeNameString = "undefined";
break;
case NAME:
// We assume here that programs don't change the value of the
// keyword undefined to something other than the value undefined.
if ("undefined".equals(argumentNode.getString())) {
typeNameString = "undefined";
}
break;
default:
break;
}
if (typeNameString != null) {
Node newNode = IR.string(typeNameString);
originalTypeofNode.replaceWith(newNode);
reportCodeChange();
return newNode;
}
return originalTypeofNode;
}
private Node tryFoldUnaryOperator(Node n) {
Preconditions.checkState(n.hasOneChild(), n);
Node left = n.getFirstChild();
Node parent = n.getParent();
if (left == null) {
return n;
}
TernaryValue leftVal = NodeUtil.getPureBooleanValue(left);
if (leftVal == TernaryValue.UNKNOWN) {
return n;
}
switch (n.getToken()) {
case NOT:
// Don't fold !0 and !1 back to false.
if (late && left.isNumber()) {
double numValue = left.getDouble();
if (numValue == 0 || numValue == 1) {
return n;
}
}
Node replacementNode = NodeUtil.booleanNode(!leftVal.toBoolean(true));
parent.replaceChild(n, replacementNode);
reportCodeChange();
return replacementNode;
case POS:
if (NodeUtil.isNumericResult(left)) {
// POS does nothing to numeric values.
parent.replaceChild(n, left.detach());
reportCodeChange();
return left;
}
return n;
case NEG:
if (left.isName()) {
if (left.getString().equals("Infinity")) {
// "-Infinity" is valid and a literal, don't modify it.
return n;
} else if (left.getString().equals("NaN")) {
// "-NaN" is "NaN".
n.removeChild(left);
parent.replaceChild(n, left);
reportCodeChange();
return left;
}
}
if (left.isNumber()) {
double negNum = -left.getDouble();
Node negNumNode = IR.number(negNum);
parent.replaceChild(n, negNumNode);
reportCodeChange();
return negNumNode;
} else {
// left is not a number node, so do not replace, but warn the
// user because they can't be doing anything good
report(NEGATING_A_NON_NUMBER_ERROR, left);
return n;
}
case BITNOT:
try {
double val = left.getDouble();
if (Math.floor(val) == val) {
int intVal = jsConvertDoubleToBits(val);
Node notIntValNode = IR.number(~intVal);
parent.replaceChild(n, notIntValNode);
reportCodeChange();
return notIntValNode;
} else {
report(FRACTIONAL_BITWISE_OPERAND, left);
return n;
}
} catch (UnsupportedOperationException ex) {
// left is not a number node, so do not replace, but warn the
// user because they can't be doing anything good
report(NEGATING_A_NON_NUMBER_ERROR, left);
return n;
}
default:
return n;
}
}
/**
* Uses a method for treating a double as 32bits that is equivalent to
* how JavaScript would convert a number before applying a bit operation.
*/
private int jsConvertDoubleToBits(double d) {
return (int) (((long) Math.floor(d)) & 0xffffffff);
}
/**
* Try to fold {@code left instanceof right} into {@code true}
* or {@code false}.
*/
private Node tryFoldInstanceof(Node n, Node left, Node right) {
Preconditions.checkArgument(n.isInstanceOf());
// TODO(johnlenz) Use type information if available to fold
// instanceof.
if (NodeUtil.isLiteralValue(left, true)
&& !mayHaveSideEffects(right)) {
Node replacementNode = null;
if (NodeUtil.isImmutableValue(left)) {
// Non-object types are never instances.
replacementNode = IR.falseNode();
} else if (right.isName()
&& "Object".equals(right.getString())) {
replacementNode = IR.trueNode();
}
if (replacementNode != null) {
n.replaceWith(replacementNode);
reportCodeChange();
return replacementNode;
}
}
return n;
}
private Node tryFoldAssign(Node n, Node left, Node right) {
Preconditions.checkArgument(n.isAssign());
if (!late) {
return n;
}
// Tries to convert x = x + y -> x += y;
if (!right.hasChildren() ||
right.getSecondChild() != right.getLastChild()) {
// RHS must have two children.
return n;
}
if (mayHaveSideEffects(left)) {
return n;
}
Node newRight;
if (areNodesEqualForInlining(left, right.getFirstChild())) {
newRight = right.getLastChild();
} else if (NodeUtil.isCommutative(right.getToken())
&& areNodesEqualForInlining(left, right.getLastChild())) {
newRight = right.getFirstChild();
} else {
return n;
}
Token newType = null;
switch (right.getToken()) {
case ADD:
newType = Token.ASSIGN_ADD;
break;
case BITAND:
newType = Token.ASSIGN_BITAND;
break;
case BITOR:
newType = Token.ASSIGN_BITOR;
break;
case BITXOR:
newType = Token.ASSIGN_BITXOR;
break;
case DIV:
newType = Token.ASSIGN_DIV;
break;
case LSH:
newType = Token.ASSIGN_LSH;
break;
case MOD:
newType = Token.ASSIGN_MOD;
break;
case MUL:
newType = Token.ASSIGN_MUL;
break;
case RSH:
newType = Token.ASSIGN_RSH;
break;
case SUB:
newType = Token.ASSIGN_SUB;
break;
case URSH:
newType = Token.ASSIGN_URSH;
break;
default:
return n;
}
Node newNode = new Node(newType,
left.detach(), newRight.detach());
n.replaceWith(newNode);
reportCodeChange();
return newNode;
}
private Node tryUnfoldAssignOp(Node n, Node left, Node right) {
if (late) {
return n;
}
if (!n.hasChildren() ||
n.getSecondChild() != n.getLastChild()) {
return n;
}
if (mayHaveSideEffects(left)) {
return n;
}
// Tries to convert x += y -> x = x + y;
Token op = NodeUtil.getOpFromAssignmentOp(n);
Node replacement = IR.assign(left.detach(),
new Node(op, left.cloneTree(), right.detach())
.srcref(n));
n.replaceWith(replacement);
reportCodeChange();
return replacement;
}
/**
* Try to fold a AND/OR node.
*/
private Node tryFoldAndOr(Node n, Node left, Node right) {
Node parent = n.getParent();
Node result = null;
Token type = n.getToken();
TernaryValue leftVal = NodeUtil.getImpureBooleanValue(left);
if (leftVal != TernaryValue.UNKNOWN) {
boolean lval = leftVal.toBoolean(true);
// (TRUE || x) => TRUE (also, (3 || x) => 3)
// (FALSE && x) => FALSE
if ((lval && type == Token.OR) || (!lval && type == Token.AND)) {
result = left;
} else if (!mayHaveSideEffects(left)) {
// (FALSE || x) => x
// (TRUE && x) => x
result = right;
} else {
// Left side may have side effects, but we know its boolean value.
// e.g. true_with_sideeffects || foo() => true_with_sideeffects, foo()
// or: false_with_sideeffects && foo() => false_with_sideeffects, foo()
// This, combined with PeepholeRemoveDeadCode, helps reduce expressions
// like "x() || false || z()".
n.detachChildren();
result = IR.comma(left, right);
}
}
// Note: Right hand side folding is handled by
// PeepholeMinimizeConditions#tryMinimizeCondition
if (result != null) {
// Fold it!
n.detachChildren();
parent.replaceChild(n, result);
reportCodeChange();
return result;
} else {
return n;
}
}
/**
* Expressions such as [foo() + 'a' + 'b'] generate parse trees
* where no node has two const children ((foo() + 'a') + 'b'), so
* tryFoldAdd() won't fold it -- tryFoldLeftChildAdd() will (for Strings).
* Specifically, it folds Add expressions where:
* - The left child is also and add expression
* - The right child is a constant value
* - The left child's right child is a STRING constant.
*/
private Node tryFoldChildAddString(Node n, Node left, Node right) {
if (NodeUtil.isLiteralValue(right, false) &&
left.isAdd()) {
Node ll = left.getFirstChild();
Node lr = ll.getNext();
// Left's right child MUST be a string. We would not want to fold
// foo() + 2 + 'a' because we don't know what foo() will return, and
// therefore we don't know if left is a string concat, or a numeric add.
if (lr.isString()) {
String leftString = NodeUtil.getStringValue(lr);
String rightString = NodeUtil.getStringValue(right);
if (leftString != null && rightString != null) {
left.removeChild(ll);
String result = leftString + rightString;
n.replaceChild(left, ll);
n.replaceChild(right, IR.string(result));
reportCodeChange();
return n;
}
}
}
if (NodeUtil.isLiteralValue(left, false) &&
right.isAdd()) {
Node rl = right.getFirstChild();
Node rr = right.getLastChild();
// Left's right child MUST be a string. We would not want to fold
// foo() + 2 + 'a' because we don't know what foo() will return, and
// therefore we don't know if left is a string concat, or a numeric add.
if (rl.isString()) {
String leftString = NodeUtil.getStringValue(left);
String rightString = NodeUtil.getStringValue(rl);
if (leftString != null && rightString != null) {
right.removeChild(rr);
String result = leftString + rightString;
n.replaceChild(right, rr);
n.replaceChild(left, IR.string(result));
reportCodeChange();
return n;
}
}
}
return n;
}
/**
* Try to fold an ADD node with constant operands
*/
private Node tryFoldAddConstantString(Node n, Node left, Node right) {
if (left.isString() || right.isString()
|| left.isArrayLit() || right.isArrayLit()) {
// Add strings.
String leftString = NodeUtil.getStringValue(left);
String rightString = NodeUtil.getStringValue(right);
if (leftString != null && rightString != null) {
Node newStringNode = IR.string(leftString + rightString);
n.replaceWith(newStringNode);
reportCodeChange();
return newStringNode;
}
}
return n;
}
/**
* Try to fold arithmetic binary operators
*/
private Node tryFoldArithmeticOp(Node n, Node left, Node right) {
Node result = performArithmeticOp(n.getToken(), left, right);
if (result != null) {
result.useSourceInfoIfMissingFromForTree(n);
n.replaceWith(result);
reportCodeChange();
return result;
}
return n;
}
/**
* Try to fold arithmetic binary operators
*/
private Node performArithmeticOp(Token opType, Node left, Node right) {
// Unlike other operations, ADD operands are not always converted
// to Number.
if (opType == Token.ADD
&& (NodeUtil.mayBeString(left, shouldUseTypes)
|| NodeUtil.mayBeString(right, shouldUseTypes))) {
return null;
}
double result;
// TODO(johnlenz): Handle NaN with unknown value. BIT ops convert NaN
// to zero so this is a little awkward here.
Double lValObj = NodeUtil.getNumberValue(left, shouldUseTypes);
if (lValObj == null) {
return null;
}
Double rValObj = NodeUtil.getNumberValue(right, shouldUseTypes);
if (rValObj == null) {
return null;
}
double lval = lValObj;
double rval = rValObj;
switch (opType) {
case BITAND:
result = NodeUtil.toInt32(lval) & NodeUtil.toInt32(rval);
break;
case BITOR:
result = NodeUtil.toInt32(lval) | NodeUtil.toInt32(rval);
break;
case BITXOR:
result = NodeUtil.toInt32(lval) ^ NodeUtil.toInt32(rval);
break;
case ADD:
result = lval + rval;
break;
case SUB:
result = lval - rval;
break;
case MUL:
result = lval * rval;
break;
case MOD:
if (rval == 0) {
return null;
}
result = lval % rval;
break;
case DIV:
if (rval == 0) {
return null;
}
result = lval / rval;
break;
default:
throw new Error("Unexpected arithmetic operator");
}
// TODO(johnlenz): consider removing the result length check.
// length of the left and right value plus 1 byte for the operator.
if ((String.valueOf(result).length() <=
String.valueOf(lval).length() + String.valueOf(rval).length() + 1
// Do not try to fold arithmetic for numbers > 2^53. After that
// point, fixed-point math starts to break down and become inaccurate.
&& Math.abs(result) <= MAX_FOLD_NUMBER)
|| Double.isNaN(result)
|| result == Double.POSITIVE_INFINITY
|| result == Double.NEGATIVE_INFINITY) {
return NodeUtil.numberNode(result, null);
}
return null;
}
/**
* Expressions such as [foo() * 10 * 20] generate parse trees
* where no node has two const children ((foo() * 10) * 20), so
* performArithmeticOp() won't fold it -- tryFoldLeftChildOp() will.
* Specifically, it folds associative expressions where:
* - The left child is also an associative expression of the same time.
* - The right child is a constant NUMBER constant.
* - The left child's right child is a NUMBER constant.
*/
private Node tryFoldLeftChildOp(Node n, Node left, Node right) {
Token opType = n.getToken();
Preconditions.checkState(
(NodeUtil.isAssociative(opType) && NodeUtil.isCommutative(opType))
|| n.isAdd());
Preconditions.checkState(!n.isAdd() || !NodeUtil.mayBeString(n, shouldUseTypes));
// Use getNumberValue to handle constants like "NaN" and "Infinity"
// other values are converted to numbers elsewhere.
Double rightValObj = NodeUtil.getNumberValue(right, shouldUseTypes);
if (rightValObj != null && left.getToken() == opType) {
Preconditions.checkState(left.hasTwoChildren());
Node ll = left.getFirstChild();
Node lr = ll.getNext();
Node valueToCombine = ll;
Node replacement = performArithmeticOp(opType, valueToCombine, right);
if (replacement == null) {
valueToCombine = lr;
replacement = performArithmeticOp(opType, valueToCombine, right);
}
if (replacement != null) {
// Remove the child that has been combined
left.removeChild(valueToCombine);
// Replace the left op with the remaining child.
n.replaceChild(left, left.removeFirstChild());
// New "-Infinity" node need location info explicitly
// added.
replacement.useSourceInfoIfMissingFromForTree(right);
n.replaceChild(right, replacement);
reportCodeChange();
}
}
return n;
}
private Node tryFoldAdd(Node node, Node left, Node right) {
Preconditions.checkArgument(node.isAdd());
if (NodeUtil.mayBeString(node, shouldUseTypes)) {
if (NodeUtil.isLiteralValue(left, false) &&
NodeUtil.isLiteralValue(right, false)) {
// '6' + 7
return tryFoldAddConstantString(node, left, right);
} else {
// a + 7 or 6 + a
return tryFoldChildAddString(node, left, right);
}
} else {
// Try arithmetic add
Node result = tryFoldArithmeticOp(node, left, right);
if (result != node) {
return result;
}
return tryFoldLeftChildOp(node, left, right);
}
}
/**
* Try to fold shift operations
*/
private Node tryFoldShift(Node n, Node left, Node right) {
if (left.isNumber() &&
right.isNumber()) {
double result;
double lval = left.getDouble();
double rval = right.getDouble();
// only the lower 5 bits are used when shifting, so don't do anything
// if the shift amount is outside [0,32)
if (!(rval >= 0 && rval < 32)) {
return n;
}
int rvalInt = (int) rval;
if (rvalInt != rval) {
report(FRACTIONAL_BITWISE_OPERAND, right);
return n;
}
if (Math.floor(lval) != lval) {
report(FRACTIONAL_BITWISE_OPERAND, left);
return n;
}
int bits = jsConvertDoubleToBits(lval);
switch (n.getToken()) {
case LSH:
result = bits << rvalInt;
break;
case RSH:
result = bits >> rvalInt;
break;
case URSH:
// JavaScript always treats the result of >>> as unsigned.
// We must force Java to do the same here.
result = 0xffffffffL & (bits >>> rvalInt);
break;
default:
throw new AssertionError("Unknown shift operator: " + n.getToken());
}
Node newNumber = IR.number(result);
n.replaceWith(newNumber);
reportCodeChange();
return newNumber;
}
return n;
}
/**
* Try to fold comparison nodes, e.g ==
*/
private Node tryFoldComparison(Node n, Node left, Node right) {
TernaryValue result = evaluateComparison(n.getToken(), left, right, shouldUseTypes);
if (result == TernaryValue.UNKNOWN) {
return n;
}
Node newNode = NodeUtil.booleanNode(result.toBoolean(true));
n.replaceWith(newNode);
reportCodeChange();
return newNode;
}
/** http://www.ecma-international.org/ecma-262/6.0/#sec-abstract-relational-comparison */
private static TernaryValue tryAbstractRelationalComparison(Node left, Node right,
boolean useTypes, boolean willNegate) {
// First, try to evaluate based on the general type.
ValueType leftValueType = NodeUtil.getKnownValueType(left);
ValueType rightValueType = NodeUtil.getKnownValueType(right);
if (leftValueType != ValueType.UNDETERMINED && rightValueType != ValueType.UNDETERMINED) {
if (leftValueType == ValueType.STRING && rightValueType == ValueType.STRING) {
String lv = NodeUtil.getStringValue(left);
String rv = NodeUtil.getStringValue(right);
if (lv != null && rv != null) {
// In JS, browsers parse \v differently. So do not compare strings if one contains \v.
if (lv.indexOf('\u000B') != -1 || rv.indexOf('\u000B') != -1) {
return TernaryValue.UNKNOWN;
} else {
return TernaryValue.forBoolean(lv.compareTo(rv) < 0);
}
} else if (left.isTypeOf() && right.isTypeOf()
&& left.getFirstChild().isName() && right.getFirstChild().isName()
&& left.getFirstChild().getString().equals(right.getFirstChild().getString())) {
// Special case: `typeof a < typeof a` is always false.
return TernaryValue.FALSE;
}
}
}
// Then, try to evaluate based on the value of the node. Try comparing as numbers.
Double lv = NodeUtil.getNumberValue(left, useTypes);
Double rv = NodeUtil.getNumberValue(right, useTypes);
if (lv == null || rv == null) {
// Special case: `x < x` is always false.
//
// TODO(moz): If we knew the named value wouldn't be NaN, it would be nice to handle
// LE and GE. We should use type information if available here.
if (!willNegate && left.isName() && right.isName()) {
if (left.getString().equals(right.getString())) {
return TernaryValue.FALSE;
}
}
return TernaryValue.UNKNOWN;
}
if (Double.isNaN(lv) || Double.isNaN(rv)) {
return TernaryValue.forBoolean(willNegate);
} else {
return TernaryValue.forBoolean(lv.doubleValue() < rv.doubleValue());
}
}
/** http://www.ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison */
private static TernaryValue tryAbstractEqualityComparison(Node left, Node right,
boolean useTypes) {
// Evaluate based on the general type.
ValueType leftValueType = NodeUtil.getKnownValueType(left);
ValueType rightValueType = NodeUtil.getKnownValueType(right);
if (leftValueType != ValueType.UNDETERMINED && rightValueType != ValueType.UNDETERMINED) {
// Delegate to strict equality comparison for values of the same type.
if (leftValueType == rightValueType) {
return tryStrictEqualityComparison(left, right, useTypes);
}
if ((leftValueType == ValueType.NULL && rightValueType == ValueType.VOID)
|| (leftValueType == ValueType.VOID && rightValueType == ValueType.NULL)) {
return TernaryValue.TRUE;
}
if ((leftValueType == ValueType.NUMBER && rightValueType == ValueType.STRING)
|| rightValueType == ValueType.BOOLEAN) {
Double rv = NodeUtil.getNumberValue(right, useTypes);
return rv == null
? TernaryValue.UNKNOWN
: tryAbstractEqualityComparison(left, IR.number(rv), useTypes);
}