Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2010 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.Joiner;
20 import com.google.common.base.Preconditions;
21 import com.google.common.base.Predicate;
22 import com.google.common.collect.ImmutableSet;
23 import com.google.javascript.jscomp.CodingConvention.Bind;
24 import com.google.javascript.rhino.IR;
25 import com.google.javascript.rhino.Node;
26 import com.google.javascript.rhino.Token;
27 import com.google.javascript.rhino.jstype.TernaryValue;
28
29 import java.util.regex.Pattern;
30
31 /**
32 * A peephole optimization that minimizes code by simplifying conditional
33 * expressions, replacing IFs with HOOKs, replacing object constructors
34 * with literals, and simplifying returns.
35 *
36 */
37 class PeepholeSubstituteAlternateSyntax
38 extends AbstractPeepholeOptimization {
39
40 private static final int AND_PRECEDENCE = NodeUtil.precedence(Token.AND);
41 private static final int OR_PRECEDENCE = NodeUtil.precedence(Token.OR);
42 private static final int NOT_PRECEDENCE = NodeUtil.precedence(Token.NOT);
43 private static final CodeGenerator REGEXP_ESCAPER =
44 CodeGenerator.forCostEstimation(
45 null /* blow up if we try to produce code */);
46
47 private final boolean late;
48
49 private final int STRING_SPLIT_OVERHEAD = ".split('.')".length();
50
51 static final DiagnosticType INVALID_REGULAR_EXPRESSION_FLAGS =
52 DiagnosticType.warning(
53 "JSC_INVALID_REGULAR_EXPRESSION_FLAGS",
54 "Invalid flags to RegExp constructor: {0}");
55
56 static final Predicate<Node> DONT_TRAVERSE_FUNCTIONS_PREDICATE
57 = new Predicate<Node>() {
58 @Override
59 public boolean apply(Node input) {
60 return !input.isFunction();
61 }
62 };
63
64 /**
65 * @param late When late is false, this mean we are currently running before
66 * most of the other optimizations. In this case we would avoid optimizations
67 * that would make the code harder to analyze (such as using string splitting,
68 * merging statements with commas, etc). When this is true, we would
69 * do anything to minimize for size.
70 */
71 PeepholeSubstituteAlternateSyntax(boolean late) {
72 this.late = late;
73 }
74
75 /**
76 * Tries apply our various peephole minimizations on the passed in node.
77 */
78 @Override
79 @SuppressWarnings("fallthrough")
80 public Node optimizeSubtree(Node node) {
81 switch(node.getType()) {
82 case Token.RETURN: {
83 Node result = tryRemoveRedundantExit(node);
84 if (result != node) {
85 return result;
86 }
87 result = tryReplaceExitWithBreak(node);
88 if (result != node) {
89 return result;
90 }
91 return tryReduceReturn(node);
92 }
93
94 case Token.THROW: {
95 Node result = tryRemoveRedundantExit(node);
96 if (result != node) {
97 return result;
98 }
99 return tryReplaceExitWithBreak(node);
100 }
101
102 // TODO(johnlenz): Maybe remove redundant BREAK and CONTINUE. Overlaps
103 // with MinimizeExitPoints.
104
105 case Token.NOT:
106 tryMinimizeCondition(node.getFirstChild());
107 return tryMinimizeNot(node);
108
109 case Token.IF:
110 tryMinimizeCondition(node.getFirstChild());
111 return tryMinimizeIf(node);
112
113 case Token.EXPR_RESULT:
114 tryMinimizeCondition(node.getFirstChild());
115 return node;
116
117 case Token.HOOK:
118 tryMinimizeCondition(node.getFirstChild());
119 return node;
120
121 case Token.WHILE:
122 case Token.DO:
123 tryMinimizeCondition(NodeUtil.getConditionExpression(node));
124 return node;
125
126 case Token.FOR:
127 if (!NodeUtil.isForIn(node)) {
128 tryJoinForCondition(node);
129 tryMinimizeCondition(NodeUtil.getConditionExpression(node));
130 }
131 return node;
132
133 case Token.TRUE:
134 case Token.FALSE:
135 return reduceTrueFalse(node);
136
137 case Token.NEW:
138 node = tryFoldStandardConstructors(node);
139 if (!node.isCall()) {
140 return node;
141 }
142 // Fall through on purpose because tryFoldStandardConstructors() may
143 // convert a NEW node into a CALL node
144 case Token.CALL:
145 Node result = tryFoldLiteralConstructor(node);
146 if (result == node) {
147 result = tryFoldSimpleFunctionCall(node);
148 if (result == node) {
149 result = tryFoldImmediateCallToBoundFunction(node);
150 }
151 }
152 return result;
153
154 case Token.COMMA:
155 return trySplitComma(node);
156
157 case Token.NAME:
158 return tryReplaceUndefined(node);
159
160 case Token.BLOCK:
161 return tryReplaceIf(node);
162
163 case Token.ARRAYLIT:
164 return tryMinimizeArrayLiteral(node);
165
166 default:
167 return node; //Nothing changed
168 }
169 }
170
171 private void tryJoinForCondition(Node n) {
172 if (!late) {
173 return;
174 }
175
176 Node block = n.getLastChild();
177 Node maybeIf = block.getFirstChild();
178 if (maybeIf != null && maybeIf.isIf()) {
179 Node maybeBreak = maybeIf.getChildAtIndex(1).getFirstChild();
180 if (maybeBreak != null && maybeBreak.isBreak()
181 && !maybeBreak.hasChildren()) {
182
183 // Preserve the IF ELSE expression is there is one.
184 if (maybeIf.getChildCount() == 3) {
185 block.replaceChild(maybeIf,
186 maybeIf.getLastChild().detachFromParent());
187 } else {
188 block.removeFirstChild();
189 }
190
191 Node ifCondition = maybeIf.removeFirstChild();
192 Node fixedIfCondition = IR.not(ifCondition)
193 .srcref(ifCondition);
194
195 // OK, join the IF expression with the FOR expression
196 Node forCondition = NodeUtil.getConditionExpression(n);
197 if (forCondition.isEmpty()) {
198 n.replaceChild(forCondition, fixedIfCondition);
199 } else {
200 Node replacement = new Node(Token.AND);
201 n.replaceChild(forCondition, replacement);
202 replacement.addChildToBack(forCondition);
203 replacement.addChildToBack(fixedIfCondition);
204 }
205
206 reportCodeChange();
207 }
208 }
209 }
210
211 private Node tryFoldSimpleFunctionCall(Node n) {
212 Preconditions.checkState(n.isCall());
213 Node callTarget = n.getFirstChild();
214 if (callTarget != null && callTarget.isName() &&
215 callTarget.getString().equals("String")) {
216 // Fold String(a) to '' + (a) on immutable literals,
217 // which allows further optimizations
218 //
219 // We can't do this in the general case, because String(a) has
220 // slightly different semantics than '' + (a). See
221 // http://code.google.com/p/closure-compiler/issues/detail?id=759
222 Node value = callTarget.getNext();
223 if (value != null && value.getNext() == null &&
224 NodeUtil.isImmutableValue(value)) {
225 Node addition = IR.add(
226 IR.string("").srcref(callTarget),
227 value.detachFromParent());
228 n.getParent().replaceChild(n, addition);
229 reportCodeChange();
230 return addition;
231 }
232 }
233 return n;
234 }
235
236 private Node tryFoldImmediateCallToBoundFunction(Node n) {
237 // Rewriting "(fn.bind(a,b))()" to "fn.call(a,b)" makes it inlinable
238 Preconditions.checkState(n.isCall());
239 Node callTarget = n.getFirstChild();
240 Bind bind = getCodingConvention().describeFunctionBind(callTarget, false);
241 if (bind != null) {
242 // replace the call target
243 bind.target.detachFromParent();
244 n.replaceChild(callTarget, bind.target);
245 callTarget = bind.target;
246
247 // push the parameters
248 addParameterAfter(bind.parameters, callTarget);
249
250 // add the this value before the parameters if necessary
251 if (bind.thisValue != null && !NodeUtil.isUndefined(bind.thisValue)) {
252 // rewrite from "fn(a, b)" to "fn.call(thisValue, a, b)"
253 Node newCallTarget = IR.getprop(
254 callTarget.cloneTree(),
255 IR.string("call").srcref(callTarget));
256 n.replaceChild(callTarget, newCallTarget);
257 n.addChildAfter(bind.thisValue.cloneTree(), newCallTarget);
258 n.putBooleanProp(Node.FREE_CALL, false);
259 } else {
260 n.putBooleanProp(Node.FREE_CALL, true);
261 }
262 reportCodeChange();
263 }
264 return n;
265 }
266
267 private void addParameterAfter(Node parameterList, Node after) {
268 if (parameterList != null) {
269 // push the last parameter to the head of the list first.
270 addParameterAfter(parameterList.getNext(), after);
271 after.getParent().addChildAfter(parameterList.cloneTree(), after);
272 }
273 }
274
275 private Node trySplitComma(Node n) {
276 if (late) {
277 return n;
278 }
279 Node parent = n.getParent();
280 Node left = n.getFirstChild();
281 Node right = n.getLastChild();
282
283 if (parent.isExprResult()
284 && !parent.getParent().isLabel()) {
285 // split comma
286 n.detachChildren();
287 // Replace the original expression with the left operand.
288 parent.replaceChild(n, left);
289 // Add the right expression afterward.
290 Node newStatement = IR.exprResult(right);
291 newStatement.copyInformationFrom(n);
292
293 //This modifies outside the subtree, which is not
294 //desirable in a peephole optimization.
295 parent.getParent().addChildAfter(newStatement, parent);
296 reportCodeChange();
297 return left;
298 } else {
299 return n;
300 }
301 }
302
303 /**
304 * Use "return x?1:2;" in place of "if(x)return 1;return 2;"
305 */
306 private Node tryReplaceIf(Node n) {
307
308 for (Node child = n.getFirstChild();
309 child != null; child = child.getNext()){
310 if (child.isIf()){
311 Node cond = child.getFirstChild();
312 Node thenBranch = cond.getNext();
313 Node elseBranch = thenBranch.getNext();
314 Node nextNode = child.getNext();
315
316 if (nextNode != null && elseBranch == null
317 && isReturnBlock(thenBranch)
318 && nextNode.isIf()) {
319 Node nextCond = nextNode.getFirstChild();
320 Node nextThen = nextCond.getNext();
321 Node nextElse = nextThen.getNext();
322 if (thenBranch.isEquivalentToTyped(nextThen)) {
323 // Transform
324 // if (x) return 1; if (y) return 1;
325 // to
326 // if (x||y) return 1;
327 child.detachFromParent();
328 child.detachChildren();
329 Node newCond = new Node(Token.OR, cond);
330 nextNode.replaceChild(nextCond, newCond);
331 newCond.addChildToBack(nextCond);
332 reportCodeChange();
333 } else if (nextElse != null
334 && thenBranch.isEquivalentToTyped(nextElse)) {
335 // Transform
336 // if (x) return 1; if (y) foo() else return 1;
337 // to
338 // if (!x&&y) foo() else return 1;
339 child.detachFromParent();
340 child.detachChildren();
341 Node newCond = new Node(Token.AND,
342 IR.not(cond).srcref(cond));
343 nextNode.replaceChild(nextCond, newCond);
344 newCond.addChildToBack(nextCond);
345 reportCodeChange();
346 }
347 } else if (nextNode != null && elseBranch == null &&
348 isReturnBlock(thenBranch) && isReturnExpression(nextNode)) {
349 Node thenExpr = null;
350 // if(x)return; return 1 -> return x?void 0:1
351 if (isReturnExpressBlock(thenBranch)) {
352 thenExpr = getBlockReturnExpression(thenBranch);
353 thenExpr.detachFromParent();
354 } else {
355 thenExpr = NodeUtil.newUndefinedNode(child);
356 }
357
358 Node elseExpr = nextNode.getFirstChild();
359
360 cond.detachFromParent();
361 elseExpr.detachFromParent();
362
363 Node returnNode = IR.returnNode(
364 IR.hook(cond, thenExpr, elseExpr)
365 .srcref(child));
366 n.replaceChild(child, returnNode);
367 n.removeChild(nextNode);
368 reportCodeChange();
369 } else if (elseBranch != null && statementMustExitParent(thenBranch)) {
370 child.removeChild(elseBranch);
371 n.addChildAfter(elseBranch, child);
372 reportCodeChange();
373 }
374 }
375 }
376 return n;
377 }
378
379 private boolean statementMustExitParent(Node n) {
380 switch (n.getType()) {
381 case Token.THROW:
382 case Token.RETURN:
383 return true;
384 case Token.BLOCK:
385 if (n.hasChildren()) {
386 Node child = n.getLastChild();
387 return statementMustExitParent(child);
388 }
389 return false;
390 // TODO(johnlenz): handle TRY/FINALLY
391 case Token.FUNCTION:
392 default:
393 return false;
394 }
395 }
396
397 /**
398 * Use "void 0" in place of "undefined"
399 */
400 private Node tryReplaceUndefined(Node n) {
401 // TODO(johnlenz): consider doing this as a normalization.
402 if (isASTNormalized()
403 && NodeUtil.isUndefined(n)
404 && !NodeUtil.isLValue(n)) {
405 Node replacement = NodeUtil.newUndefinedNode(n);
406 n.getParent().replaceChild(n, replacement);
407 reportCodeChange();
408 return replacement;
409 }
410 return n;
411 }
412
413 /**
414 * Reduce "return undefined" or "return void 0" to simply "return".
415 *
416 * @return The original node, maybe simplified.
417 */
418 private Node tryReduceReturn(Node n) {
419 Node result = n.getFirstChild();
420
421 if (result != null) {
422 switch (result.getType()) {
423 case Token.VOID:
424 Node operand = result.getFirstChild();
425 if (!mayHaveSideEffects(operand)) {
426 n.removeFirstChild();
427 reportCodeChange();
428 }
429 break;
430 case Token.NAME:
431 String name = result.getString();
432 if (name.equals("undefined")) {
433 n.removeFirstChild();
434 reportCodeChange();
435 }
436 break;
437 }
438 }
439
440 return n;
441 }
442
443 /**
444 * Replace duplicate exits in control structures. If the node following
445 * the exit node expression has the same effect as exit node, the node can
446 * be replaced or removed.
447 * For example:
448 * "while (a) {return f()} return f();" ==> "while (a) {break} return f();"
449 * "while (a) {throw 'ow'} throw 'ow';" ==> "while (a) {break} throw 'ow';"
450 *
451 * @param n An follow control exit expression (a THROW or RETURN node)
452 * @return The replacement for n, or the original if no change was made.
453 */
454 private Node tryReplaceExitWithBreak(Node n) {
455 Node result = n.getFirstChild();
456
457 // Find the enclosing control structure, if any, that a "break" would exit
458 // from.
459 Node breakTarget = n;
460 for (;!ControlFlowAnalysis.isBreakTarget(breakTarget, null /* no label */);
461 breakTarget = breakTarget.getParent()) {
462 if (breakTarget.isFunction() || breakTarget.isScript()) {
463 // No break target.
464 return n;
465 }
466 }
467
468 Node follow = ControlFlowAnalysis.computeFollowNode(breakTarget);
469
470 // Skip pass all the finally blocks because both the break and return will
471 // also trigger all the finally blocks. However, the order of execution is
472 // slightly changed. Consider:
473 //
474 // return a() -> finally { b() } -> return a()
475 //
476 // which would call a() first. However, changing the first return to a
477 // break will result in calling b().
478
479 Node prefinallyFollows = follow;
480 follow = skipFinallyNodes(follow);
481
482 if (prefinallyFollows != follow) {
483 // There were finally clauses
484 if (!isPure(result)) {
485 // Can't defer the exit
486 return n;
487 }
488 }
489
490 if (follow == null && (n.isThrow() || result != null)) {
491 // Can't complete remove a throw here or a return with a result.
492 return n;
493 }
494
495 // When follow is null, this mean the follow of a break target is the
496 // end of a function. This means a break is same as return.
497 if (follow == null || areMatchingExits(n, follow)) {
498 Node replacement = IR.breakNode();
499 n.getParent().replaceChild(n, replacement);
500 this.reportCodeChange();
501 return replacement;
502 }
503
504 return n;
505 }
506
507 /**
508 * Remove duplicate exits. If the node following the exit node expression
509 * has the same effect as exit node, the node can be removed.
510 * For example:
511 * "if (a) {return f()} return f();" ==> "if (a) {} return f();"
512 * "if (a) {throw 'ow'} throw 'ow';" ==> "if (a) {} throw 'ow';"
513 *
514 * @param n An follow control exit expression (a THROW or RETURN node)
515 * @return The replacement for n, or the original if no change was made.
516 */
517 private Node tryRemoveRedundantExit(Node n) {
518 Node exitExpr = n.getFirstChild();
519
520 Node follow = ControlFlowAnalysis.computeFollowNode(n);
521
522 // Skip pass all the finally blocks because both the fall through and return
523 // will also trigger all the finally blocks.
524 Node prefinallyFollows = follow;
525 follow = skipFinallyNodes(follow);
526 if (prefinallyFollows != follow) {
527 // There were finally clauses
528 if (!isPure(exitExpr)) {
529 // Can't replace the return
530 return n;
531 }
532 }
533
534 if (follow == null && (n.isThrow() || exitExpr != null)) {
535 // Can't complete remove a throw here or a return with a result.
536 return n;
537 }
538
539 // When follow is null, this mean the follow of a break target is the
540 // end of a function. This means a break is same as return.
541 if (follow == null || areMatchingExits(n, follow)) {
542 n.detachFromParent();
543 reportCodeChange();
544 return null;
545 }
546
547 return n;
548 }
549
550 /**
551 * @return Whether the expression does not produces and can not be affected
552 * by side-effects.
553 */
554 boolean isPure(Node n) {
555 return n == null
556 || (!NodeUtil.canBeSideEffected(n)
557 && !mayHaveSideEffects(n));
558 }
559
560 /**
561 * @return n or the node following any following finally nodes.
562 */
563 Node skipFinallyNodes(Node n) {
564 while (n != null && NodeUtil.isTryFinallyNode(n.getParent(), n)) {
565 n = ControlFlowAnalysis.computeFollowNode(n);
566 }
567 return n;
568 }
569
570 /**
571 * Check whether one exit can be replaced with another. Verify:
572 * 1) They are identical expressions
573 * 2) If an exception is possible that the statements, the original
574 * and the potential replacement are in the same exception handler.
575 */
576 boolean areMatchingExits(Node nodeThis, Node nodeThat) {
577 return nodeThis.isEquivalentTo(nodeThat)
578 && (!isExceptionPossible(nodeThis)
579 || getExceptionHandler(nodeThis) == getExceptionHandler(nodeThat));
580 }
581
582 boolean isExceptionPossible(Node n) {
583 // TODO(johnlenz): maybe use ControlFlowAnalysis.mayThrowException?
584 Preconditions.checkState(n.isReturn()
585 || n.isThrow());
586 return n.isThrow()
587 || (n.hasChildren()
588 && !NodeUtil.isLiteralValue(n.getLastChild(), true));
589 }
590
591 Node getExceptionHandler(Node n) {
592 return ControlFlowAnalysis.getExceptionHandler(n);
593 }
594
595 /**
596 * Try to minimize NOT nodes such as !(x==y).
597 *
598 * Returns the replacement for n or the original if no change was made
599 */
600 private Node tryMinimizeNot(Node n) {
601 Node parent = n.getParent();
602
603 Node notChild = n.getFirstChild();
604 // negative operator of the current one : == -> != for instance.
605 int complementOperator;
606 switch (notChild.getType()) {
607 case Token.EQ:
608 complementOperator = Token.NE;
609 break;
610 case Token.NE:
611 complementOperator = Token.EQ;
612 break;
613 case Token.SHEQ:
614 complementOperator = Token.SHNE;
615 break;
616 case Token.SHNE:
617 complementOperator = Token.SHEQ;
618 break;
619 // GT, GE, LT, LE are not handled in this because !(x<NaN) != x>=NaN.
620 default:
621 return n;
622 }
623 Node newOperator = n.removeFirstChild();
624 newOperator.setType(complementOperator);
625 parent.replaceChild(n, newOperator);
626 reportCodeChange();
627 return newOperator;
628 }
629
630 /**
631 * Try turning IF nodes into smaller HOOKs
632 *
633 * Returns the replacement for n or the original if no replacement was
634 * necessary.
635 */
636 private Node tryMinimizeIf(Node n) {
637
638 Node parent = n.getParent();
639
640 Node cond = n.getFirstChild();
641
642 /* If the condition is a literal, we'll let other
643 * optimizations try to remove useless code.
644 */
645 if (NodeUtil.isLiteralValue(cond, true)) {
646 return n;
647 }
648
649 Node thenBranch = cond.getNext();
650 Node elseBranch = thenBranch.getNext();
651
652 if (elseBranch == null) {
653 if (isFoldableExpressBlock(thenBranch)) {
654 Node expr = getBlockExpression(thenBranch);
655 if (!late && isPropertyAssignmentInExpression(expr)) {
656 // Keep opportunities for CollapseProperties such as
657 // a.longIdentifier || a.longIdentifier = ... -> var a = ...;
658 // until CollapseProperties has been run.
659 return n;
660 }
661
662 if (cond.isNot()) {
663 // if(!x)bar(); -> x||bar();
664 if (isLowerPrecedenceInExpression(cond, OR_PRECEDENCE) &&
665 isLowerPrecedenceInExpression(expr.getFirstChild(),
666 OR_PRECEDENCE)) {
667 // It's not okay to add two sets of parentheses.
668 return n;
669 }
670
671 Node or = IR.or(
672 cond.removeFirstChild(),
673 expr.removeFirstChild()).srcref(n);
674 Node newExpr = NodeUtil.newExpr(or);
675 parent.replaceChild(n, newExpr);
676 reportCodeChange();
677
678 return newExpr;
679 }
680
681 // if(x)foo(); -> x&&foo();
682 if (isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) &&
683 isLowerPrecedenceInExpression(expr.getFirstChild(),
684 AND_PRECEDENCE)) {
685 // One additional set of parentheses is worth the change even if
686 // there is no immediate code size win. However, two extra pair of
687 // {}, we would have to think twice. (unless we know for sure the
688 // we can further optimize its parent.
689 return n;
690 }
691
692 n.removeChild(cond);
693 Node and = IR.and(cond, expr.removeFirstChild()).srcref(n);
694 Node newExpr = NodeUtil.newExpr(and);
695 parent.replaceChild(n, newExpr);
696 reportCodeChange();
697
698 return newExpr;
699 } else {
700
701 // Try to combine two IF-ELSE
702 if (NodeUtil.isStatementBlock(thenBranch) &&
703 thenBranch.hasOneChild()) {
704 Node innerIf = thenBranch.getFirstChild();
705
706 if (innerIf.isIf()) {
707 Node innerCond = innerIf.getFirstChild();
708 Node innerThenBranch = innerCond.getNext();
709 Node innerElseBranch = innerThenBranch.getNext();
710
711 if (innerElseBranch == null &&
712 !(isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) &&
713 isLowerPrecedenceInExpression(innerCond, AND_PRECEDENCE))) {
714 n.detachChildren();
715 n.addChildToBack(
716 IR.and(
717 cond,
718 innerCond.detachFromParent())
719 .srcref(cond));
720 n.addChildrenToBack(innerThenBranch.detachFromParent());
721 reportCodeChange();
722 // Not worth trying to fold the current IF-ELSE into && because
723 // the inner IF-ELSE wasn't able to be folded into && anyways.
724 return n;
725 }
726 }
727 }
728 }
729
730 return n;
731 }
732
733 /* TODO(dcc) This modifies the siblings of n, which is undesirable for a
734 * peephole optimization. This should probably get moved to another pass.
735 */
736 tryRemoveRepeatedStatements(n);
737
738 // if(!x)foo();else bar(); -> if(x)bar();else foo();
739 // An additional set of curly braces isn't worth it.
740 if (cond.isNot() && !consumesDanglingElse(elseBranch)) {
741 n.replaceChild(cond, cond.removeFirstChild());
742 n.removeChild(thenBranch);
743 n.addChildToBack(thenBranch);
744 reportCodeChange();
745 return n;
746 }
747
748 // if(x)return 1;else return 2; -> return x?1:2;
749 if (isReturnExpressBlock(thenBranch) && isReturnExpressBlock(elseBranch)) {
750 Node thenExpr = getBlockReturnExpression(thenBranch);
751 Node elseExpr = getBlockReturnExpression(elseBranch);
752 n.removeChild(cond);
753 thenExpr.detachFromParent();
754 elseExpr.detachFromParent();
755
756 // note - we ignore any cases with "return;", technically this
757 // can be converted to "return undefined;" or some variant, but
758 // that does not help code size.
759 Node returnNode = IR.returnNode(
760 IR.hook(cond, thenExpr, elseExpr)
761 .srcref(n));
762 parent.replaceChild(n, returnNode);
763 reportCodeChange();
764 return returnNode;
765 }
766
767 boolean thenBranchIsExpressionBlock = isFoldableExpressBlock(thenBranch);
768 boolean elseBranchIsExpressionBlock = isFoldableExpressBlock(elseBranch);
769
770 if (thenBranchIsExpressionBlock && elseBranchIsExpressionBlock) {
771 Node thenOp = getBlockExpression(thenBranch).getFirstChild();
772 Node elseOp = getBlockExpression(elseBranch).getFirstChild();
773 if (thenOp.getType() == elseOp.getType()) {
774 // if(x)a=1;else a=2; -> a=x?1:2;
775 if (NodeUtil.isAssignmentOp(thenOp)) {
776 Node lhs = thenOp.getFirstChild();
777 if (areNodesEqualForInlining(lhs, elseOp.getFirstChild()) &&
778 // if LHS has side effects, don't proceed [since the optimization
779 // evaluates LHS before cond]
780 // NOTE - there are some circumstances where we can
781 // proceed even if there are side effects...
782 !mayEffectMutableState(lhs) &&
783 (!mayHaveSideEffects(cond) ||
784 (thenOp.isAssign() && thenOp.getFirstChild().isName()))) {
785
786 n.removeChild(cond);
787 Node assignName = thenOp.removeFirstChild();
788 Node thenExpr = thenOp.removeFirstChild();
789 Node elseExpr = elseOp.getLastChild();
790 elseOp.removeChild(elseExpr);
791
792 Node hookNode = IR.hook(cond, thenExpr, elseExpr).srcref(n);
793 Node assign = new Node(thenOp.getType(), assignName, hookNode)
794 .srcref(thenOp);
795 Node expr = NodeUtil.newExpr(assign);
796 parent.replaceChild(n, expr);
797 reportCodeChange();
798
799 return expr;
800 }
801 }
802 }
803 // if(x)foo();else bar(); -> x?foo():bar()
804 n.removeChild(cond);
805 thenOp.detachFromParent();
806 elseOp.detachFromParent();
807 Node expr = IR.exprResult(
808 IR.hook(cond, thenOp, elseOp).srcref(n));
809 parent.replaceChild(n, expr);
810 reportCodeChange();
811 return expr;
812 }
813
814 boolean thenBranchIsVar = isVarBlock(thenBranch);
815 boolean elseBranchIsVar = isVarBlock(elseBranch);
816
817 // if(x)var y=1;else y=2 -> var y=x?1:2
818 if (thenBranchIsVar && elseBranchIsExpressionBlock &&
819 getBlockExpression(elseBranch).getFirstChild().isAssign()) {
820
821 Node var = getBlockVar(thenBranch);
822 Node elseAssign = getBlockExpression(elseBranch).getFirstChild();
823
824 Node name1 = var.getFirstChild();
825 Node maybeName2 = elseAssign.getFirstChild();
826
827 if (name1.hasChildren()
828 && maybeName2.isName()
829 && name1.getString().equals(maybeName2.getString())) {
830 Node thenExpr = name1.removeChildren();
831 Node elseExpr = elseAssign.getLastChild().detachFromParent();
832 cond.detachFromParent();
833 Node hookNode = IR.hook(cond, thenExpr, elseExpr)
834 .srcref(n);
835 var.detachFromParent();
836 name1.addChildrenToBack(hookNode);
837 parent.replaceChild(n, var);
838 reportCodeChange();
839 return var;
840 }
841
842 // if(x)y=1;else var y=2 -> var y=x?1:2
843 } else if (elseBranchIsVar && thenBranchIsExpressionBlock &&
844 getBlockExpression(thenBranch).getFirstChild().isAssign()) {
845
846 Node var = getBlockVar(elseBranch);
847 Node thenAssign = getBlockExpression(thenBranch).getFirstChild();
848
849 Node maybeName1 = thenAssign.getFirstChild();
850 Node name2 = var.getFirstChild();
851
852 if (name2.hasChildren()
853 && maybeName1.isName()
854 && maybeName1.getString().equals(name2.getString())) {
855 Node thenExpr = thenAssign.getLastChild().detachFromParent();
856 Node elseExpr = name2.removeChildren();
857 cond.detachFromParent();
858 Node hookNode = IR.hook(cond, thenExpr, elseExpr)
859 .srcref(n);
860 var.detachFromParent();
861 name2.addChildrenToBack(hookNode);
862 parent.replaceChild(n, var);
863 reportCodeChange();
864
865 return var;
866 }
867 }
868
869 return n;
870 }
871
872 /**
873 * Try to remove duplicate statements from IF blocks. For example:
874 *
875 * if (a) {
876 * x = 1;
877 * return true;
878 * } else {
879 * x = 2;
880 * return true;
881 * }
882 *
883 * becomes:
884 *
885 * if (a) {
886 * x = 1;
887 * } else {
888 * x = 2;
889 * }
890 * return true;
891 *
892 * @param n The IF node to examine.
893 */
894 private void tryRemoveRepeatedStatements(Node n) {
895 Preconditions.checkState(n.isIf());
896
897 Node parent = n.getParent();
898 if (!NodeUtil.isStatementBlock(parent)) {
899 // If the immediate parent is something like a label, we
900 // can't move the statement, so bail.
901 return;
902 }
903
904 Node cond = n.getFirstChild();
905 Node trueBranch = cond.getNext();
906 Node falseBranch = trueBranch.getNext();
907 Preconditions.checkNotNull(trueBranch);
908 Preconditions.checkNotNull(falseBranch);
909
910 while (true) {
911 Node lastTrue = trueBranch.getLastChild();
912 Node lastFalse = falseBranch.getLastChild();
913 if (lastTrue == null || lastFalse == null
914 || !areNodesEqualForInlining(lastTrue, lastFalse)) {
915 break;
916 }
917 lastTrue.detachFromParent();
918 lastFalse.detachFromParent();
919 parent.addChildAfter(lastTrue, n);
920 reportCodeChange();
921 }
922 }
923
924 /**
925 * @return Whether the node is a block with a single statement that is
926 * an expression.
927 */
928 private boolean isFoldableExpressBlock(Node n) {
929 if (n.isBlock()) {
930 if (n.hasOneChild()) {
931 Node maybeExpr = n.getFirstChild();
932 if (maybeExpr.isExprResult()) {
933 // IE has a bug where event handlers behave differently when
934 // their return value is used vs. when their return value is in
935 // an EXPR_RESULT. It's pretty freaking weird. See:
936 // http://code.google.com/p/closure-compiler/issues/detail?id=291
937 // We try to detect this case, and not fold EXPR_RESULTs
938 // into other expressions.
939 if (maybeExpr.getFirstChild().isCall()) {
940 Node calledFn = maybeExpr.getFirstChild().getFirstChild();
941
942 // We only have to worry about methods with an implicit 'this'
943 // param, or this doesn't happen.
944 if (calledFn.isGetElem()) {
945 return false;
946 } else if (calledFn.isGetProp() &&
947 calledFn.getLastChild().getString().startsWith("on")) {
948 return false;
949 }
950 }
951
952 return true;
953 }
954 return false;
955 }
956 }
957
958 return false;
959 }
960
961 /**
962 * @return The expression node.
963 */
964 private Node getBlockExpression(Node n) {
965 Preconditions.checkState(isFoldableExpressBlock(n));
966 return n.getFirstChild();
967 }
968
969 /**
970 * @return Whether the node is a block with a single statement that is
971 * an return with or without an expression.
972 */
973 private boolean isReturnBlock(Node n) {
974 if (n.isBlock()) {
975 if (n.hasOneChild()) {
976 Node first = n.getFirstChild();
977 return first.isReturn();
978 }
979 }
980
981 return false;
982 }
983
984 /**
985 * @return Whether the node is a block with a single statement that is
986 * an return.
987 */
988 private boolean isReturnExpressBlock(Node n) {
989 if (n.isBlock()) {
990 if (n.hasOneChild()) {
991 Node first = n.getFirstChild();
992 if (first.isReturn()) {
993 return first.hasOneChild();
994 }
995 }
996 }
997
998 return false;
999 }
1000
1001 /**
1002 * @return Whether the node is a single return statement.
1003 */
1004 private boolean isReturnExpression(Node n) {
1005 if (n.isReturn()) {
1006 return n.hasOneChild();
1007 }
1008 return false;
1009 }
1010
1011 /**
1012 * @return The expression that is part of the return.
1013 */
1014 private Node getBlockReturnExpression(Node n) {
1015 Preconditions.checkState(isReturnExpressBlock(n));
1016 return n.getFirstChild().getFirstChild();
1017 }
1018
1019 /**
1020 * @return Whether the node is a block with a single statement that is
1021 * a VAR declaration of a single variable.
1022 */
1023 private boolean isVarBlock(Node n) {
1024 if (n.isBlock()) {
1025 if (n.hasOneChild()) {
1026 Node first = n.getFirstChild();
1027 if (first.isVar()) {
1028 return first.hasOneChild();
1029 }
1030 }
1031 }
1032
1033 return false;
1034 }
1035
1036 /**
1037 * @return The var node.
1038 */
1039 private Node getBlockVar(Node n) {
1040 Preconditions.checkState(isVarBlock(n));
1041 return n.getFirstChild();
1042 }
1043
1044 /**
1045 * Does a statement consume a 'dangling else'? A statement consumes
1046 * a 'dangling else' if an 'else' token following the statement
1047 * would be considered by the parser to be part of the statement.
1048 */
1049 private boolean consumesDanglingElse(Node n) {
1050 while (true) {
1051 switch (n.getType()) {
1052 case Token.IF:
1053 if (n.getChildCount() < 3) {
1054 return true;
1055 }
1056 // This IF node has no else clause.
1057 n = n.getLastChild();
1058 continue;
1059 case Token.WITH:
1060 case Token.WHILE:
1061 case Token.FOR:
1062 n = n.getLastChild();
1063 continue;
1064 default:
1065 return false;
1066 }
1067 }
1068 }
1069
1070 /**
1071 * Does the expression contain an operator with lower precedence than
1072 * the argument?
1073 */
1074 private boolean isLowerPrecedenceInExpression(Node n,
1075 final int precedence) {
1076 Predicate<Node> isLowerPrecedencePredicate = new Predicate<Node>() {
1077 @Override
1078 public boolean apply(Node input) {
1079 return NodeUtil.precedence(input.getType()) < precedence;
1080 }
1081 };
1082
1083 return NodeUtil.has(n, isLowerPrecedencePredicate,
1084 DONT_TRAVERSE_FUNCTIONS_PREDICATE);
1085 }
1086
1087 /**
1088 * Whether the node type has lower precedence than "precedence"
1089 */
1090 private boolean isLowerPrecedence(Node n, final int precedence) {
1091 return NodeUtil.precedence(n.getType()) < precedence;
1092 }
1093
1094 /**
1095 * Whether the node type has higher precedence than "precedence"
1096 */
1097 private boolean isHigherPrecedence(Node n, final int precedence) {
1098 return NodeUtil.precedence(n.getType()) > precedence;
1099 }
1100 /**
1101 * Does the expression contain a property assignment?
1102 */
1103 private boolean isPropertyAssignmentInExpression(Node n) {
1104 Predicate<Node> isPropertyAssignmentInExpressionPredicate =
1105 new Predicate<Node>() {
1106 @Override
1107 public boolean apply(Node input) {
1108 return (input.isGetProp() &&
1109 input.getParent().isAssign());
1110 }
1111 };
1112
1113 return NodeUtil.has(n, isPropertyAssignmentInExpressionPredicate,
1114 DONT_TRAVERSE_FUNCTIONS_PREDICATE);
1115 }
1116
1117 /**
1118 * Try to minimize conditions expressions, as there are additional
1119 * assumptions that can be made when it is known that the final result
1120 * is a boolean.
1121 *
1122 * The following transformations are done recursively:
1123 * !(x||y) --> !x&&!y
1124 * !(x&&y) --> !x||!y
1125 * !!x --> x
1126 * Thus:
1127 * !(x&&!y) --> !x||!!y --> !x||y
1128 *
1129 * Returns the replacement for n, or the original if no change was made
1130 */
1131 private Node tryMinimizeCondition(Node n) {
1132 Node parent = n.getParent();
1133
1134 switch (n.getType()) {
1135 case Token.NOT:
1136 Node first = n.getFirstChild();
1137 switch (first.getType()) {
1138 case Token.NOT: {
1139 Node newRoot = first.removeFirstChild();
1140 parent.replaceChild(n, newRoot);
1141 reportCodeChange();
1142 // No need to traverse, tryMinimizeCondition is called on the
1143 // NOT children are handled below.
1144 return newRoot;
1145 }
1146 case Token.AND:
1147 case Token.OR: {
1148 // !(!x && !y) --> x || y
1149 // !(!x || !y) --> x && y
1150 // !(!x && y) --> x || !y
1151 // !(!x || y) --> x && !y
1152 // !(x && !y) --> !x || y
1153 // !(x || !y) --> !x && y
1154 // !(x && y) --> !x || !y
1155 // !(x || y) --> !x && !y
1156 Node leftParent = first.getFirstChild();
1157 Node rightParent = first.getLastChild();
1158 Node left, right;
1159
1160 // Check special case when such transformation cannot reduce
1161 // due to the added ()
1162 // It only occurs when both of expressions are not NOT expressions
1163 if (!leftParent.isNot()
1164 && !rightParent.isNot()) {
1165 // If an expression has higher precedence than && or ||,
1166 // but lower precedence than NOT, an additional () is needed
1167 // Thus we do not preceed
1168 int op_precedence = NodeUtil.precedence(first.getType());
1169 if ((isLowerPrecedence(leftParent, NOT_PRECEDENCE)
1170 && isHigherPrecedence(leftParent, op_precedence))
1171 || (isLowerPrecedence(rightParent, NOT_PRECEDENCE)
1172 && isHigherPrecedence(rightParent, op_precedence))) {
1173 return n;
1174 }
1175 }
1176
1177 if (leftParent.isNot()) {
1178 left = leftParent.removeFirstChild();
1179 } else {
1180 leftParent.detachFromParent();
1181 left = IR.not(leftParent).srcref(leftParent);
1182 }
1183 if (rightParent.isNot()) {
1184 right = rightParent.removeFirstChild();
1185 } else {
1186 rightParent.detachFromParent();
1187 right = IR.not(rightParent).srcref(rightParent);
1188 }
1189
1190 int newOp = (first.isAnd()) ? Token.OR : Token.AND;
1191 Node newRoot = new Node(newOp, left, right);
1192 parent.replaceChild(n, newRoot);
1193 reportCodeChange();
1194 // No need to traverse, tryMinimizeCondition is called on the
1195 // AND and OR children below.
1196 return newRoot;
1197 }
1198
1199 default:
1200 TernaryValue nVal = NodeUtil.getPureBooleanValue(first);
1201 if (nVal != TernaryValue.UNKNOWN) {
1202 boolean result = nVal.not().toBoolean(true);
1203 int equivalentResult = result ? 1 : 0;
1204 return maybeReplaceChildWithNumber(n, parent, equivalentResult);
1205 }
1206 }
1207 // No need to traverse, tryMinimizeCondition is called on the NOT
1208 // children in the general case in the main post-order traversal.
1209 return n;
1210
1211 case Token.OR:
1212 case Token.AND: {
1213 Node left = n.getFirstChild();
1214 Node right = n.getLastChild();
1215
1216 // Because the expression is in a boolean context minimize
1217 // the children, this can't be done in the general case.
1218 left = tryMinimizeCondition(left);
1219 right = tryMinimizeCondition(right);
1220
1221 // Remove useless conditionals
1222 // Handle four cases:
1223 // x || false --> x
1224 // x || true --> true
1225 // x && true --> x
1226 // x && false --> false
1227 TernaryValue rightVal = NodeUtil.getPureBooleanValue(right);
1228 if (NodeUtil.getPureBooleanValue(right) != TernaryValue.UNKNOWN) {
1229 int type = n.getType();
1230 Node replacement = null;
1231 boolean rval = rightVal.toBoolean(true);
1232
1233 // (x || FALSE) => x
1234 // (x && TRUE) => x
1235 if (type == Token.OR && !rval ||
1236 type == Token.AND && rval) {
1237 replacement = left;
1238 } else if (!mayHaveSideEffects(left)) {
1239 replacement = right;
1240 }
1241
1242 if (replacement != null) {
1243 n.detachChildren();
1244 parent.replaceChild(n, replacement);
1245 reportCodeChange();
1246 return replacement;
1247 }
1248 }
1249 return n;
1250 }
1251
1252 case Token.HOOK: {
1253 Node condition = n.getFirstChild();
1254 Node trueNode = n.getFirstChild().getNext();
1255 Node falseNode = n.getLastChild();
1256
1257 // Because the expression is in a boolean context minimize
1258 // the result children, this can't be done in the general case.
1259 // The condition is handled in the general case in #optimizeSubtree
1260 trueNode = tryMinimizeCondition(trueNode);
1261 falseNode = tryMinimizeCondition(falseNode);
1262
1263 // Handle four cases:
1264 // x ? true : false --> x
1265 // x ? false : true --> !x
1266 // x ? true : y --> x || y
1267 // x ? y : false --> x && y
1268 Node replacement = null;
1269 TernaryValue trueNodeVal = NodeUtil.getPureBooleanValue(trueNode);
1270 TernaryValue falseNodeVal = NodeUtil.getPureBooleanValue(falseNode);
1271 if (trueNodeVal == TernaryValue.TRUE
1272 && falseNodeVal == TernaryValue.FALSE) {
1273 // Remove useless conditionals, keep the condition
1274 condition.detachFromParent();
1275 replacement = condition;
1276 } else if (trueNodeVal == TernaryValue.FALSE
1277 && falseNodeVal == TernaryValue.TRUE) {
1278 // Remove useless conditionals, keep the condition
1279 condition.detachFromParent();
1280 replacement = IR.not(condition);
1281 } else if (trueNodeVal == TernaryValue.TRUE) {
1282 // Remove useless true case.
1283 n.detachChildren();
1284 replacement = IR.or(condition, falseNode);
1285 } else if (falseNodeVal == TernaryValue.FALSE) {
1286 // Remove useless false case
1287 n.detachChildren();
1288 replacement = IR.and(condition, trueNode);
1289 }
1290
1291 if (replacement != null) {
1292 parent.replaceChild(n, replacement);
1293 n = replacement;
1294 reportCodeChange();
1295 }
1296
1297 return n;
1298 }
1299
1300 default:
1301 // while(true) --> while(1)
1302 TernaryValue nVal = NodeUtil.getPureBooleanValue(n);
1303 if (nVal != TernaryValue.UNKNOWN) {
1304 boolean result = nVal.toBoolean(true);
1305 int equivalentResult = result ? 1 : 0;
1306 return maybeReplaceChildWithNumber(n, parent, equivalentResult);
1307 }
1308 // We can't do anything else currently.
1309 return n;
1310 }
1311 }
1312
1313 /**
1314 * Replaces a node with a number node if the new number node is not equivalent
1315 * to the current node.
1316 *
1317 * Returns the replacement for n if it was replaced, otherwise returns n.
1318 */
1319 private Node maybeReplaceChildWithNumber(Node n, Node parent, int num) {
1320 Node newNode = IR.number(num);
1321 if (!newNode.isEquivalentTo(n)) {
1322 parent.replaceChild(n, newNode);
1323 reportCodeChange();
1324
1325 return newNode;
1326 }
1327
1328 return n;
1329 }
1330
1331 private static final ImmutableSet<String> STANDARD_OBJECT_CONSTRUCTORS =
1332 // String, Number, and Boolean functions return non-object types, whereas
1333 // new String, new Number, and new Boolean return object types, so don't
1334 // include them here.
1335 ImmutableSet.of(
1336 "Object",
1337 "Array",
1338 "RegExp",
1339 "Error"
1340 );
1341
1342 /**
1343 * Fold "new Object()" to "Object()".
1344 */
1345 private Node tryFoldStandardConstructors(Node n) {
1346 Preconditions.checkState(n.isNew());
1347
1348 // If name normalization has been run then we know that
1349 // new Object() does in fact refer to what we think it is
1350 // and not some custom-defined Object().
1351 if (isASTNormalized()) {
1352 if (n.getFirstChild().isName()) {
1353 String className = n.getFirstChild().getString();
1354 if (STANDARD_OBJECT_CONSTRUCTORS.contains(className)) {
1355 n.setType(Token.CALL);
1356 n.putBooleanProp(Node.FREE_CALL, true);
1357 reportCodeChange();
1358 }
1359 }
1360 }
1361
1362 return n;
1363 }
1364
1365 /**
1366 * Replaces a new Array or Object node with an object literal, unless the
1367 * call to Array or Object is to a local function with the same name.
1368 */
1369 private Node tryFoldLiteralConstructor(Node n) {
1370 Preconditions.checkArgument(n.isCall()
1371 || n.isNew());
1372
1373 Node constructorNameNode = n.getFirstChild();
1374
1375 Node newLiteralNode = null;
1376
1377 // We require the AST to be normalized to ensure that, say,
1378 // Object() really refers to the built-in Object constructor
1379 // and not a user-defined constructor with the same name.
1380
1381 if (isASTNormalized() && Token.NAME == constructorNameNode.getType()) {
1382
1383 String className = constructorNameNode.getString();
1384
1385 if ("RegExp".equals(className)) {
1386 // "RegExp("boo", "g")" --> /boo/g
1387 return tryFoldRegularExpressionConstructor(n);
1388 } else {
1389 boolean constructorHasArgs = constructorNameNode.getNext() != null;
1390
1391 if ("Object".equals(className) && !constructorHasArgs) {
1392 // "Object()" --> "{}"
1393 newLiteralNode = IR.objectlit();
1394 } else if ("Array".equals(className)) {
1395 // "Array(arg0, arg1, ...)" --> "[arg0, arg1, ...]"
1396 Node arg0 = constructorNameNode.getNext();
1397 FoldArrayAction action = isSafeToFoldArrayConstructor(arg0);
1398
1399 if (action == FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS ||
1400 action == FoldArrayAction.SAFE_TO_FOLD_WITHOUT_ARGS) {
1401 newLiteralNode = IR.arraylit();
1402 n.removeChildren();
1403 if (action == FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS) {
1404 newLiteralNode.addChildrenToFront(arg0);
1405 }
1406 }
1407 }
1408
1409 if (newLiteralNode != null) {
1410 n.getParent().replaceChild(n, newLiteralNode);
1411 reportCodeChange();
1412 return newLiteralNode;
1413 }
1414 }
1415 }
1416 return n;
1417 }
1418
1419 private static enum FoldArrayAction {
1420 NOT_SAFE_TO_FOLD, SAFE_TO_FOLD_WITH_ARGS, SAFE_TO_FOLD_WITHOUT_ARGS}
1421
1422 /**
1423 * Checks if it is safe to fold Array() constructor into []. It can be
1424 * obviously done, if the initial constructor has either no arguments or
1425 * at least two. The remaining case may be unsafe since Array(number)
1426 * actually reserves memory for an empty array which contains number elements.
1427 */
1428 private FoldArrayAction isSafeToFoldArrayConstructor(Node arg) {
1429 FoldArrayAction action = FoldArrayAction.NOT_SAFE_TO_FOLD;
1430
1431 if (arg == null) {
1432 action = FoldArrayAction.SAFE_TO_FOLD_WITHOUT_ARGS;
1433 } else if (arg.getNext() != null) {
1434 action = FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS;
1435 } else {
1436 switch (arg.getType()) {
1437 case Token.STRING:
1438 // "Array('a')" --> "['a']"
1439 action = FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS;
1440 break;
1441 case Token.NUMBER:
1442 // "Array(0)" --> "[]"
1443 if (arg.getDouble() == 0) {
1444 action = FoldArrayAction.SAFE_TO_FOLD_WITHOUT_ARGS;
1445 }
1446 break;
1447 case Token.ARRAYLIT:
1448 // "Array([args])" --> "[[args]]"
1449 action = FoldArrayAction.SAFE_TO_FOLD_WITH_ARGS;
1450 break;
1451 default:
1452 }
1453 }
1454 return action;
1455 }
1456
1457 private Node tryFoldRegularExpressionConstructor(Node n) {
1458 Node parent = n.getParent();
1459 Node constructor = n.getFirstChild();
1460 Node pattern = constructor.getNext(); // e.g. ^foobar$
1461 Node flags = null != pattern ? pattern.getNext() : null; // e.g. gi
1462
1463 if (null == pattern || (null != flags && null != flags.getNext())) {
1464 // too few or too many arguments
1465 return n;
1466 }
1467
1468 if (// is pattern folded
1469 pattern.isString()
1470 // make sure empty pattern doesn't fold to //
1471 && !"".equals(pattern.getString())
1472
1473 // NOTE(nicksantos): Make sure that the regexp isn't longer than
1474 // 100 chars, or it blows up the regexp parser in Opera 9.2.
1475 && pattern.getString().length() < 100
1476
1477 && (null == flags || flags.isString())
1478 // don't escape patterns with Unicode escapes since Safari behaves badly
1479 // (read can't parse or crashes) on regex literals with Unicode escapes
1480 && (isEcmaScript5OrGreater()
1481 || !containsUnicodeEscape(pattern.getString()))) {
1482
1483 // Make sure that / is escaped, so that it will fit safely in /brackets/
1484 // and make sure that no LineTerminatorCharacters appear literally inside
1485 // the pattern.
1486 // pattern is a string value with \\ and similar already escaped
1487 pattern = makeForwardSlashBracketSafe(pattern);
1488
1489 Node regexLiteral;
1490 if (null == flags || "".equals(flags.getString())) {
1491 // fold to /foobar/
1492 regexLiteral = IR.regexp(pattern);
1493 } else {
1494 // fold to /foobar/gi
1495 if (!areValidRegexpFlags(flags.getString())) {
1496 report(INVALID_REGULAR_EXPRESSION_FLAGS, flags);
1497 return n;
1498 }
1499 if (!areSafeFlagsToFold(flags.getString())) {
1500 return n;
1501 }
1502 n.removeChild(flags);
1503 regexLiteral = IR.regexp(pattern, flags);
1504 }
1505
1506 parent.replaceChild(n, regexLiteral);
1507 reportCodeChange();
1508 return regexLiteral;
1509 }
1510
1511 return n;
1512 }
1513
1514 private Node reduceTrueFalse(Node n) {
1515 if (late) {
1516 Node not = IR.not(IR.number(n.isTrue() ? 0 : 1));
1517 not.copyInformationFromForTree(n);
1518 n.getParent().replaceChild(n, not);
1519 reportCodeChange();
1520 return not;
1521 }
1522 return n;
1523 }
1524
1525 private Node tryMinimizeArrayLiteral(Node n) {
1526 boolean allStrings = true;
1527 for (Node cur = n.getFirstChild(); cur != null; cur = cur.getNext()) {
1528 if (!cur.isString()) {
1529 allStrings = false;
1530 }
1531 }
1532
1533 if (allStrings) {
1534 return tryMinimizeStringArrayLiteral(n);
1535 } else {
1536 return n;
1537 }
1538 }
1539
1540 private Node tryMinimizeStringArrayLiteral(Node n) {
1541 if(!late) {
1542 return n;
1543 }
1544
1545 int numElements = n.getChildCount();
1546 // We save two bytes per element.
1547 int saving = numElements * 2 - STRING_SPLIT_OVERHEAD;
1548 if (saving <= 0) {
1549 return n;
1550 }
1551
1552 String[] strings = new String[n.getChildCount()];
1553 int idx = 0;
1554 for (Node cur = n.getFirstChild(); cur != null; cur = cur.getNext()) {
1555 strings[idx++] = cur.getString();
1556 }
1557
1558 // These delimiters are chars that appears a lot in the program therefore
1559 // probably have a small Huffman encoding.
1560 String delimiter = pickDelimiter(strings);
1561 if (delimiter != null) {
1562 String template = Joiner.on(delimiter).join(strings);
1563 Node call = IR.call(
1564 IR.getprop(
1565 IR.string(template),
1566 IR.string("split")),
1567 IR.string("" + delimiter));
1568 call.copyInformationFromForTree(n);
1569 n.getParent().replaceChild(n, call);
1570 reportCodeChange();
1571 return call;
1572 }
1573 return n;
1574 }
1575
1576 /**
1577 * Find a delimiter that does not occur in the given strings
1578 * @param strings The strings that must be separated.
1579 * @return a delimiter string or null
1580 */
1581 private String pickDelimiter(String[] strings) {
1582 boolean allLength1 = true;
1583 for (String s : strings) {
1584 if (s.length() != 1) {
1585 allLength1 = false;
1586 break;
1587 }
1588 }
1589
1590 if (allLength1) {
1591 return "";
1592 }
1593
1594 String[] delimiters = new String[]{" ", ";", ",", "{", "}", null};
1595 int i = 0;
1596 NEXT_DELIMITER: for (;delimiters[i] != null; i++) {
1597 for (String cur : strings) {
1598 if (cur.contains(delimiters[i])) {
1599 continue NEXT_DELIMITER;
1600 }
1601 }
1602 break;
1603 }
1604 return delimiters[i];
1605 }
1606
1607 private static final Pattern REGEXP_FLAGS_RE = Pattern.compile("^[gmi]*$");
1608
1609 /**
1610 * are the given flags valid regular expression flags?
1611 * JavaScript recognizes several suffix flags for regular expressions,
1612 * 'g' - global replace, 'i' - case insensitive, 'm' - multi-line.
1613 * They are case insensitive, and JavaScript does not recognize the extended
1614 * syntax mode, single-line mode, or expression replacement mode from Perl 5.
1615 */
1616 private static boolean areValidRegexpFlags(String flags) {
1617 return REGEXP_FLAGS_RE.matcher(flags).matches();
1618 }
1619
1620 /**
1621 * are the given flags safe to fold?
1622 * We don't fold the regular expression if global ('g') flag is on,
1623 * because in this case it isn't really a constant: its 'lastIndex'
1624 * property contains the state of last execution, so replacing
1625 * 'new RegExp('foobar','g')' with '/foobar/g' may change the behavior of
1626 * the program if the RegExp is used inside a loop, for example.
1627 * <p>
1628 * ECMAScript 5 explicitly disallows pooling of regular expression literals so
1629 * in ECMAScript 5, {@code /foo/g} and {@code new RegExp('foo', 'g')} are
1630 * equivalent.
1631 * From section 7.8.5:
1632 * "Then each time the literal is evaluated, a new object is created as if by
1633 * the expression new RegExp(Pattern, Flags) where RegExp is the standard
1634 * built-in constructor with that name."
1635 */
1636 private boolean areSafeFlagsToFold(String flags) {
1637 return isEcmaScript5OrGreater() || flags.indexOf('g') < 0;
1638 }
1639
1640 /**
1641 * returns a string node that can safely be rendered inside /brackets/.
1642 */
1643 private static Node makeForwardSlashBracketSafe(Node n) {
1644 String s = n.getString();
1645 // sb contains everything in s[0:pos]
1646 StringBuilder sb = null;
1647 int pos = 0;
1648 boolean isEscaped = false, inCharset = false;
1649 for (int i = 0; i < s.length(); ++i) {
1650 char ch = s.charAt(i);
1651 switch (ch) {
1652 case '\\':
1653 isEscaped = !isEscaped;
1654 continue;
1655 case '/':
1656 // Escape a literal forward slash if it is not already escaped and is
1657 // not inside a character set.
1658 // new RegExp('/') -> /\//
1659 // but the following do not need extra escaping
1660 // new RegExp('\\/') -> /\//
1661 // new RegExp('[/]') -> /[/]/
1662 if (!isEscaped && !inCharset) {
1663 if (null == sb) { sb = new StringBuilder(s.length() + 16); }
1664 sb.append(s, pos, i).append('\\');
1665 pos = i;
1666 }
1667 break;
1668 case '[':
1669 if (!isEscaped) {
1670 inCharset = true;
1671 }
1672 break;
1673 case ']':
1674 if (!isEscaped) {
1675 inCharset = false;
1676 }
1677 break;
1678 case '\r': case '\n': case '\u2028': case '\u2029':
1679 // LineTerminators cannot appear raw inside a regular
1680 // expression literal.
1681 // They can't appear legally in a quoted string, but when
1682 // the quoted string from
1683 // new RegExp('\n')
1684 // reaches here, the quoting has been removed.
1685 // Requote just these code-points.
1686 if (null == sb) { sb = new StringBuilder(s.length() + 16); }
1687 if (isEscaped) {
1688 sb.append(s, pos, i - 1);
1689 } else {
1690 sb.append(s, pos, i);
1691 }
1692 switch (ch) {
1693 case '\r': sb.append("\\r"); break;
1694 case '\n': sb.append("\\n"); break;
1695 case '\u2028': sb.append("\\u2028"); break;
1696 case '\u2029': sb.append("\\u2029"); break;
1697 }
1698 pos = i + 1;
1699 break;
1700 }
1701 isEscaped = false;
1702 }
1703
1704 if (null == sb) { return n.cloneTree(); }
1705
1706 sb.append(s, pos, s.length());
1707 return IR.string(sb.toString()).srcref(n);
1708 }
1709
1710 /**
1711 * true if the JavaScript string would contain a Unicode escape when written
1712 * out as the body of a regular expression literal.
1713 */
1714 static boolean containsUnicodeEscape(String s) {
1715 String esc = REGEXP_ESCAPER.regexpEscape(s);
1716 for (int i = -1; (i = esc.indexOf("\\u", i + 1)) >= 0;) {
1717 int nSlashes = 0;
1718 while (i - nSlashes > 0 && '\\' == esc.charAt(i - nSlashes - 1)) {
1719 ++nSlashes;
1720 }
1721 // if there are an even number of slashes before the \ u then it is a
1722 // Unicode literal.
1723 if (0 == (nSlashes & 1)) { return true; }
1724 }
1725 return false;
1726 }
1727 }