Debian Codegraph @

src/com/google/javascript/jscomp/PeepholeFoldConstants.java

raw symbols SCIP
1 /*
2 * Copyright 2004 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Preconditions;
20 import com.google.javascript.rhino.IR;
21 import com.google.javascript.rhino.Node;
22 import com.google.javascript.rhino.Token;
23 import com.google.javascript.rhino.head.ScriptRuntime;
24 import com.google.javascript.rhino.jstype.TernaryValue;
25
26 /**
27 * Peephole optimization to fold constants (e.g. x + 1 + 7 --> x + 8).
28 *
29 */
30 class PeepholeFoldConstants extends AbstractPeepholeOptimization {
31
32 // TODO(johnlenz): optimizations should not be emiting errors. Move these to
33 // a check pass.
34 static final DiagnosticType INVALID_GETELEM_INDEX_ERROR =
35 DiagnosticType.warning(
36 "JSC_INVALID_GETELEM_INDEX_ERROR",
37 "Array index not integer: {0}");
38
39 static final DiagnosticType INDEX_OUT_OF_BOUNDS_ERROR =
40 DiagnosticType.warning(
41 "JSC_INDEX_OUT_OF_BOUNDS_ERROR",
42 "Array index out of bounds: {0}");
43
44 static final DiagnosticType NEGATING_A_NON_NUMBER_ERROR =
45 DiagnosticType.warning(
46 "JSC_NEGATING_A_NON_NUMBER_ERROR",
47 "Can't negate non-numeric value: {0}");
48
49 static final DiagnosticType BITWISE_OPERAND_OUT_OF_RANGE =
50 DiagnosticType.warning(
51 "JSC_BITWISE_OPERAND_OUT_OF_RANGE",
52 "Operand out of range, bitwise operation will lose information: {0}");
53
54 static final DiagnosticType SHIFT_AMOUNT_OUT_OF_BOUNDS =
55 DiagnosticType.warning(
56 "JSC_SHIFT_AMOUNT_OUT_OF_BOUNDS",
57 "Shift amount out of bounds: {0}");
58
59 static final DiagnosticType FRACTIONAL_BITWISE_OPERAND =
60 DiagnosticType.warning(
61 "JSC_FRACTIONAL_BITWISE_OPERAND",
62 "Fractional bitwise operand: {0}");
63
64 private static final double MAX_FOLD_NUMBER = Math.pow(2, 53);
65
66 private final boolean late;
67
68 /**
69 * @param late When late is false, this mean we are currently running before
70 * most of the other optimizations. In this case we would avoid optimizations
71 * that would make the code harder to analyze. When this is true, we would
72 * do anything to minimize for size.
73 */
74 PeepholeFoldConstants(boolean late) {
75 this.late = late;
76 }
77
78 @Override
79 Node optimizeSubtree(Node subtree) {
80 switch(subtree.getType()) {
81 case Token.NEW:
82 return tryFoldCtorCall(subtree);
83
84 case Token.TYPEOF:
85 return tryFoldTypeof(subtree);
86
87 case Token.NOT:
88 case Token.POS:
89 case Token.NEG:
90 case Token.BITNOT:
91 tryReduceOperandsForOp(subtree);
92 return tryFoldUnaryOperator(subtree);
93
94 case Token.VOID:
95 return tryReduceVoid(subtree);
96
97 default:
98 tryReduceOperandsForOp(subtree);
99 return tryFoldBinaryOperator(subtree);
100 }
101 }
102
103 private Node tryFoldBinaryOperator(Node subtree) {
104 Node left = subtree.getFirstChild();
105
106 if (left == null) {
107 return subtree;
108 }
109
110 Node right = left.getNext();
111
112 if (right == null) {
113 return subtree;
114 }
115
116 // If we've reached here, node is truly a binary operator.
117 switch(subtree.getType()) {
118 case Token.GETPROP:
119 return tryFoldGetProp(subtree, left, right);
120
121 case Token.GETELEM:
122 return tryFoldGetElem(subtree, left, right);
123
124 case Token.INSTANCEOF:
125 return tryFoldInstanceof(subtree, left, right);
126
127 case Token.AND:
128 case Token.OR:
129 return tryFoldAndOr(subtree, left, right);
130
131 case Token.LSH:
132 case Token.RSH:
133 case Token.URSH:
134 return tryFoldShift(subtree, left, right);
135
136 case Token.ASSIGN:
137 return tryFoldAssign(subtree, left, right);
138
139 case Token.ASSIGN_BITOR:
140 case Token.ASSIGN_BITXOR:
141 case Token.ASSIGN_BITAND:
142 case Token.ASSIGN_LSH:
143 case Token.ASSIGN_RSH:
144 case Token.ASSIGN_URSH:
145 case Token.ASSIGN_ADD:
146 case Token.ASSIGN_SUB:
147 case Token.ASSIGN_MUL:
148 case Token.ASSIGN_DIV:
149 case Token.ASSIGN_MOD:
150 return tryUnfoldAssignOp(subtree, left, right);
151
152 case Token.ADD:
153 return tryFoldAdd(subtree, left, right);
154
155 case Token.SUB:
156 case Token.DIV:
157 case Token.MOD:
158 return tryFoldArithmeticOp(subtree, left, right);
159
160 case Token.MUL:
161 case Token.BITAND:
162 case Token.BITOR:
163 case Token.BITXOR:
164 Node result = tryFoldArithmeticOp(subtree, left, right);
165 if (result != subtree) {
166 return result;
167 }
168 return tryFoldLeftChildOp(subtree, left, right);
169
170 case Token.LT:
171 case Token.GT:
172 case Token.LE:
173 case Token.GE:
174 case Token.EQ:
175 case Token.NE:
176 case Token.SHEQ:
177 case Token.SHNE:
178 return tryFoldComparison(subtree, left, right);
179
180 default:
181 return subtree;
182 }
183 }
184
185 private Node tryReduceVoid(Node n) {
186 Node child = n.getFirstChild();
187 if (!child.isNumber() || child.getDouble() != 0.0) {
188 if (!mayHaveSideEffects(n)) {
189 n.replaceChild(child, IR.number(0));
190 reportCodeChange();
191 }
192 }
193 return n;
194 }
195
196 private void tryReduceOperandsForOp(Node n) {
197 switch (n.getType()) {
198 case Token.ADD:
199 Node left = n.getFirstChild();
200 Node right = n.getLastChild();
201 if (!NodeUtil.mayBeString(left) && !NodeUtil.mayBeString(right)) {
202 tryConvertOperandsToNumber(n);
203 }
204 break;
205 case Token.ASSIGN_BITOR:
206 case Token.ASSIGN_BITXOR:
207 case Token.ASSIGN_BITAND:
208 // TODO(johnlenz): convert these to integers.
209 case Token.ASSIGN_LSH:
210 case Token.ASSIGN_RSH:
211 case Token.ASSIGN_URSH:
212 case Token.ASSIGN_SUB:
213 case Token.ASSIGN_MUL:
214 case Token.ASSIGN_MOD:
215 case Token.ASSIGN_DIV:
216 tryConvertToNumber(n.getLastChild());
217 break;
218 case Token.BITNOT:
219 case Token.BITOR:
220 case Token.BITXOR:
221 case Token.BITAND:
222 case Token.LSH:
223 case Token.RSH:
224 case Token.URSH:
225 case Token.SUB:
226 case Token.MUL:
227 case Token.MOD:
228 case Token.DIV:
229 case Token.POS:
230 case Token.NEG:
231 tryConvertOperandsToNumber(n);
232 break;
233 }
234 }
235
236 private void tryConvertOperandsToNumber(Node n) {
237 Node next;
238 for (Node c = n.getFirstChild(); c != null; c = next) {
239 next = c.getNext();
240 tryConvertToNumber(c);
241 }
242 }
243
244 private void tryConvertToNumber(Node n) {
245 switch (n.getType()) {
246 case Token.NUMBER:
247 // Nothing to do
248 return;
249 case Token.AND:
250 case Token.OR:
251 case Token.COMMA:
252 tryConvertToNumber(n.getLastChild());
253 return;
254 case Token.HOOK:
255 tryConvertToNumber(n.getChildAtIndex(1));
256 tryConvertToNumber(n.getLastChild());
257 return;
258 case Token.NAME:
259 if (!NodeUtil.isUndefined(n)) {
260 return;
261 }
262 break;
263 }
264
265 Double result = NodeUtil.getNumberValue(n);
266 if (result == null) {
267 return;
268 }
269
270 double value = result;
271
272 Node replacement = NodeUtil.numberNode(value, n);
273 if (replacement.isEquivalentTo(n)) {
274 return;
275 }
276
277 n.getParent().replaceChild(n, replacement);
278 reportCodeChange();
279 }
280
281 /**
282 * Folds 'typeof(foo)' if foo is a literal, e.g.
283 * typeof("bar") --> "string"
284 * typeof(6) --> "number"
285 */
286 private Node tryFoldTypeof(Node originalTypeofNode) {
287 Preconditions.checkArgument(originalTypeofNode.isTypeOf());
288
289 Node argumentNode = originalTypeofNode.getFirstChild();
290 if (argumentNode == null || !NodeUtil.isLiteralValue(argumentNode, true)) {
291 return originalTypeofNode;
292 }
293
294 String typeNameString = null;
295
296 switch (argumentNode.getType()) {
297 case Token.FUNCTION:
298 typeNameString = "function";
299 break;
300 case Token.STRING:
301 typeNameString = "string";
302 break;
303 case Token.NUMBER:
304 typeNameString = "number";
305 break;
306 case Token.TRUE:
307 case Token.FALSE:
308 typeNameString = "boolean";
309 break;
310 case Token.NULL:
311 case Token.OBJECTLIT:
312 case Token.ARRAYLIT:
313 typeNameString = "object";
314 break;
315 case Token.VOID:
316 typeNameString = "undefined";
317 break;
318 case Token.NAME:
319 // We assume here that programs don't change the value of the
320 // keyword undefined to something other than the value undefined.
321 if ("undefined".equals(argumentNode.getString())) {
322 typeNameString = "undefined";
323 }
324 break;
325 }
326
327 if (typeNameString != null) {
328 Node newNode = IR.string(typeNameString);
329 originalTypeofNode.getParent().replaceChild(originalTypeofNode, newNode);
330 reportCodeChange();
331
332 return newNode;
333 }
334
335 return originalTypeofNode;
336 }
337
338 private Node tryFoldUnaryOperator(Node n) {
339 Preconditions.checkState(n.hasOneChild());
340
341 Node left = n.getFirstChild();
342 Node parent = n.getParent();
343
344 if (left == null) {
345 return n;
346 }
347
348 TernaryValue leftVal = NodeUtil.getPureBooleanValue(left);
349 if (leftVal == TernaryValue.UNKNOWN) {
350 return n;
351 }
352
353 switch (n.getType()) {
354 case Token.NOT:
355 // Don't fold !0 and !1 back to false.
356 if (late && left.isNumber()) {
357 double numValue = left.getDouble();
358 if (numValue == 0 || numValue == 1) {
359 return n;
360 }
361 }
362 Node replacementNode = NodeUtil.booleanNode(!leftVal.toBoolean(true));
363 parent.replaceChild(n, replacementNode);
364 reportCodeChange();
365 return replacementNode;
366 case Token.POS:
367 if (NodeUtil.isNumericResult(left)) {
368 // POS does nothing to numeric values.
369 parent.replaceChild(n, left.detachFromParent());
370 reportCodeChange();
371 return left;
372 }
373 return n;
374 case Token.NEG:
375 if (left.isName()) {
376 if (left.getString().equals("Infinity")) {
377 // "-Infinity" is valid and a literal, don't modify it.
378 return n;
379 } else if (left.getString().equals("NaN")) {
380 // "-NaN" is "NaN".
381 n.removeChild(left);
382 parent.replaceChild(n, left);
383 reportCodeChange();
384 return left;
385 }
386 }
387
388 if (left.isNumber()) {
389 double negNum = -left.getDouble();
390
391 Node negNumNode = IR.number(negNum);
392 parent.replaceChild(n, negNumNode);
393 reportCodeChange();
394 return negNumNode;
395 } else {
396 // left is not a number node, so do not replace, but warn the
397 // user because they can't be doing anything good
398 report(NEGATING_A_NON_NUMBER_ERROR, left);
399 return n;
400 }
401 case Token.BITNOT:
402 try {
403 double val = left.getDouble();
404 if (val >= Integer.MIN_VALUE && val <= Integer.MAX_VALUE) {
405 int intVal = (int) val;
406 if (intVal == val) {
407 Node notIntValNode = IR.number(~intVal);
408 parent.replaceChild(n, notIntValNode);
409 reportCodeChange();
410 return notIntValNode;
411 } else {
412 report(FRACTIONAL_BITWISE_OPERAND, left);
413 return n;
414 }
415 } else {
416 report(BITWISE_OPERAND_OUT_OF_RANGE, left);
417 return n;
418 }
419 } catch (UnsupportedOperationException ex) {
420 // left is not a number node, so do not replace, but warn the
421 // user because they can't be doing anything good
422 report(NEGATING_A_NON_NUMBER_ERROR, left);
423 return n;
424 }
425 default:
426 return n;
427 }
428 }
429
430 /**
431 * Try to fold {@code left instanceof right} into {@code true}
432 * or {@code false}.
433 */
434 private Node tryFoldInstanceof(Node n, Node left, Node right) {
435 Preconditions.checkArgument(n.isInstanceOf());
436
437 // TODO(johnlenz) Use type information if available to fold
438 // instanceof.
439 if (NodeUtil.isLiteralValue(left, true)
440 && !mayHaveSideEffects(right)) {
441
442 Node replacementNode = null;
443
444 if (NodeUtil.isImmutableValue(left)) {
445 // Non-object types are never instances.
446 replacementNode = IR.falseNode();
447 } else if (right.isName()
448 && "Object".equals(right.getString())) {
449 replacementNode = IR.trueNode();
450 }
451
452 if (replacementNode != null) {
453 n.getParent().replaceChild(n, replacementNode);
454 reportCodeChange();
455 return replacementNode;
456 }
457 }
458
459 return n;
460 }
461
462 private Node tryFoldAssign(Node n, Node left, Node right) {
463 Preconditions.checkArgument(n.isAssign());
464
465 if (!late) {
466 return n;
467 }
468
469 // Tries to convert x = x + y -> x += y;
470 if (!right.hasChildren() ||
471 right.getFirstChild().getNext() != right.getLastChild()) {
472 // RHS must have two children.
473 return n;
474 }
475
476 if (mayHaveSideEffects(left)) {
477 return n;
478 }
479
480 Node newRight;
481 if (areNodesEqualForInlining(left, right.getFirstChild())) {
482 newRight = right.getLastChild();
483 } else if (NodeUtil.isCommutative(right.getType()) &&
484 areNodesEqualForInlining(left, right.getLastChild())) {
485 newRight = right.getFirstChild();
486 } else {
487 return n;
488 }
489
490 int newType = -1;
491 switch (right.getType()) {
492 case Token.ADD:
493 newType = Token.ASSIGN_ADD;
494 break;
495 case Token.BITAND:
496 newType = Token.ASSIGN_BITAND;
497 break;
498 case Token.BITOR:
499 newType = Token.ASSIGN_BITOR;
500 break;
501 case Token.BITXOR:
502 newType = Token.ASSIGN_BITXOR;
503 break;
504 case Token.DIV:
505 newType = Token.ASSIGN_DIV;
506 break;
507 case Token.LSH:
508 newType = Token.ASSIGN_LSH;
509 break;
510 case Token.MOD:
511 newType = Token.ASSIGN_MOD;
512 break;
513 case Token.MUL:
514 newType = Token.ASSIGN_MUL;
515 break;
516 case Token.RSH:
517 newType = Token.ASSIGN_RSH;
518 break;
519 case Token.SUB:
520 newType = Token.ASSIGN_SUB;
521 break;
522 case Token.URSH:
523 newType = Token.ASSIGN_URSH;
524 break;
525 default:
526 return n;
527 }
528
529 Node newNode = new Node(newType,
530 left.detachFromParent(), newRight.detachFromParent());
531 n.getParent().replaceChild(n, newNode);
532
533 reportCodeChange();
534
535 return newNode;
536 }
537
538 private Node tryUnfoldAssignOp(Node n, Node left, Node right) {
539 if (late) {
540 return n;
541 }
542
543 if (!n.hasChildren() ||
544 n.getFirstChild().getNext() != n.getLastChild()) {
545 return n;
546 }
547
548 if (mayHaveSideEffects(left)) {
549 return n;
550 }
551
552 // Tries to convert x += y -> x = x + y;
553 int op = NodeUtil.getOpFromAssignmentOp(n);
554 Node replacement = IR.assign(left.detachFromParent(),
555 new Node(op, left.cloneTree(), right.detachFromParent())
556 .srcref(n));
557 n.getParent().replaceChild(n, replacement);
558 reportCodeChange();
559
560 return replacement;
561 }
562
563 /**
564 * Try to fold a AND/OR node.
565 */
566 private Node tryFoldAndOr(Node n, Node left, Node right) {
567 Node parent = n.getParent();
568
569 Node result = null;
570
571 int type = n.getType();
572
573 TernaryValue leftVal = NodeUtil.getImpureBooleanValue(left);
574
575 if (leftVal != TernaryValue.UNKNOWN) {
576 boolean lval = leftVal.toBoolean(true);
577
578 // (TRUE || x) => TRUE (also, (3 || x) => 3)
579 // (FALSE && x) => FALSE
580 if (lval && type == Token.OR ||
581 !lval && type == Token.AND) {
582 result = left;
583
584 } else if (!mayHaveSideEffects(left)) {
585 // (FALSE || x) => x
586 // (TRUE && x) => x
587 result = right;
588 }
589 }
590
591 // Note: Right hand side folding is handled by
592 // PeepholeSubstituteAlternateSyntax#tryMinimizeCondition
593
594 if (result != null) {
595 // Fold it!
596 n.removeChild(result);
597 parent.replaceChild(n, result);
598 reportCodeChange();
599
600 return result;
601 } else {
602 return n;
603 }
604 }
605
606 /**
607 * Expressions such as [foo() + 'a' + 'b'] generate parse trees
608 * where no node has two const children ((foo() + 'a') + 'b'), so
609 * tryFoldAdd() won't fold it -- tryFoldLeftChildAdd() will (for Strings).
610 * Specifically, it folds Add expressions where:
611 * - The left child is also and add expression
612 * - The right child is a constant value
613 * - The left child's right child is a STRING constant.
614 */
615 private Node tryFoldChildAddString(Node n, Node left, Node right) {
616
617 if (NodeUtil.isLiteralValue(right, false) &&
618 left.isAdd()) {
619
620 Node ll = left.getFirstChild();
621 Node lr = ll.getNext();
622
623 // Left's right child MUST be a string. We would not want to fold
624 // foo() + 2 + 'a' because we don't know what foo() will return, and
625 // therefore we don't know if left is a string concat, or a numeric add.
626 if (lr.isString()) {
627 String leftString = NodeUtil.getStringValue(lr);
628 String rightString = NodeUtil.getStringValue(right);
629 if (leftString != null && rightString != null) {
630 left.removeChild(ll);
631 String result = leftString + rightString;
632 n.replaceChild(left, ll);
633 n.replaceChild(right, IR.string(result));
634 reportCodeChange();
635 return n;
636 }
637 }
638 }
639
640 if (NodeUtil.isLiteralValue(left, false) &&
641 right.isAdd()) {
642
643 Node rl = right.getFirstChild();
644 Node rr = right.getLastChild();
645
646 // Left's right child MUST be a string. We would not want to fold
647 // foo() + 2 + 'a' because we don't know what foo() will return, and
648 // therefore we don't know if left is a string concat, or a numeric add.
649 if (rl.isString()) {
650 String leftString = NodeUtil.getStringValue(left);
651 String rightString = NodeUtil.getStringValue(rl);
652 if (leftString != null && rightString != null) {
653 right.removeChild(rr);
654 String result = leftString + rightString;
655 n.replaceChild(right, rr);
656 n.replaceChild(left, IR.string(result));
657 reportCodeChange();
658 return n;
659 }
660 }
661 }
662
663 return n;
664 }
665
666 /**
667 * Try to fold an ADD node with constant operands
668 */
669 private Node tryFoldAddConstantString(Node n, Node left, Node right) {
670 if (left.isString() ||
671 right.isString()) {
672 // Add strings.
673 String leftString = NodeUtil.getStringValue(left);
674 String rightString = NodeUtil.getStringValue(right);
675 if (leftString != null && rightString != null) {
676 Node newStringNode = IR.string(leftString + rightString);
677 n.getParent().replaceChild(n, newStringNode);
678 reportCodeChange();
679 return newStringNode;
680 }
681 }
682
683
684
685 return n;
686 }
687
688 /**
689 * Try to fold arithmetic binary operators
690 */
691 private Node tryFoldArithmeticOp(Node n, Node left, Node right) {
692 Node result = performArithmeticOp(n.getType(), left, right);
693 if (result != null) {
694 result.copyInformationFromForTree(n);
695 n.getParent().replaceChild(n, result);
696 reportCodeChange();
697 return result;
698 }
699 return n;
700 }
701
702 /**
703 * Try to fold arithmetic binary operators
704 */
705 private Node performArithmeticOp(int opType, Node left, Node right) {
706 // Unlike other operations, ADD operands are not always converted
707 // to Number.
708 if (opType == Token.ADD
709 && (NodeUtil.mayBeString(left, false)
710 || NodeUtil.mayBeString(right, false))) {
711 return null;
712 }
713
714 double result;
715
716 // TODO(johnlenz): Handle NaN with unknown value. BIT ops convert NaN
717 // to zero so this is a little awkward here.
718
719 Double lValObj = NodeUtil.getNumberValue(left);
720 if (lValObj == null) {
721 return null;
722 }
723 Double rValObj = NodeUtil.getNumberValue(right);
724 if (rValObj == null) {
725 return null;
726 }
727
728 double lval = lValObj;
729 double rval = rValObj;
730
731 switch (opType) {
732 case Token.BITAND:
733 result = ScriptRuntime.toInt32(lval) & ScriptRuntime.toInt32(rval);
734 break;
735 case Token.BITOR:
736 result = ScriptRuntime.toInt32(lval) | ScriptRuntime.toInt32(rval);
737 break;
738 case Token.BITXOR:
739 result = ScriptRuntime.toInt32(lval) ^ ScriptRuntime.toInt32(rval);
740 break;
741 case Token.ADD:
742 result = lval + rval;
743 break;
744 case Token.SUB:
745 result = lval - rval;
746 break;
747 case Token.MUL:
748 result = lval * rval;
749 break;
750 case Token.MOD:
751 if (rval == 0) {
752 return null;
753 }
754 result = lval % rval;
755 break;
756 case Token.DIV:
757 if (rval == 0) {
758 return null;
759 }
760 result = lval / rval;
761 break;
762 default:
763 throw new Error("Unexpected arithmetic operator");
764 }
765
766 // TODO(johnlenz): consider removing the result length check.
767 // length of the left and right value plus 1 byte for the operator.
768 if ((String.valueOf(result).length() <=
769 String.valueOf(lval).length() + String.valueOf(rval).length() + 1
770
771 // Do not try to fold arithmetic for numbers > 2^53. After that
772 // point, fixed-point math starts to break down and become inaccurate.
773 && Math.abs(result) <= MAX_FOLD_NUMBER)
774 || Double.isNaN(result)
775 || result == Double.POSITIVE_INFINITY
776 || result == Double.NEGATIVE_INFINITY) {
777 return NodeUtil.numberNode(result, null);
778 }
779 return null;
780 }
781
782 /**
783 * Expressions such as [foo() * 10 * 20] generate parse trees
784 * where no node has two const children ((foo() * 10) * 20), so
785 * performArithmeticOp() won't fold it -- tryFoldLeftChildOp() will.
786 * Specifically, it folds associative expressions where:
787 * - The left child is also an associative expression of the same time.
788 * - The right child is a constant NUMBER constant.
789 * - The left child's right child is a NUMBER constant.
790 */
791 private Node tryFoldLeftChildOp(Node n, Node left, Node right) {
792 int opType = n.getType();
793 Preconditions.checkState(
794 (NodeUtil.isAssociative(opType) && NodeUtil.isCommutative(opType))
795 || n.isAdd());
796
797 Preconditions.checkState(
798 !n.isAdd()|| !NodeUtil.mayBeString(n));
799
800 // Use getNumberValue to handle constants like "NaN" and "Infinity"
801 // other values are converted to numbers elsewhere.
802 Double rightValObj = NodeUtil.getNumberValue(right);
803 if (rightValObj != null && left.getType() == opType) {
804 Preconditions.checkState(left.getChildCount() == 2);
805
806 Node ll = left.getFirstChild();
807 Node lr = ll.getNext();
808
809 Node valueToCombine = ll;
810 Node replacement = performArithmeticOp(opType, valueToCombine, right);
811 if (replacement == null) {
812 valueToCombine = lr;
813 replacement = performArithmeticOp(opType, valueToCombine, right);
814 }
815 if (replacement != null) {
816 // Remove the child that has been combined
817 left.removeChild(valueToCombine);
818 // Replace the left op with the remaining child.
819 n.replaceChild(left, left.removeFirstChild());
820 // New "-Infinity" node need location info explicitly
821 // added.
822 replacement.copyInformationFromForTree(right);
823 n.replaceChild(right, replacement);
824 reportCodeChange();
825 }
826 }
827
828 return n;
829 }
830
831 private Node tryFoldAdd(Node node, Node left, Node right) {
832 Preconditions.checkArgument(node.isAdd());
833
834 if (NodeUtil.mayBeString(node, true)) {
835 if (NodeUtil.isLiteralValue(left, false) &&
836 NodeUtil.isLiteralValue(right, false)) {
837 // '6' + 7
838 return tryFoldAddConstantString(node, left, right);
839 } else {
840 // a + 7 or 6 + a
841 return tryFoldChildAddString(node, left, right);
842 }
843 } else {
844 // Try arithmetic add
845 Node result = tryFoldArithmeticOp(node, left, right);
846 if (result != node) {
847 return result;
848 }
849 return tryFoldLeftChildOp(node, left, right);
850 }
851 }
852
853 /**
854 * Try to fold shift operations
855 */
856 private Node tryFoldShift(Node n, Node left, Node right) {
857 if (left.isNumber() &&
858 right.isNumber()) {
859
860 double result;
861 double lval = left.getDouble();
862 double rval = right.getDouble();
863
864 // check ranges. We do not do anything that would clip the double to
865 // a 32-bit range, since the user likely does not intend that.
866 if (!(lval >= Integer.MIN_VALUE && lval <= Integer.MAX_VALUE)) {
867 report(BITWISE_OPERAND_OUT_OF_RANGE, left);
868 return n;
869 }
870
871 // only the lower 5 bits are used when shifting, so don't do anything
872 // if the shift amount is outside [0,32)
873 if (!(rval >= 0 && rval < 32)) {
874 report(SHIFT_AMOUNT_OUT_OF_BOUNDS, right);
875 return n;
876 }
877
878 // Convert the numbers to ints
879 int lvalInt = (int) lval;
880 if (lvalInt != lval) {
881 report(FRACTIONAL_BITWISE_OPERAND, left);
882 return n;
883 }
884
885 int rvalInt = (int) rval;
886 if (rvalInt != rval) {
887 report(FRACTIONAL_BITWISE_OPERAND, right);
888 return n;
889 }
890
891 switch (n.getType()) {
892 case Token.LSH:
893 result = lvalInt << rvalInt;
894 break;
895 case Token.RSH:
896 result = lvalInt >> rvalInt;
897 break;
898 case Token.URSH:
899 // JavaScript handles zero shifts on signed numbers differently than
900 // Java as an Java int can not represent the unsigned 32-bit number
901 // where JavaScript can so use a long here.
902 long lvalLong = lvalInt & 0xffffffffL;
903 result = lvalLong >>> rvalInt;
904 break;
905 default:
906 throw new AssertionError("Unknown shift operator: " +
907 Token.name(n.getType()));
908 }
909
910 Node newNumber = IR.number(result);
911 n.getParent().replaceChild(n, newNumber);
912 reportCodeChange();
913
914 return newNumber;
915 }
916
917 return n;
918 }
919
920 /**
921 * Try to fold comparison nodes, e.g ==
922 */
923 @SuppressWarnings("fallthrough")
924 private Node tryFoldComparison(Node n, Node left, Node right) {
925 TernaryValue result = evaluateComparison(n.getType(), left, right);
926 if (result == TernaryValue.UNKNOWN) {
927 return n;
928 }
929
930 Node newNode = NodeUtil.booleanNode(result.toBoolean(true));
931 n.getParent().replaceChild(n, newNode);
932 reportCodeChange();
933
934 return newNode;
935 }
936
937 static TernaryValue evaluateComparison(int op, Node left, Node right) {
938 boolean leftLiteral = NodeUtil.isLiteralValue(left, true);
939 boolean rightLiteral = NodeUtil.isLiteralValue(right, true);
940
941 if (!leftLiteral || !rightLiteral) {
942 // We only handle literal operands for LT and GT.
943 if (op != Token.GT && op != Token.LT) {
944 return TernaryValue.UNKNOWN;
945 }
946 }
947
948 boolean undefinedRight = NodeUtil.isUndefined(right) && rightLiteral;
949 boolean nullRight = right.isNull();
950 int lhType = getNormalizedNodeType(left);
951 int rhType = getNormalizedNodeType(right);
952 switch (lhType) {
953 case Token.VOID:
954 if (!leftLiteral) {
955 return TernaryValue.UNKNOWN;
956 } else if (!rightLiteral) {
957 return TernaryValue.UNKNOWN;
958 } else {
959 return TernaryValue.forBoolean(compareToUndefined(right, op));
960 }
961
962 case Token.NULL:
963 if (rightLiteral && isEqualityOp(op)) {
964 return TernaryValue.forBoolean(compareToNull(right, op));
965 }
966 // fallthrough
967 case Token.TRUE:
968 case Token.FALSE:
969 if (undefinedRight) {
970 return TernaryValue.forBoolean(compareToUndefined(left, op));
971 }
972 if (rhType != Token.TRUE &&
973 rhType != Token.FALSE &&
974 rhType != Token.NULL) {
975 return TernaryValue.UNKNOWN;
976 }
977 switch (op) {
978 case Token.SHEQ:
979 case Token.EQ:
980 return TernaryValue.forBoolean(lhType == rhType);
981
982 case Token.SHNE:
983 case Token.NE:
984 return TernaryValue.forBoolean(lhType != rhType);
985
986 case Token.GE:
987 case Token.LE:
988 case Token.GT:
989 case Token.LT:
990 return compareAsNumbers(op, left, right);
991 }
992 return TernaryValue.UNKNOWN;
993
994 case Token.THIS:
995 if (!right.isThis()) {
996 return TernaryValue.UNKNOWN;
997 }
998 switch (op) {
999 case Token.SHEQ:
1000 case Token.EQ:
1001 return TernaryValue.TRUE;
1002
1003 case Token.SHNE:
1004 case Token.NE:
1005 return TernaryValue.FALSE;
1006 }
1007
1008 // We can only handle == and != here.
1009 // GT, LT, GE, LE depend on the type of "this" and how it will
1010 // be converted to number. The results are different depending on
1011 // whether it is a string, NaN or other number value.
1012 return TernaryValue.UNKNOWN;
1013
1014 case Token.STRING:
1015 if (undefinedRight) {
1016 return TernaryValue.forBoolean(compareToUndefined(left, op));
1017 }
1018 if (nullRight && isEqualityOp(op)) {
1019 return TernaryValue.forBoolean(compareToNull(left, op));
1020 }
1021 if (Token.STRING != right.getType()) {
1022 return TernaryValue.UNKNOWN; // Only eval if they are the same type
1023 }
1024
1025 switch (op) {
1026 case Token.SHEQ:
1027 case Token.EQ:
1028 return areStringsEqual(left.getString(), right.getString());
1029
1030 case Token.SHNE:
1031 case Token.NE:
1032 return areStringsEqual(left.getString(), right.getString()).not();
1033 }
1034
1035 return TernaryValue.UNKNOWN;
1036
1037 case Token.NUMBER:
1038 if (undefinedRight) {
1039 return TernaryValue.forBoolean(compareToUndefined(left, op));
1040 }
1041 if (nullRight && isEqualityOp(op)) {
1042 return TernaryValue.forBoolean(compareToNull(left, op));
1043 }
1044 if (Token.NUMBER != right.getType()) {
1045 return TernaryValue.UNKNOWN; // Only eval if they are the same type
1046 }
1047 return compareAsNumbers(op, left, right);
1048
1049 case Token.NAME:
1050 if (leftLiteral && undefinedRight) {
1051 return TernaryValue.forBoolean(compareToUndefined(left, op));
1052 }
1053
1054 if (rightLiteral) {
1055 boolean undefinedLeft = (left.getString().equals("undefined"));
1056 if (undefinedLeft) {
1057 return TernaryValue.forBoolean(compareToUndefined(right, op));
1058 }
1059 if (leftLiteral && nullRight && isEqualityOp(op)) {
1060 return TernaryValue.forBoolean(compareToNull(left, op));
1061 }
1062 }
1063
1064 if (Token.NAME != right.getType()) {
1065 return TernaryValue.UNKNOWN; // Only eval if they are the same type
1066 }
1067 String ln = left.getString();
1068 String rn = right.getString();
1069 if (!ln.equals(rn)) {
1070 return TernaryValue.UNKNOWN; // Not the same value name.
1071 }
1072
1073 switch (op) {
1074 // If we knew the named value wouldn't be NaN, it would be nice
1075 // to handle EQ,NE,LE,GE,SHEQ, and SHNE.
1076 case Token.LT:
1077 case Token.GT:
1078 return TernaryValue.FALSE;
1079 }
1080
1081 return TernaryValue.UNKNOWN; // don't handle that op
1082
1083 case Token.NEG:
1084 if (leftLiteral) {
1085 if (undefinedRight) {
1086 return TernaryValue.forBoolean(compareToUndefined(left, op));
1087 }
1088 if (nullRight && isEqualityOp(op)) {
1089 return TernaryValue.forBoolean(compareToNull(left, op));
1090 }
1091 }
1092 // Nothing else for now.
1093 return TernaryValue.UNKNOWN;
1094
1095 case Token.ARRAYLIT:
1096 case Token.OBJECTLIT:
1097 case Token.REGEXP:
1098 case Token.FUNCTION:
1099 if (leftLiteral) {
1100 if (undefinedRight) {
1101 return TernaryValue.forBoolean(compareToUndefined(left, op));
1102 }
1103 if (nullRight && isEqualityOp(op)) {
1104 return TernaryValue.forBoolean(compareToNull(left, op));
1105 }
1106 }
1107 // ignore the rest for now.
1108 return TernaryValue.UNKNOWN;
1109
1110 default:
1111 // assert, this should cover all consts
1112 return TernaryValue.UNKNOWN;
1113 }
1114 }
1115
1116 /** Returns whether two JS strings are equal. */
1117 private static TernaryValue areStringsEqual(String a, String b) {
1118 // In JS, browsers parse \v differently. So do not consider strings
1119 // equal if one contains \v.
1120 if (a.indexOf('\u000B') != -1 ||
1121 b.indexOf('\u000B') != -1) {
1122 return TernaryValue.UNKNOWN;
1123 } else {
1124 return a.equals(b) ? TernaryValue.TRUE : TernaryValue.FALSE;
1125 }
1126 }
1127
1128 /**
1129 * @return Translate NOT expressions into TRUE or FALSE when possible.
1130 */
1131 private static int getNormalizedNodeType(Node n) {
1132 int type = n.getType();
1133 if (type == Token.NOT) {
1134 TernaryValue value = NodeUtil.getPureBooleanValue(n);
1135 switch (value) {
1136 case TRUE:
1137 return Token.TRUE;
1138 case FALSE:
1139 return Token.FALSE;
1140 case UNKNOWN:
1141 return type;
1142 }
1143 }
1144 return type;
1145 }
1146
1147 /**
1148 * The result of the comparison, or UNKNOWN if the
1149 * result could not be determined.
1150 */
1151 private static TernaryValue compareAsNumbers(int op, Node left, Node right) {
1152 Double leftValue = NodeUtil.getNumberValue(left);
1153 if (leftValue == null) {
1154 return TernaryValue.UNKNOWN;
1155 }
1156 Double rightValue = NodeUtil.getNumberValue(right);
1157 if (rightValue == null) {
1158 return TernaryValue.UNKNOWN;
1159 }
1160
1161 double lv = leftValue;
1162 double rv = rightValue;
1163
1164 switch (op) {
1165 case Token.SHEQ:
1166 case Token.EQ:
1167 Preconditions.checkState(
1168 left.isNumber() && right.isNumber());
1169 return TernaryValue.forBoolean(lv == rv);
1170 case Token.SHNE:
1171 case Token.NE:
1172 Preconditions.checkState(
1173 left.isNumber() && right.isNumber());
1174 return TernaryValue.forBoolean(lv != rv);
1175 case Token.LE:
1176 return TernaryValue.forBoolean(lv <= rv);
1177 case Token.LT:
1178 return TernaryValue.forBoolean(lv < rv);
1179 case Token.GE:
1180 return TernaryValue.forBoolean(lv >= rv);
1181 case Token.GT:
1182 return TernaryValue.forBoolean(lv > rv);
1183 default:
1184 return TernaryValue.UNKNOWN; // don't handle that op
1185 }
1186 }
1187
1188 /**
1189 * @param value The value to compare to "undefined"
1190 * @param op The boolean op to compare with
1191 * @return Whether the boolean op is true or false
1192 */
1193 private static boolean compareToUndefined(Node value, int op) {
1194 Preconditions.checkState(NodeUtil.isLiteralValue(value, true));
1195 boolean valueUndefined = NodeUtil.isUndefined(value);
1196 boolean valueNull = (Token.NULL == value.getType());
1197 boolean equivalent = valueUndefined || valueNull;
1198 switch (op) {
1199 case Token.EQ:
1200 // undefined is only equal to null or an undefined value
1201 return equivalent;
1202 case Token.NE:
1203 return !equivalent;
1204 case Token.SHEQ:
1205 return valueUndefined;
1206 case Token.SHNE:
1207 return !valueUndefined;
1208 case Token.LT:
1209 case Token.GT:
1210 case Token.LE:
1211 case Token.GE:
1212 return false;
1213 default:
1214 throw new IllegalStateException("unexpected.");
1215 }
1216 }
1217
1218 private static boolean isEqualityOp(int op) {
1219 switch (op) {
1220 case Token.EQ:
1221 case Token.NE:
1222 case Token.SHEQ:
1223 case Token.SHNE:
1224 return true;
1225 }
1226 return false;
1227 }
1228
1229 /**
1230 * @param value The value to compare to "null"
1231 * @param op The boolean op to compare with
1232 * @return Whether the boolean op is true or false
1233 */
1234 private static boolean compareToNull(Node value, int op) {
1235 boolean valueUndefined = NodeUtil.isUndefined(value);
1236 boolean valueNull = (Token.NULL == value.getType());
1237 boolean equivalent = valueUndefined || valueNull;
1238 switch (op) {
1239 case Token.EQ:
1240 // undefined is only equal to null or an undefined value
1241 return equivalent;
1242 case Token.NE:
1243 return !equivalent;
1244 case Token.SHEQ:
1245 return valueNull;
1246 case Token.SHNE:
1247 return !valueNull;
1248 default:
1249 throw new IllegalStateException("unexpected.");
1250 }
1251 }
1252
1253 /**
1254 * Try to fold away unnecessary object instantiation.
1255 * e.g. this[new String('eval')] -> this.eval
1256 */
1257 private Node tryFoldCtorCall(Node n) {
1258 Preconditions.checkArgument(n.isNew());
1259
1260 // we can remove this for GETELEM calls (anywhere else?)
1261 if (inForcedStringContext(n)) {
1262 return tryFoldInForcedStringContext(n);
1263 }
1264 return n;
1265 }
1266
1267 /** Returns whether this node must be coerced to a string. */
1268 private boolean inForcedStringContext(Node n) {
1269 if (n.getParent().isGetElem() &&
1270 n.getParent().getLastChild() == n) {
1271 return true;
1272 }
1273
1274 // we can fold in the case "" + new String("")
1275 if (n.getParent().isAdd()) {
1276 return true;
1277 }
1278 return false;
1279 }
1280
1281 private Node tryFoldInForcedStringContext(Node n) {
1282 // For now, we only know how to fold ctors.
1283 Preconditions.checkArgument(n.isNew());
1284
1285 Node objectType = n.getFirstChild();
1286 if (!objectType.isName()) {
1287 return n;
1288 }
1289
1290 if (objectType.getString().equals("String")) {
1291 Node value = objectType.getNext();
1292 String stringValue = null;
1293 if (value == null) {
1294 stringValue = "";
1295 } else {
1296 if (!NodeUtil.isImmutableValue(value)) {
1297 return n;
1298 }
1299
1300 stringValue = NodeUtil.getStringValue(value);
1301 }
1302
1303 if (stringValue == null) {
1304 return n;
1305 }
1306
1307 Node parent = n.getParent();
1308 Node newString = IR.string(stringValue);
1309
1310 parent.replaceChild(n, newString);
1311 newString.copyInformationFrom(parent);
1312 reportCodeChange();
1313
1314 return newString;
1315 }
1316 return n;
1317 }
1318
1319 /**
1320 * Try to fold array-element. e.g [1, 2, 3][10];
1321 */
1322 private Node tryFoldGetElem(Node n, Node left, Node right) {
1323 Preconditions.checkArgument(n.isGetElem());
1324
1325 if (left.isObjectLit()) {
1326 return tryFoldObjectPropAccess(n, left, right);
1327 }
1328
1329 if (left.isArrayLit()) {
1330 return tryFoldArrayAccess(n, left, right);
1331 }
1332 return n;
1333 }
1334
1335 /**
1336 * Try to fold array-length. e.g [1, 2, 3].length ==> 3, [x, y].length ==> 2
1337 */
1338 private Node tryFoldGetProp(Node n, Node left, Node right) {
1339 Preconditions.checkArgument(n.isGetProp());
1340
1341 if (left.isObjectLit()) {
1342 return tryFoldObjectPropAccess(n, left, right);
1343 }
1344
1345 if (right.isString() &&
1346 right.getString().equals("length")) {
1347 int knownLength = -1;
1348 switch (left.getType()) {
1349 case Token.ARRAYLIT:
1350 if (mayHaveSideEffects(left)) {
1351 // Nope, can't fold this, without handling the side-effects.
1352 return n;
1353 }
1354 knownLength = left.getChildCount();
1355 break;
1356 case Token.STRING:
1357 knownLength = left.getString().length();
1358 break;
1359 default:
1360 // Not a foldable case, forget it.
1361 return n;
1362 }
1363
1364 Preconditions.checkState(knownLength != -1);
1365 Node lengthNode = IR.number(knownLength);
1366 n.getParent().replaceChild(n, lengthNode);
1367 reportCodeChange();
1368
1369 return lengthNode;
1370 }
1371
1372 return n;
1373 }
1374
1375 private boolean isAssignmentTarget(Node n) {
1376 Node parent = n.getParent();
1377 if ((NodeUtil.isAssignmentOp(parent) && parent.getFirstChild() == n)
1378 || parent.isInc()
1379 || parent.isDec()) {
1380 // If GETPROP/GETELEM is used as assignment target the object literal is
1381 // acting as a temporary we can't fold it here:
1382 // "{a:x}.a += 1" is not "x += 1"
1383 return true;
1384 }
1385 return false;
1386 }
1387
1388 private Node tryFoldArrayAccess(Node n, Node left, Node right) {
1389 // If GETPROP/GETELEM is used as assignment target the array literal is
1390 // acting as a temporary we can't fold it here:
1391 // "[][0] += 1"
1392 if (isAssignmentTarget(n)) {
1393 return n;
1394 }
1395
1396 if (!right.isNumber()) {
1397 // Sometimes people like to use complex expressions to index into
1398 // arrays, or strings to index into array methods.
1399 return n;
1400 }
1401
1402 double index = right.getDouble();
1403 int intIndex = (int) index;
1404 if (intIndex != index) {
1405 report(INVALID_GETELEM_INDEX_ERROR, right);
1406 return n;
1407 }
1408
1409 if (intIndex < 0) {
1410 report(INDEX_OUT_OF_BOUNDS_ERROR, right);
1411 return n;
1412 }
1413
1414 Node current = left.getFirstChild();
1415 Node elem = null;
1416 for (int i = 0; current != null; i++) {
1417 if (i != intIndex) {
1418 if (mayHaveSideEffects(current)) {
1419 return n;
1420 }
1421 } else {
1422 elem = current;
1423 }
1424
1425 current = current.getNext();
1426 }
1427
1428 if (elem == null) {
1429 report(INDEX_OUT_OF_BOUNDS_ERROR, right);
1430 return n;
1431 }
1432
1433 if (elem.isEmpty()) {
1434 elem = NodeUtil.newUndefinedNode(elem);
1435 } else {
1436 left.removeChild(elem);
1437 }
1438
1439 // Replace the entire GETELEM with the value
1440 n.getParent().replaceChild(n, elem);
1441 reportCodeChange();
1442 return elem;
1443 }
1444
1445 private Node tryFoldObjectPropAccess(Node n, Node left, Node right) {
1446 Preconditions.checkArgument(NodeUtil.isGet(n));
1447
1448 if (!left.isObjectLit() || !right.isString()) {
1449 return n;
1450 }
1451
1452 if (isAssignmentTarget(n)) {
1453 // If GETPROP/GETELEM is used as assignment target the object literal is
1454 // acting as a temporary we can't fold it here:
1455 // "{a:x}.a += 1" is not "x += 1"
1456 return n;
1457 }
1458
1459 // find the last definition in the object literal
1460 Node key = null;
1461 Node value = null;
1462 for (Node c = left.getFirstChild(); c != null; c = c.getNext()) {
1463 if (c.getString().equals(right.getString())) {
1464 switch (c.getType()) {
1465 case Token.SETTER_DEF:
1466 continue;
1467 case Token.GETTER_DEF:
1468 case Token.STRING_KEY:
1469 if (value != null && mayHaveSideEffects(value)) {
1470 // The previously found value had side-effects
1471 return n;
1472 }
1473 key = c;
1474 value = key.getFirstChild();
1475 break;
1476 default:
1477 throw new IllegalStateException();
1478 }
1479 } else if (mayHaveSideEffects(c.getFirstChild())) {
1480 // We don't handle the side-effects here as they might need a temporary
1481 // or need to be reordered.
1482 return n;
1483 }
1484 }
1485
1486 // Didn't find a definition of the name in the object literal, it might
1487 // be coming from the Object prototype
1488 if (value == null) {
1489 return n;
1490 }
1491
1492 if (value.isFunction() && NodeUtil.referencesThis(value)) {
1493 // 'this' may refer to the object we are trying to remove
1494 return n;
1495 }
1496
1497 Node replacement = value.detachFromParent();
1498 if (key.isGetterDef()){
1499 replacement = IR.call(replacement);
1500 replacement.putBooleanProp(Node.FREE_CALL, true);
1501 }
1502
1503 n.getParent().replaceChild(n, replacement);
1504 reportCodeChange();
1505 return n;
1506 }
1507 }